diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae9ce91 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +sm_* +.*/ +scripting_ext/ +!scripting/include/guesswho/* +!scripting/include/feedthetrolls +!scripting/include/hideandseek +!scripting/include/guessswho/* +!scripting/hideandseek.sp +!scripting/guessswho.sp +!scripting/sm_namespamblock.sp +!plugins/sm_namespamblock.smx +.push.settings.jsonc* +template.config.js +scripting/sm_give.sp +scripting/include/steamtools.inc +scripting/L4D2Testing.sp +plugins/L4D2Testing.smx +scripting/cancer.sp +plugins/sm_give.smx +plugins/l4d2_stats_recorder.smx +scripting/l4d2_stats_recorder.sp +scripting/include/smlib.inc +scripting/l4d2_custom.sp +plugins/l4d2_custom.smx +plugins/disable_cameras.smx +plugins/l4d_esfp.smx +plugins/customstatus.smx +scripting/l4d_esfp.sp +scripting/customstatus.sp +plugins/ssh.smx +scripting/include/ssh.inc +scripting/ssh.sp +scripting/l4d2_witch_force_attack_cmd.sp +l4d2_stats_plugin/ +data \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9f2fb35 --- /dev/null +++ b/README.md @@ -0,0 +1,458 @@ +# sourcemod-plugins +This is a collection of sourcemod plugins, most are used on my servers. The majority of the plugins are created by me, but some are modifications of other plugins. +Some of the plugins / changes are very specific, but may be useful to someone. + +Not always the latest versions. If you have any interest with a plugin, I can make sure to upload the latest. + +Useful things: +1. Netprop viewer https://jackz.me/netprops/l4d2 + +## Plugin List + +### Created by Me +* #### CSGO + * [csgo-knifehp](#csgo-knifehp) - First plugin I've made + * [CSGOTroll](#csgotroll) - Abandoned friend trolling plugin +* #### L4D2 + * [l4d2-manual-director](#l4d2-manual-director) - Spawn specials on demand via director or at your cursor + * [l4d2-info-cmd](#l4d2-info-cmd) - Prints a full state of all survivors, useful for external information + * [AutoWarpBot](#autowarpbot) - Abandoned + * [L4D2FFKickProtection](#l4d2ffkickprotection) - Prevents players being voted off from friendly firing and prevents admins from being kicked + * [l4d2_avoid_minigun](#l4d2_avoid_minigun) - Makes bots avoid being infront of any in-use miniguns. Useful for spawned miniguns + * [l4d2_ai_minigun](#l4d2_ai_minigun) - Based off [Silver's Survivor Bot Holdout plugin](https://forums.alliedmods.net/showthread.php?p=1741099), allows you to spawn survivor bots but with no limit. + * [L4D2Tools](#l4d2tools) - A collection of utilities, mostly just used with [l4d_survivor_identity_fix](#l4d_survivor_identity_fix) and the /model command + * [l4d2_swarm](#l4d2_swarm) - Uses vscript RushVictim to make all zombies target a player, like a more subtle vomitplayer + * [l4d2_feedthetrolls](#l4d2_feedthetrolls) - Full collection of tools to troll your friends or troll the trolls + * [l4d2_autobotcrown](#l4d2_autobotcrown) - Bots will auto crown + * [l4d2_extraplayeritems](#l4d2_extraplayeritems) - Includes tons of utilities for 5+ games, such as 5+ player hud, extra kit / item spawning, and more + * [l4d2_population_control](#l4d2_population_control) - Allows you to custom the type of zombies that spawn (% of clowns, mud men, etc..) + * [globalbans](#globalbans) - Bans synced via mysql, way lighter than the sourcebans cesspool. + * [l4d2_rollback](#l4d2_rollback) - Abandoned and broken, but makes periodic backup of all player's items + * [l4d2_autorestart](#l4d2_autorestart) - Restarts server if it's been on for a certain uptime or when empty with just bots. + * [l4d2_TKStopper](#l4d2_tkstopper) - All the teamkiller and shitty-aim player punishments. Auto increasing reverse ff and teamkill detection + * [l4d2_crescendo_control](#l4d2_crescendo_control) - Prevents players from running far ahead and starting events, and logs button presses + * [l4d2_vocalize_control](#l4d2_vocalize_control) - Allows you to locally mute someone from vocalizing + * [l4d2_guesswho](#l4d2_guesswho) - Garry's Mod's Guess Who in l4d2, inspired by hide and seek + * [l4d2_hideandseek](#l4d2_hideandseek) - An enhancement to the base hide and seek mutation + * [l4d2_hats](#l4d2_hats) - Entity Hats & Entity editing + * [l4d2_prophunt](#l4d2_prophunt) - Garry's Mod inspired prop hunt, inspired by hide and seek + * [sm_namespamblock](#sm_namespamblock) - Basic plugin that bans players if they change their name in rapid succession + * [l4d2-stats-plugin](https://github.com/jackzmc/l4d2-stats-plugin) - Custom stats recorder, see https://stats.jackz.me + * [l4d2-ai-tweaks](#l4d2_ai_tweaks) - Very minor tweaks to survivor bots' behavior + +### Modified Others +* [200IQBots_FlyYouFools](#200iqbots_flyyoufools) - Improved code to make it support multiple tanks and work better +* [l4d_survivor_identity_fix](#l4d_survivor_identity_fix) - Use with [L4D2Tools](#l4d2tools) to change models, some fixes +* [BetterWitchAvoidance](#betterwitchavoidance) +* l4d_anti_rush - Modified plugin to add a forward, so other plugins (like feedthetrolls) can do something. In addition, use highest flow value achieved for players (fixes issue when admins go back and players who haven't moved suddenly get punished) +* [l4d2_sb_fix](#l4d2_sb_fix) - Updated to 1.11 & latest sourcepawn syntax & removed the FCVAR_NOTIFY from all cvars (why is that added?) +* GrabEnt - Improved version that prevents moving certain entities (such as invisual walls, ragdolls, etc) and improved some code + +## Dependencies +This is a list of most common dependencies, independent if they are used for a certain plugin. +Check the plugin info for an exact list. + +* [Left 4 Dhooks Direct](https://forums.alliedmods.net/showthread.php?t=321696) +* [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) + +### Development Dependencies +Most L4D2 plugins use my own include: jutils.inc, it's provided in this repo. +Some do require newer includes for my modified plugins (such as my improved survivor identity fix) + +## Descriptions + +### csgo-knifehp +On knife kill, gives the player 100 HP (configurable) +* **Convars:** + * `knifehp_enable <0/1>` - Enable regaining health on knife kill + * `knifehp_max_health <#>` - Maximum health to set an attacker to + * `knifehp_amount <#>` - Amount of health to give attacker + + +### l4d2-manual-director +~~Probably going to be posted publicly sometime.~~ Allows you to spawn specials on cursor, or via director, forcefully, bypassing limits +* **Convars:** + * `manual_director_version|mandirector_version` - ... gets version + * `mandirector_notify_spawn <1/0>` - Should spawning specials notify on use? + * `mandirector_announce_level <0/1/2/3>` - Announcement types. 0 - None, 1 - Only bosses, 2 - Only specials+, 3 - Everything + * `mandirector_enable_tank <0/1>` - Should tanks be allowed to be spawned? + * `mandirector_enable_witch <0/1>` - Should witches be allowed to be spawned? + * `mandirector_enable_mob <0/1>` - Should mobs be allowed to be spawned +* **Commands:** + * `sm_spawnspecial [amount]` - Spawn a special via director + * `sm_forcespecial [amount]` - Force spawn a special via director, bypassing spawn limits + * `sm_forcecursor [amount]` - Force spawn a special at cursor, bypassing spawn limits + * `sm_cursormenu` - Show the spawn menu for cursor spawning + * `sm_specialmenu` - Show the spawn menu for director spawning + * `sm_directormenu` (Same as sm_specialmenu for now) + + +### l4d2-info-cmd +Technically 'l4d2 game info', haven't changed name. Just prints general information, used for a project +* **Commands:** + * `sm_gameinfo` +* Example Response: + ``` + >map,diff,mode,tempoState,totalSeconds + c1m1_hotel,1,coop,3,1622 + >id,name,bot,health,status,throwSlot,kitSlot,pillSlot,survivorType,velocity,primaryWpn,secondaryWpn + 1,Jackz,0,80,alive,0,,first_aid_kit,,Bill,0,,pistol + 3,Zoey,1,75,alive,0,,first_aid_kit,,Zoey,0,,pistol + 4,Francis,1,76,alive,0,,,,Francis,0,,pistol + 5,Louis,1,90,alive,0,,first_aid_kit,,Louis,0,,pistol + ``` + + +### AutoWarpBot +Simple l4d2 plugin that will auto teleport bots to checkpoint once all real players have reached the saferoom. +Doesn't really work well. Abandoned. + + +### 200IQBots_FlyYouFools +Updated version of ConnerRia's plugin. Improves bots avoidance of tanks. Change from original is updated sourcepawn syntax, some optimizations/cleanup, and fixes such as bots avoiding tank that has not been activated, or not escaping in vehicle due to presence of tank. +Latest version now has support for multiple tanks, the bots might not avoid them as effectively as they would with one tank but they still try their best. +* **Convars:** + * `FlyYouFools_Version` - Prints the version of plugin + + +### BetterWitchAvoidance +Inspired by the 200IQBots_FlyYouFools. Bots avoid witch if its over 40% anger when close, or a little bigger range at 60% or more. Not recommended to use, normal behavior seems fine. + + +### L4D2FFKickProtection +Simple plugin that prevents a player that is being vote-kicked from doing any ff damage to teammates. +It also prevents vote kicking of admins, instead will notify admins. +It also makes any vote kicks created by an admin to instantly be accepted by all players + +* **Convars:** + * `sm_votekick_force_threshold <#>` - The threshold of damage where the offending player is just immediately kicked. 0 -> Any attempted damage, -1 -> No auto kick. + + +### CSGOTroll +Another joke plugin, with it configured, a victim will have a % chance their shots just fail. This can be for the AWP or all weapons at least for now. +* **Convars:** + * `troll_enable <0/1>` - Enable troll. 0 -> OFF, 1 -> Shots + * `troll_shot_fail_percentage <0.0-1.0>` - percentage float (0.0 to 1.0) chance that victims' shots fail + * `troll_targets ` - comma separated list of steamid64 targets (ex: STEAM_0:0:75141700) + * `troll_shot_mode <0/1>` - 0 -> ALL Weapons, 1 -> AWP + + +### l4d2_avoid_minigun +Makes the bots avoid standing in front of or on top of the player that is using a minigun. It checks every 2.0 seconds if they are in the way, then forces them to move to behind you. There is no configuration, all automatic. + + +### l4d2_ai_minigun +Requires: [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) + +Spawn the holdout bots used in the passing. This supports all 8 characters, including with the minigun. They can spawn with any weapon or default to ak47. + +**Notes:** +* The minigun holdout bot has to internally be Louis, so it will be Louis making sounds, with whatever model specified being shown. This doesn't apply for normal holdout bot. +* \ can be "bill" or their numeric id (4). + +Code modified from https://forums.alliedmods.net/showthread.php?p=1741099 + +* **Commands:** + * `sm_ai_minigun ` - Spawns an ai bot with minigun infront of wherever you are looking. Can also use numbers (0-7). + * `sm_ai_holdout [wpn]` - Spawns a normal ai holdout bot (no minigun), with any weapon w/ laser sight (default is ak). + * `sm_ai_remove_far` - Removes any holdout or minigun bots that are 750 units or more from any player. + + +### L4D2Tools +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) +* [Modified L4D Survivor Identity Fix](#l4d_survivor_identity_fix) + +A collection of small tools: + * Notification of when someone picks up laser sights (only the first user, includes bots), + * Record time it takes for a finale or gauntlet run to be completed. + * Record the amount of friendly fire damage done + * Set the survivor models of any survivor with updated [l4d_survivor_identity_fix](#l4d_survivor_identity_fix) + * Automatically returns melee weapons that an idle bot dropped once no longer idle + * Automatically make players go idle when ping spikes + * Slowly kill any zombies attacking survivor bot's blind spots (Fixes brain dead bots stuck taking damage and not killing them) + +* **Convars:** + * `sm_laser_use_notice <0/1>` - Enable notification of when a laser box was used first + * `sm_time_finale <0/1/2>` - Record the time it takes to complete finale. 0 -> OFF, 1 -> Gauntlets Only, 2 -> All finales + * `sm_ff_notice <0/1/2>` - Should we record FF damages? 0: OFF, 1: To chat, 2: To HUD text. + * `sm_autoidle_ping_max <30.0...>` - "The highest ping a player can have until they will automatically go idle.\n0=OFF, Min is 30 +* **Commands:** + * `sm_model ` - Sets the survivor model of the target player(s). 'character' is name or ID of character. + * `sm_surv ` - Sets the m_survivorCharacter prop only of the target player(s). 'character' is name or ID of character. + + +### l4d2_swarm +This plugin is used to counter trolls and otherwise bad players. It simply uses the new script function RushVictim() to make all zombies in X radius attack Y target. It's that simple. + +This really only affects wandering zombies, mobs and panic events, but it may work slightly when bile or pipes are thrown. It does not and can't change the targets of zombies. + +* **Convars:** + * `sm_swarm_default_range <20-Infinity>` - The default range for commands & menus. Defaults to 7,500 +* **Commands:** + * `sm_swarm [player] [range]` - Swarm a player, or random if none." + * Aliases: `sm_rush` + * `sm_rushmenu` - Opens a menu to quickly rush any player. Can be bound to a key to quickly rush as well + * Aliases: `sm_rmenu` + * `sm_swarmtoggle [range]` - Will continuously run the swarm method on the player at the range. Use the command again or type "disable" for player to disable. Switching players will not disable, just switches target. + * Aliases: `sm_rushtoggle`, `sm_rt` + * `sm_rushtogglemenu` - Will open a menu to quickly select a player to continuously rush. + * Aliases: `sm_rtmenu` + + +### l4d2_feedthetrolls +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* (Optional) [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) +* (Optional) [Actions](https://forums.alliedmods.net/showthread.php?t=336374) +* (Optional) [Modified L4D Antirush](#l4d_anti_rush) + +This plugin allows you to enact certain troll modes on any player, some are subtle some are less so. Either way, it works great to deal with a rusher, an asshole or even your friends. + +See updated list of trolls and their descriptions: +https://admin.jackz.me/docs/ftt + +* **Convars:** + * `sm_ftt_autopunish_mode <#>` - (Not used, WIP) Sets the modes that auto punish will activate for. 1 -> Early crescendo activations + * `sm_ftt_autopunish_action <#>` - Which actions will autopunish activate? Add bits together. 0=None, 1=TankMagnet 2=SpecialMagnet 4=Swarm 8=VomitPlayer + * `sm_ftt_autopunish_expires <0...>` - How many minutes (in gameticks) until autopunish trolls are removed. 0 for never. +* **Commands:** + * `sm_fta [player]` - The main command, opens a menu to select a troll to apply, with modifiers and flags + * `sm_ftr [player]` - Removes all active trolls from a player + * `sm_ftc [player]` - Opens a menu to select a combo of trolls + * `sm_ftl` - Lists all players that have a mode applied. + * `sm_ftm` - Lists all troll options & their descriptions + * `sm_mark` - Toggles marking a player to be banned when they fully disconnect + * `sm_insta [player] [special]` - (No arguments opens menu) - Spawns a special via the director that will only target the victim + * `sm_inface [player] [special]` - Identical to above, but special will be spawned as close as possible to survivor. Boomers auto explode, jockeys on their head, etc. + * `sm_bots_attack [target health]` - Slightly broken, but makes all bots shoot at player until they hit X health or a timeout is reached. Turn on `sb_friendlyfire` for it to be effective. + * `sm_stagger ` - Makes a player stagger, shortcut to the Stagger troll + * `sm_witch_attack ` - Makes all witches agro on the player + * `sm_scharge [timeout seconds]` - Will wait till there's no obstructions and players in the way, then spawns a charger behind them to charge them. + * `sm_healbots [# bots or 0 default]` - Makes n amount of bots chase a player down to heal them. Won't stop until they are healed, they die, or you run command again. + * `sm_csplat - Shortcut to Car Splat. Spawns car in top/front/back that hits the player` + +### l4d2_autobotcrown +Makes any suitable bot (> 40 hp, has shotgun) automatically crown a witch. Supports multiple bots and witches, but only one bot can crown one witch at a time. Plugin is disabled in realism, and is really on suitable for coop or versus. Even works with idle players. + +Bots do sometimes miss, but sometimes still manage to kill witch. They also don't care if there is danger in the way (fire, acid, angry witch). + +* **Convars:** + * `l4d2_autocrown_allowed_difficulty ` - The difficulties the plugin is active on. 1=Easy, 2=Normal 4=Advanced 8=Expert. Add numbers together. + * `l4d2_autocrown_modes_tog ` - (Not implemented) - Turn on the plugin in these game modes. 0=All, 1=Coop, 2=Survival, 4=Versus, 8=Scavenge. Add numbers together + + +### l4d2_extraplayeritems +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* [L4D Info Editor](https://forums.alliedmods.net/showthread.php?p=2614626) +* (Development dependency) Updated l4d2_weapon_stocks.inc + +A well rounded tool that provides extra utilities to a 5+ co-op campaign. + +Features: +* Automatically giving extra kits for each extra player in saferooms +* Increasing item count for items randomly depending on player count +* Fix same-models survivors having to fight over ammo pack usage +* Automatically lock the first saferoom door for every chapter, until a threshold of players or time has passed +* Includes a HUD that shows all the survivors and their items, and optionally their ping (breaks randomly not sure why) +* Includes a new 5+ special spawning director +* Spawn an extra tank that scales with player count + +* **Convars:** + * `epi_item_chance` - The base chance (multiplied by player count) of an extra item being spawned. Default: 0.056 + * `epi_kitmode` - Decides how extra kits should be added. Default is 0 + * 0 -> Overwrites previous extra kits + * 1 -> Adds onto previous extra kits + * `epi_updateminplayers` - Should the plugin update abm's cvar min_players convar to the player count? (0 no, 1 yes) + * `epi_doorunlock_percent` - The percent of players that need to be loaded in before saferoom door is opened. + * Default is 0.8, set to 0 to disable door locking + * `epi_doorunlock_wait` - How many seconds after to unlock saferoom door. 0 to disable timer + * `epi_doorunlock_open` - Controls when or if the door automatically opens after unlocked. Add bits together. + * 0 = Never, 1 = When timer expires, 2 = When all players loaded in + * `epi_hudstate` - Controls when the extra player hud shows. + * 0 = Never, 1 = When 5+ players, 2 = Always on + * `epi_sp_spawning` - Determines what specials are spawned. Add bits together. + * 1 = Specials, 2 = Witches, 4 = Tanks + * `epi_enabled` - When should epi be enabled? + * 0 = OFF, 1 = Only when 5+ and official map, 2 = Only when 5+, 3 = Always + * `epi_tank_chunkhp` - The amount of health to add to a tank per extra player + * `epi_gamemodes` - Comma separated list of allowed gamemodes. + + +### l4d_survivor_identity_fix +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) + +A fork of [Survivor Identity Fix plugin](https://forums.alliedmods.net/showthread.php?t=280539) that adds support for other plugins to update the model cache. This is used by [L4D2Tools](#L4D2Tools) to update the identity when someone changes their model with `sm_model`. It also will clear the memory of model when a player disconnects entirely or on a new map. + +In addition, has a fix for the passing finale, and will automatically temporarily change L4D characters to L4D2 until finale starts preventing game messing up their characters. + + +### l4d2_population_control +Allows you to set the chances that a common spawns as a certain uncommon. The order of the cvars is the order the percentages are ran +* **Convars:** + * `l4d2_population_chance <0.0-1.0>` Default: 1.0, the chance that the code runs on a spawn (basically if 0.0, none of the % chances will run for all types) + * `l4d2_population_clowns <0.0-1.0>` The chance that on a common spawn that the special will be a clown. + * `l4d2_population_mud <0.0-1.0>` The chance that on a common spawn that the special will be a mud common. + * `l4d2_population_ceda <0.0-1.0>` The chance that on a common spawn that the special will be a ceda common. + * `l4d2_population_worker <0.0-1.0>` The chance that on a common spawn that the special will be a worker common. + * `l4d2_population_riot <0.0-1.0>` The chance that on a common spawn that the special will be a riot common. + * `l4d2_population_jimmy <0.0-1.0>` The chance that on a common spawn that the special will be a jimmy common + * `l4d2_population_common <#>` - The maximum amount of commons that can spawn. + * 0 will turn off, + * value > 0 will enforce the exact value + * value < 0 will enforce z_common_limit + | value | +* **Commands:** + * `sm_populations` or `sm_population_list` - Lists all the cvar values + +### globalbans +This plugin will store bans in a database and read from it on connect. This allows you to easily have bans global between servers. +It will automatically intercept any ban that calls OnBanIdentity or OnBanClient (so sm_ban will work normally) +Note: All admin players are ignored + +* **Convars:** + * `sm_globalbans_kick_type <0/1/2>` + * 0 = Do not kick, just notify + * 1 = Kick if banned + * 2 = Kick if cannot reach database + + +### l4d2_rollback +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) + +An idea that you can either manually or have events (friendly fire, new player joining) trigger saving all the player's states. Then if say, a troll comes and kills you and/or incaps your team, you can just quick restore to exactly the point you were at with the same items, health, etc. + +Currently **abandoned.** + +Currently auto triggers: + +1. On any recent friendly fire (only triggers once per 100 game ticks) +2. Any new player joins (only triggers once per 100 game ticks) + +* **Commands:** + * `sm_save` - Initiates a manual save of all player's states + * `sm_state` - Lists all the states + * `sm_restore ` - Restores the selected player's state. @all for all + +### l4d2_autorestart +Plugin that automatically restarts server when the server is NOT hibernating, with bots around and no players. +This fixes an issue with custom maps that force sb_all_bot_game to 1 and disable hibernation. + +### l4d2_TKStopper +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) + +Plugin that prevents team killers by checking multiple criterias. Default system is as: +Any survivor that attacks another survivor + +1. If within first 2 minutes of joining, no damage is dealt to either victim or attacker. This prevents the next person to join being punished. +2. If during the finale vehicle arrival, they do 0x damage to victim and take 2x reverse friendly fire +3. If neither #1 or #2, both the victim and the attacker take 1/2 the original damage +4. If victim is in a saferoom, no damage is dealt. + +See https://admin.jackz.me/docs/plugins#tkstopper for some more implementation information + + +During any of the above three conditions, if they deal (or attempt to deal) over 75 HP in 15 seconds (configurable) they will be instantly banned for a set period of time (60 minutes). If they are for sure a team killer, it can be extended to a permanent ban. + +* **Cvars:** + * `l4d2_tk_forgiveness_time <#>` - The minimum amount of seconds to pass (in seconds) where a player's previous accumulated FF is forgive. Default is 15s + * `l4d2_tk_bantime` - How long in minutes should a player be banned for? 0 for permanently. Default is 60 + * `l4d2_tk_ban_ff_threshold` - How much damage does a player need to do before being instantly banned. Default 75 HP + * `l4d2_tk_ban_join_time` - Upto how many minutes should any new player's FF be ignored. Default is 2 Minutes + + + +### l4d2_crescendo_control +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) + +This plugin prevents the activation of buttons ahead of the team. It will prevent players from starting crescendos (and some small other activities as a side effect) until a certain threshold of the team has reached the area. + +_This plugin is not perfect, sometimes it may trigger early, or not trigger at all depending on the map. Sometimes you need to as admins, move forward to allow non-admins to activate events._ + + +* **Cvars:** + * `l4d2_crescendo_percent` + * `l4d2_crescendo_range` + + +### l4d2_vocalize_control +A very small plugin that simply allows a player to mute another player's vocalizations only for them. + +* **Commands:** + * `sm_vgag ` - Vocalize gag or ungags selected player(s) for the command activator only + +### l4d2_sb_fix +A fork of https://forums.alliedmods.net/showthread.php?p=2757330 +- Updated to latest sourcepawn syntax (now 1.11) +- Fixed some stupid things (all cvars being FCVAR_NOTIFY) + + +### l4d2_hideandseek +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) + +A sourcemod extenstion of the vscript gamemode (https://steamcommunity.com/sharedfiles/filedetails/?id=2467133506) +- Player blockers, portals, and props to change and control the maps +- Optional climbable infected ladders, and heart beat when seeker nearby +- Some quality of life (winner messages, change seeker mid game, change map time) +- and a lot more + + +### l4d2_guesswho +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) + +Based off gmod guess who game, find the real players amongst a group of bots. +All logic is written in this plugin, thus is required. +Vscript required for hud & mutation + +Gamemode: https://steamcommunity.com/sharedfiles/filedetails/?id=2823719841 + +Requires l4dtoolz and left4dhooks, and optionally skip intro cutscene + +### l4d2_prophunt +Requires: +* [Left4Dhooks](https://forums.alliedmods.net/showthread.php?t=321696) +* [Scene Processor](https://forums.alliedmods.net/showthread.php?p=2147410) + +Based off gmod prop hunt, find the real players amongst a group of props. +All logic is written in this plugin, thus is required. +Vscript required for hud & mutation + +* Gamemode: https://steamcommunity.com/sharedfiles/filedetails/?id=2850550331 + +* Demo Map: https://steamcommunity.com/sharedfiles/filedetails/?id=2855027013 (makes most prop_static -> prop_dynamic) + +Requires l4dtoolz and left4dhooks, and optionally skip intro cutscene + +### l4d2_hats + +Lets you hat any entity (has blacklist support), including players. Yeet, place, restore, and more with the hats. + +**Be warned, this can cause server crashes.** It's a lot stable now, but some features are disabled by default (reverse hats + visible hats) as they caused too many crashes. Most crashes are caused by hats and ladders, but default settings prevent it. + +It also includes an entity editor and invisible wall creator. View the file to see commands and cvars + +### sm_namespamblock + +If a user changes their name 3 times within 10 seconds, they will be temp banned for 10 minutes. +Requires recompile to change. + +* **Commands:** + * `status2` - Shitty name, but shows all non-admin players, sorted by last joined ascending (up top). Shows steamid and the first name they joined the server as + * `sm_status2` - Same command, but allows /status2 in chat + +### l4d2_ai_tweaks + +Simply, prevents an idle bot (that is a bot for an idle player) from healing another player unless: +1. The target is black and white +2. The player has been idle for over **ALLOW_HEALING_MIN_IDLE_TIME** (a \#define) seconds (default is 3 minutes) + +Requires recompile to change. diff --git a/data/ftt_phrases.cfg b/data/ftt_phrases.cfg new file mode 100644 index 0000000..cb42447 --- /dev/null +++ b/data/ftt_phrases.cfg @@ -0,0 +1,251 @@ +"Phrases" +{ + "_Full Message Phrases" + { + "1" "I peed my pants" + "2" "I love peas" + "3" "I sure wish I was a zombie right now" + "4" "mexico menu" + "5" "Admin respect is essential" + "6" "I respect the admins of this server" + "7" "ok" + "8" "I think that you are all awesome" + "9" "You are all doing great!" + "10" "Honestly, I'm jealous of you all" + "11" "Pickles" + "12" "A chair is a piece of furniture with a raised surface supported by legs, commonly used to seat a single person." + "13" "meow" + "14" "honk" + "15" "Chairs are supported most often by four legs, and have a back; however, a chair can have three legs, or can have a different shape." + "16" "It's not admin abuse when the point of being an admin is to abuse" + "17" "Many are called but few are chosen" + "18" "Out of sight, out of mind" + "19" "Thou shalt not kill" + "20" "Life's not all beer and skittles" + "21" "Dollars to doughnuts" + "22" "I'll go to the foot of our stairs" + "23" "I could go for a BBQ bacon burger, and a large order of fries, and an orange soda with no ice, and a piece of hot apple pie." + "24" "I'll have two number 9s, a number 9 large, a number 6 with extra dip, a number 7, two number 45s, one with cheese, and a large soda." + "25" "Lightning Never Strikes The Same Place Twice" + "26" "In peace, vigilance. In war, victory. In death, sacrifice." + "27" "Slotted spoons don't hold much soup" + "28" "Have you ever been on a shrimp boat?" + "29" "I am a pretty pink princess" + "30" "Jimmy crack corn, and I don't care" + "31" "Penquins are practically chickens" + "32" "I don't know about you, but I find fire very dramatic!" + "33" "gabe newell" + "34" "9 years of development" + "35" "nothing worse than a case of the fanny fungus" + "36" "Sometimes, I dream about cheese." + "37" "STRIDER!!!" + "38" "I thought that he was invinsible!" + "39" "Yeah, Canadians are DICKS." + "40" "I ever tell you about the time Keith and I made fireworks?" + "41" "Hey. We need to talk. I've got a proposition that might be mutually advantageous." + "42" "Now, I didn't know shit about chemistry, but Keith figured Gasoline burns, doesn't it?" + "43" "Heh, third-degree burns on 95 percent of his body. Man, people in the next city over were calling to complain about the smell of burning skin" + "44" "Yahoo!" + "45" "I have possibly made an oopsie in my pants" + "46" "DAVY!" + "47" "I hate myself" + "48" "I'm not a fan of you" + "49" "MOMMY!" + "50" "Barry later returns to express his gratitude to Vanessa, breaking the sacred rule that bees are not to communicate with humans." + "51" "Barry becomes a member of the Pollen Jocks, and they fly off to a flower patch. Armed with the pollen of the last flowers," + "52" "According to all known laws of aviation, there is no way a bee should be able to fly. Its wings are too small to get its fat little body off the ground. The bee, of course, flies anyway" + "53" "Barry, I'm going to make it with the power of my mind. With a little help from my friends. See if you can't get them to join in." + "54" "Please exit your residency by 8:59 PM, or we will be forced to take legal" + "55" "Ooh, black and yellow! Let's shake it up a little." + "56" "Yellow, black. Yellow, black. Yellow, black. Yellow, black." + "57" "because bees don't care what humans think is impossible." + "58" "No i wanna help please" + "59" "thankls guy youre super good at the game :)" + "60" "everything french people do is not special." + "61" "i bet rats in nyc cook the food all the time but nobody gives a shit cause they’re not french." + "62" "NOT FAIR! NOT FAIR!" + "63" "wahhhhhhhhhhhhhhh" + "64" "i stuffed shrimp inside of me once" + "65" "I stick fireworks up my ass so when i poop its a real explosion" + "66" "I ordered a hooker online once, she had three legs." + "67" "i like to breastfeed my cat on flights" + "68" "I swear im just above the rest" + "69" "I find it pretty hard to find love" + "70" "Seeing my team sitting back while i deal with the horde" + "71" "I love the dick sucking buisness too" + "72" "Until you finally wake up and realize that i was right" + } + "fuck" + { + "1" "fudge" + "2" "mars bar" + "3" "fiddlestick" + "4" "fiddle" + "5" "ok" + "6" "i love" + } + "shit" + { + "1" "oopsie" + "2" "ok" + "3" "woopsie" + "4" "ope" + } + "nigger" + { + "1" "nice lady" + "2" "friendly person" + "3" "ok" + "4" "honk" + "5" "my mom" + "6" "my dad" + "7" "my brother" + "8" "my sister" + } + "whore" + { + "1" "lady who I respect" + "2" "respectable woman" + "3" "ok" + } + "cunt" + { + "1" "pickle" + "2" "pineapple" + "3" "ok" + } + "bitch" + { + "1" "my dog" + "2" "their dog" + "3" "your dog" + "4" "our dog" + } + "ass" + { + "1" "has" + "2" "caboose" + "3" "fanny pants" + } + "salty" + { + "1" "peppery" + "2" "sweet" + "3" "honey" + } + "dead" + { + "1" "alive" + } + "alive" + { + "1" "dead" + } + "zombie" + { + "1" "shrimp" + "2" "pineapple" + } + "boomer" + { + "1" "hunter" + "2" "smoker" + "3" "jockey" + "4" "charger" + "5" "witch" + "6" "tank" + "7" "spitter" + } + "smoker" + { + "1" "hunter" + "2" "boomer" + "3" "jockey" + "4" "charger" + "5" "witch" + "6" "tank" + "7" "spitter" + } + "hunter" + { + "1" "boomer" + "2" "smoker" + "3" "jockey" + "4" "charger" + "5" "witch" + "6" "tank" + "7" "spitter" + } + "jockey" + { + "1" "hunter" + "2" "smoker" + "3" "boomer" + "4" "charger" + "5" "witch" + "6" "tank" + "7" "spitter" + } + "spitter" + { + "1" "hunter" + "2" "smoker" + "3" "jockey" + "4" "charger" + "5" "witch" + "6" "tank" + "7" "boomer" + } + "charger" + { + "1" "hunter" + "2" "smoker" + "3" "jockey" + "4" "boomer" + "5" "witch" + "6" "tank" + "7" "spitter" + } + "witch" + { + "1" "hunter" + "2" "smoker" + "3" "jockey" + "4" "charger" + "5" "boomer" + "6" "tank" + "7" "spitter" + } + "tank" + { + "1" "hunter" + "2" "smoker" + "3" "jockey" + "4" "charger" + "5" "witch" + "6" "boomer" + "7" "spitter" + } + "dickhead" + { + "1" "poopie" + "2" "quack" + "3" "big brain" + "4" "cactus" + "5" "friend" + "6" "mom" + "7" "mommie" + } + "cock" + { + "1" "foot" + } + "dick" + { + "1" "Canadian" + } + "dicks" + { + "1" "Canadians" + } +} \ No newline at end of file diff --git a/data/guesswho/config.cfg b/data/guesswho/config.cfg new file mode 100644 index 0000000..a42efa4 --- /dev/null +++ b/data/guesswho/config.cfg @@ -0,0 +1,87 @@ +"guesswho" +{ + "c1m1_hotel" + { + "spawnpoint" "442.905334 5640.576660 2656.031250" + "ents" + { + "FENCE" + { + "origin" "1602.161499 5618.440917 2656.031250" + "rotation" "0.000000 -178.836151 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + "VENDING" + { + "origin" "406.428405 5625.409667 2656.031250" + "rotation" "0.000000 90.238922 0.000000" + "type" "prop_dynamic" + "model" "props\cs_office\vending_machine.mdl" + } + } + + } + "c8m5_rooftop" + { + "spawnpoint" "5386.052246 8413.505859 5536.031250" + } + "c2m2_fairgrounds" + { + "spawnpoint" "-3451.616943 -818.726989 128.031250" + "ents" + { + "DROP_BLOCK" + { + "origin" "-3073.630371 -910.963195 192.623626" + "scale" "30 260 100" + } + "ENTRANCE_BLOCK" + { + "origin" "-2826.833251 -1978.528808 -127.915451" + "rotation" "0.000000 -1.978949 0.000000" + "type" "prop_dynamic" + "model" "props_urban\wood_fence001_128.mdl" + } + "ENTRANCE_BLOCK_PROP" + { + "origin" "-2826.833251 -1978.528808 -127.915451" + "scale" "20 100 500" + } + "STAIR_BLOCK_PROP" + { + "origin" "-3241.681884 -1817.223266 256.031250" + "rotation" "0.000000 92.011253 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "STAIR_BLOCK" + { + "origin" "-3321.681884 -1817.223266 300.031250" + "scale" "140 20 60" + } + } + } + "c11m4_terminal" + { + "spawnpoint" "3081.824951 4571.367187 152.031250" + "ents" + { + "ENTRANCE_BLOCKER" + { + "origin" "2700.844482 1865.502807 177.313140" + "scale" "200 100 200" + } + "fire" + { + "origin" "2700.844482 1865.502807 179.313140" + "type" "env_fire" + "scale" "1.0 256 8" + } + } + "inputs" + { + "checkpoint_entrance" "Kill" + } + } +} diff --git a/data/hideandseek.cfg b/data/hideandseek.cfg new file mode 100644 index 0000000..698862d --- /dev/null +++ b/data/hideandseek.cfg @@ -0,0 +1,2083 @@ +"hideandseek" +{ + "c4m1_milltown_a" + { + "spawnpoint" "-3904.694580 7205.333984 199.836639" + "ents" + { + "TRUCK_SKIP" + { + "origin" "-3369.870117 7448.359375 96.031250" + "rotation" "0.000000 24.135879 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "BARRICADE_1" + { + "origin" "2074.847167 2896.825439 96.031250" + "rotation" "0.000000 175.428447 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "BARRICADE_2" + { + "origin" "2065.847167 2779.825439 96.031250" + "rotation" "0.000000 175.428447 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "BARRICADE_3" + { + "origin" "2071 2670 96.031250" + "rotation" "0.000000 175.428447 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "DOOR_BLOCK" + { + "origin" "2000.038940 2530.103759 104.031250" + "rotation" "90.000000 180.681259 0.000000" + "type" "prop_dynamic" + "model" "props_mill/wood_stack.mdl" + } + "BARRICADE_SIDE" + { + "origin" "1938.229248 2108.860839 96.353591" + "rotation" "0.000000 175.428447 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "HOUSE_BLOCK_1" + { + "origin" "1917.533691 2347.451416 104.031250" + "rotation" "0.000000 0.041839 0.000000" + "type" "prop_dynamic" + "model" "props/cs_office/bookshelf2.mdl" + } + "HOUSE_BLOCK_2" + { + "origin" "1917.533691 2247.451416 104.031250" + "rotation" "0.000000 0.041839 0.000000" + "type" "prop_dynamic" + "model" "props/cs_office/bookshelf2.mdl" + } + "TREEHOUSE_BLOCKER" + { + "origin" "2072.242675 3038.970703 206.251251" + "scale" "5.000000 1500.000000 400.000000" + "type" "env_physics_blocker" + } + "ENTRANCE_STOPPER" + { + "origin" "-4057.503173 7158.272949 201.491455" + "scale" "5.000000 2500.000000 800.000000" + "type" "env_physics_blocker" + } + + } + } + "c5m4_quarter" + { + "spawnpoint" "-3663.735351 3156.915039 64.031250" + "sets" + { + "block" + { + "spawnpoint" "-1322.446411 2238.070800 72.031250" + } + "block_long" + { + "spawnpoint" "-1213.040527 325.299438 176.126968" + } + } + "ents" + { + "END_BLOCK" + { + "origin" "-1534.599975 -1606.185058 256.031250" + "rotation" "0.000000 -177.669448 0.000000" + "type" "prop_dynamic" + "model" "props_urban/fridge001.mdl" + } + "END_BLOCK_2" + { + "origin" "-1802.811401 -1206.369750 260.031250" + "type" "env_physics_blocker" + "scale" "100 100 50" + } + "BEGIN_BLOCK" + { + "origin" "-1548.047607 2458.536437 60.044128" + "scale" "1600.000000 10.000000 400.000000" + "type" "env_physics_blocker" + "set" "block" + } + "STAIRS" + { + "origin" "-1118.047607 915.536437 244.044128" + "rotation" "0.000000 180.843437 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/stairs_house_01.mdl" + } + "GATE_TP" + { + "origin" "-1630.467895 -396.031250 184.031250" + "type" "_portal" + "offset" "-1623.645263 -332.286193 135.869384" + "scale" "10 10 10" + } + "PORTAL_1" + { + "origin" "-1446.877319 -358.595733 203.116073" + "type" "_relportal" + "offset" "0.000000 10.000000 0.000000" + "scale" "100 40 50" + } + "PORTAL_1_PROPA" + { + "origin" "-1575.466674 -420.767852 65.182296" + "rotation" "0.000000 180.843437 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/stairs_house_01.mdl" + } + "PORTAL_1_PROPB" + { + "origin" "-1575.466674 -310.767852 65.182296" + "rotation" "0.000000 180.843437 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/stairs_house_01.mdl" + } + "FLAT_BLOCK" + { + "origin" "-3188.373779 3200.747802 300.585388" + "scale" "500 400 50" + "type" "env_physics_blocker" + } + "FENCE_SKIP" + { + "origin" "-1555.620239 2514.195068 64.031250" + "rotation" "0.0 -71.973693 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "SHORT_BLOCK" + { + "origin" "-563.721069 1031.170043 143.387512" + "rotation" "62.338180 6.194050 0.000000" + "type" "prop_dynamic" + "model" "props_interiors\couch.mdl" + "set" "block_long" + } + "SHORT_BLOCK_SUPPORT" + { + + "origin" "-608.215881 1030.887817 96.031250" + "rotation" "0.530479 -82.875152 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "set" "block_long" + } + "SHORT_BLOCK_SUPPORT2" + { + + "origin" "-608.215881 1030.887817 136.031250" + "rotation" "0.530479 -82.875152 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "set" "block_long" + } + "TRACTOR_EARLY_HELP" + { + "origin" "-1503.682861 539.312591 255.984069" + "rotation" "89.000000 0.671798 90.000000" + "type" "prop_dynamic" + "model" "props_exteriors\fence002.mdl" + } + "GNOME" + { + "origin" "-3511.222656 2463.375488 432.031250" + "type" "prop_physics_multiplayer" + "model" "props_junk/gnome.mdl" + } + "lol" + { + "origin" "-2386.989013 1119.776489 80.031250" + "rotation" "0.000000 -86.269416 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_teenangst.mdl" + } + } + "inputs" + { + "float_tracktrain" "TeleportToPathTrack float_path2" + "float_final_nav_blocker" "BlockNav" + "float_music" "Kill" + "float_start_nav_blocker2" "Kill" + "float_start_nav_blocker3" "Kill" + "courtyard_spawn1_breakable" "Kill" + "courtyard_spawn2_breakable" "Kill" + } + } + "c8m3_sewers" + { + "ents" + { + "A" + { + "origin" "13265.965820 8547.057617 -250.7" + "type" "env_physics_blocker" + } + "B" + { + "origin" "14130.535156 8026.46386 -254.7" + "type" "env_physics_blocker" + } + "A_PROP" + { + "origin" "13265.965820 8497.057617 -240.7" + "type" "prop_dynamic" + "model" "props/cs_office/shelves_metal.mdl" + "rotation" "90 90 0" + } + "B_PROP" + { + "origin" "14130.535156 8026.46386 -254.7" + "type" "prop_dynamic" + "model" "props_swamp/river_sign01.mdl" + "rotation" "90 0 0" + } + "STAIR_HELP" + { + "origin" "11896.693359 7291.923828 143.372573" + "rotation" "0.000000 -90.646430 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + } + "ROOF_EXIT" + { + "origin" "11353 5861 204" + "rotation" "0 96 0" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "ROOF_FIX_FIXER" + { + "origin" "10579.599609 5120.623535 280.031250" + "scale" "20 1000 400" + "type" "env_physics_blocker" + } + "ROOF_FIX_FIXER_CORNER" + { + "origin" "10617.877929 5216.473144 280.031250" + "scale" "40 60 400" + "type" "env_physics_blocker" + } + "ROOF_NO_SNEAKY_JUMP" + { + "origin" "11127.424804 5662.353515 408.031250" + "scale" "20 300 500" + "type" "env_physics_blocker" + } + "ROOF_BRIDGE" + { + "origin" "12421.961914 4886.637207 568.031250" + "rotation" "-11.137193 -159.704940 0.000000" + "type" "prop_dynamic" + "model" "props_unique\rope_bridge.mdl" + + } + "ROOF_STOP" + { + "origin" "11895.786132 4616.688476 712.031250" + "rotation" "0.137193 0.704940 0.000000" + "type" "prop_dynamic" + "model" "props_wasteland\coolingtank01.mdl" + } + "ROOF_STOP2" + { + + "origin" "11641.057617 4630.232421 712.031250" + "rotation" "0.137193 0.704940 0.000000" + "type" "prop_dynamic" + "model" "props_wasteland\coolingtank01.mdl" + } + "ROOF_STOP3" + { + "origin" "11432.921875 4660.313476 712.031250" + "rotation" "0.137193 0.704940 0.000000" + "type" "prop_dynamic" + "model" "props_wasteland\coolingtank01.mdl" + } + "ROOF_STOP_WALL" + { + "origin" "11641.057617 4630.232421 712.031250" + "type" "env_physics_blocker" + "scale" "2000 90 600" + } + "ROOF_DEATH_PREVENT" + { + "origin" "12456.858398 4781.894042 568.031250" + "rotation" "0.000000 -131.235916 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + "ROOF_DEATH_PREVENT_WALL" + { + "origin" "12310.758789 4753.980957 568.031250" + "type" "env_physics_blocker" + "scale" "120 60 400" + } + "ROOF_DEATH_PREVENT_PREVENTER" + { + "origin" "11994.040039 4736.263671 712.031250" + "rotation" "0.000000 -4.221647 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + "STAIR_ACCESS" + { + + "origin" "11100.574218 5208.395996 317.781250" + "rotation" "0.290893 -80.968573 32.000000" + "type" "prop_dynamic" + "model" "props_swamp\plank001b_192.mdl" + } + "GAS_STOP" + { + "origin" "12682.116210 5713.574218 568.031250" + "rotation" "0.000000 73.767333 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + "GAS_STOP2" + { + "origin" "12580.110351 5731.003417 568.031250" + "rotation" "0.000000 73.767333 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + "GAS_BLOCK" + { + "origin" "12812.621093 5929.395507 463.586090" + "type" "env_physics_blocker" + "scale" "300 1000 1000" + } + "NO_DIE" + { + "origin" "11323.022460 4793.813476 712.031250" + "rotation" "0.000000 -134.307327 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\barricade001_128_reference.mdl" + } + } + "inputs" + { + "anv_mapfixes_unattackable_wrongway1" "Kill" + } + } + "c3m1_plankcountry" + { + "spawnpoint" "-12070.341796 10517.305664 183.448410" + "sets" + { + "area2" + { + "spawnpoint" "-4240.322265 6052.394531 28.160285" + } + "end" + { + "spawnpoint" "-1030.998535 4821.037109 144.160293" + } + "large" + { + "spawnpoint" "-1030.998535 4821.037109 144.160293" + } + } + "ents" + { + "divider" + { + "origin" "-1023.450622 4939.198242 144.160293" + "rotation" "0.000000 -90.445228 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + "set" "area2" + } + "divider" + { + "origin" "-1023.450622 4939.198242 144.160293" + "rotation" "0.000000 -90.445228 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + "set" "end" + } + } + "inputs" + { + "func_breakable" "Break" + } + } + "c3m3_shantytown" + { + "sets" + { + "hut" + { + "spawnpoint" "-3914.085449 -3092.477050 62.502365" + } + "end-large" + { + "spawnpoint" "-557.272216 -2464.328125 4.269320" + "inputs" + { + "delete_coop_ents_postIO" "Trigger" + "bridge_minifinale" "Close" + "bridge_minifinale" "SetSpeed 200" + } + } + } + "ents" + { + "door_block" + { + "origin" "-4004.808593 -3011.982666 62.502365" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_urban\fridge002.mdl" + } + "door_wall" + { + "origin" "-4000.808593 -3011.982666 62.502365" + "scale" "20 1050 300" + } + "door_block_tree" + { + "origin" "-4135.271972 -3837.605224 -0.291338" + "rotation" "-0.559620 173.978195 0.000000" + "type" "prop_dynamic" + "model" "props_foliage\swamp_cypress_knee01.mdl" + } + "door_block_tree" + { + "origin" "-4116.226562 -3944.508056 0.005385" + "rotation" "-0.559620 173.978195 0.000000" + "type" "prop_dynamic" + "model" "props_foliage\swamp_cypress_knee01.mdl" + } + "large_block" + { + "origin" "-1745.625976 -2745.440429 0.031250" + "set" "end-large" + "scale" "50 2000 400" + } + "large_block_prop" + { + "origin" "-1780.625976 -2880.440429 0.031250" + "type" "prop_dynamic" + "set" "end-large" + "rotation" "0 90 0" + "model" "props_debris\airliner_wreckage3.mdl" + } + "large_block_prop" + { + "origin" "-1573.762573 -3763.656494 -10.686201" + "type" "prop_dynamic" + "set" "end-large" + "rotation" "0 90 0" + "model" "props_debris\dead_cow_smallpile.mdl" + } + } + "inputs" + { + "bridge_button" "Kill" + } + } + "c3m4_plantation" + { + "sets" + { + "begin" + { + + } + "mansion" + { + "climbing" "on" + "spawnpoint" "1656.207519 -120.207824 224.031250" + } + } + "defaultset" "begin" + "ents" + { + "A" + { + "origin" "2000.802612 -426.686829 402.803497" + "type" "env_physics_blocker" + "scale" "150.0 150.00 1.0" + "set" "begin" + } + "A_PROP" + { + "origin" "2000.802612 -426.686829 402.803497" + "type" "prop_dynamic" + "model" "props_swamp/boardwalk_384.mdl" + "rotation" "0 90 0" + "set" "begin" + } + "MANSION_ENT_RAIL" + { + "model" "props_exteriors/wood_railing004c.mdl" + "type" "prop_dynamic" + "origin" "2529.63 -804.10 642.56" + "angles" "0.00 178.84 0.00" + "set" "mansion" + } + "MANSION_ENT_BLOCK" + { + "origin" "2563.37 -818.00 366.03" + "type" "env_physics_blocker" + "scale" "441 10 400" + "set" "mansion" + } + "MANSION_ENT_GATE" + { + "model" "props_street/police_barricade_496in.mdl" + "origin" "1693.63 -1178.33 169.86" + "type" "prop_dynamic" + "set" "mansion" + } + } + "inputs" + { + "env_physics_blocker" "Kill" + "gate_explode_relay" "Trigger" + "prop_minigun" "Kill" + } + } + "c1m3_mall" + { + "sets" + { + "mid" + { + "spawnpoint" "1457.455078 -1059.256469 280.031250" + } + } + "defaultset" "begin" + "ents" + { + "A" + { + "origin" "1581.286865 -1029.394043 280.079254" + "type" "prop_dynamic" + "model" "props_junk/dumpster.mdl" + "rotation" "0 90 0" + } + "B" + { + "origin" "1714.133179 -1023.777527 347.735168" + "scale" "25.0 25.00 100.0" + "type" "env_physics_blocker" + "set" "begin" + } + "B" + { + "origin" "1714.133179 -1023.777527 347.735168" + "scale" "25.0 25.00 100.0" + "type" "env_physics_blocker" + "set" "mid" + } + "lol" + { + "origin" "2129.125976 -2346.968750 0.031250" + "rotation" "0.000000 39.811450 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_namvet.mdl" + } + "VENT_WARPER" + { + "origin" "1203.086791 -2000.914306 384.031250" + "type" "_portal" + "scale" "40 40 50" + "offset" "1159.986694 -2063.281738 456.013153" + "set" "mid" + } + "EXIT_BLOCK" + { + "origin" "1283.903686 -5341.520019 536.031250" + "rotation" "0.000000 0.968292 0.000000" + "type" "prop_dynamic" + "model" "props\cs_office\vending_machine.mdl" + "set" "mid" + } + + } + "inputs" + { + "sound_alarm" "StopSound" + "sound_alarm" "Kill" + "blocker_stairwell" "Kill" + "hurt_stairwell" "Kill" + "door_stairwell" "Unlock" + "blocker_stairwell_clip" "Kill" + "door_hallway" "Kill" + "breakwall_bathroom_wall" "Break" + "breakble_glass_minifinale" "Break" + "env_player_blocker" "Kill" + "relay_elevator_path_02" "Trigger" + "soundscapes-hall" "StopSound" + "soundscapes-hall.entry" "StopSound" + } + } + "c6m2_bedlam" + { + "ents" + { + "A" + { + "origin" "349.935608 3156.456543 263.583710" + "scale" "100.0 50.00 300.0" + "type" "env_physics_blocker" + "set" "short" + } + "A_PROP" + { + "origin" "350.063263 3171.198730 198.247498" + "type" "prop_dynamic" + "model" "props_industrial/barrel_fuel.mdl" + "rotation" "0 -91 -0.000109" + "set" "short" + } + "B_PROP" + { + "origin" "1138.566650 1374.530884 -194.578400" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 180 0" + } + "B_PROP2" + { + "origin" "1363.922241 1381.682617 -194.578400" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 0 0" + } + "DOOR_BLOCK" + { + "origin" "1401.782592 4686.330566 -101.095458" + "type" "env_physics_blocker" + "scale" "60 20 100" + } + "DOOR_BLOCK_PROP" + { + "origin" "1401.782592 4686.330566 -160.095458" + "type" "prop_dynamic" + "model" "props\de_train\pallet_barrels.mdl" + "rotation" "0 -91 -0.000109" + } + "RETURN_HELPER" + { + "origin" "1251.872436 1316.629760 -78.262710" + "rotation" "0.000000 178.612152 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + } + "inputs" + { + "gate_1_alarm" "Kill" + "sound_alarm" "Kill" + "gate_2_alarm" "Kill" + } + } + "c7m1_docks" + { + "climbing" "off" + "spawnpoint" "11068.093750 -207.805831 -67.623802" + "ents" + { + "A_PROP" + { + "origin" "8469.404297 854.461121 14.257706" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 -90 0" + } + "B_PROP" + { + "origin" "3522.576416 647.513244 176.031250" + "rotation" "0.000000 -88.406250 0.000000" + "type" "prop_dynamic" + "model" "props_doors/roll-up_door_full.mdl" + } + "B_PROP" + { + "origin" "3266.576416 647.513244 176.031250" + "rotation" "0.000000 -88.406250 0.000000" + "type" "prop_dynamic" + "model" "props_doors/roll-up_door_full.mdl" + } + "DUMPSTER_EXIT" + { + "origin" "3604 263 149" + "model" "props_junk/dumpster_2.mdl" + "type" "prop_dynamic" + "rotation" "0 180 0" + } + "DUMPSTER_ENTER" + { + "origin" "3872.412841 588.284240 176.031250" + "model" "props_junk/dumpster_2.mdl" + "type" "prop_dynamic" + "rotation" "0 0 0" + } + "CRATE_SHORTCUT" + { + "origin" "5288.236328 596.502136 146.863418" + "rotation" "0.000000 178.612152 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "SPAWN_BLOCK_PROP" + { + "origin" "11404.483398 -227.757766 -63.968750" + "rotation" "0.966560 -176.921936 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "SPAWN_BLOCK" + { + "origin" "11404.483398 -227.757766 0.968750" + "scale" "20 1000 100" + "type" "env_physics_blocker" + } + "lol" + { + "origin" "7641.535644 2735.968750 240.031250" + "rotation" "8.966513 -31.319810 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_namvet.mdl" + } + } + "inputs" + { + "tankdoorin" "Open" + "tankdoorout" "Open" + "traincar_navblocker" "Kill" + "tankdoorin_button" "Kill" + "tankdoorout_button" "Kill" + "tank_door_clip" "Kill" + "tank_sound_timer" "Disable" + "delete_coop_ents_postIO" "Trigger" + "battlefield_cleared" "UnblockNav" + } + } + "c10m2_drainage" + { + "ents" + { + "TOP_HELPER" + { + "origin" "-9874.015625 -7637.003417 -467.968750" + "rotation" "0.000000 -90.964706 0.000000" + "type" "prop_dynamic" + "model" "props_interiors/desk_executive.mdl" + } + "STAIRS" + { + "origin" "-8120.544433 -7200.660156 -561.968750" + "rotation" "0.000000 180.672305 -8.000000" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + } + "BOX" + { + "origin" "-8713.857421 -7792.103027 -395.968750" + "rotation" "0.000000 90.578536 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "PORTAL1_ENT" + { + "origin" "-8713.857421 -7792.103027 -300.968750" + "type" "_relportal" + "offset" "0 150 50" + "scale" "60 30 5" + } + "PORTAL1_EXIT" + { + + "origin" "-8698.404296 -7663.968750 -260.968750" + "type" "_portal" + "offset" "-8776.213867 -7811.048339 -395.968750" + "scale" "60 30 50" + } + "PORTAL2_EXIT" + { + + "origin" "-9443.846679 -7276.223144 -307.968750" + "type" "_portal" + "offset" "-9520.279296 -7281.130859 -467.968750" + "scale" "20 100 100" + } + "PORTAL3_EXIT" + { + + "origin" "-9867.969726 -6852.831054 -307.968750" + "type" "_portal" + "offset" "-9871.308593 -6921.020507 -467.968750" + "scale" "100 20 100" + } + "PORTAL4_EXIT" + { + + "origin" "-8984.172851 -7881.412597 -307.968750" + "type" "_portal" + "offset" "-8928.278320 -7888.108886 -336.968750" + "scale" "20 100 100" + } + "FALL_BARRIER" + { + "origin" "-8830.380859 -8800.031250 -307.968750" + "rotation" "0.000000 94.068542 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors\fence002.mdl" + } + "PORTAL_5_ENTRANCE_PROP" + { + "origin" "-8932.521484 -8515.070312 -400.968750" + "rotation" "0.000000 -178.028656 0.000000" + "type" "prop_dynamic" + "model" "props/de_nuke/crate_small.mdl" + } + "PORTAL_5_ENTRACE" + { + "origin" "-8970.968750 -8521.311523 -307.968750" + "type" "_portal" + "offset" "-9147.531250 -8549.711914 -307.968750" + "scale" "5 50 20" + } + "PORTAL5_EXIT" + { + + "origin" "-9072.031250 -8532.894531 -307.968750" + "type" "_portal" + "offset" "-8942.968750 -8528.318359 -330.968750" + "scale" "20 100 100" + } + "BRIDGE_COLLIDE" + { + "origin" "-8402.264648 -8553.781250 -400.065338" + "scale" "400 40 5" + "type" "env_physics_blocker" + } + "WINDOW_BLOCK_PROP" + { + "origin" "-6125.968750 -6989.230957 -63.608612" + "rotation" "0.000000 -177.974670 0.000000" + "type" "prop_dynamic" + "model" "props_vehicles/army_truck.mdl" + } + "WINDOW_BLOCK" + { + "origin" "-6131.369140 -7206.083496 -17.568002" + "scale" "50 200 200" + "type" "env_physics_blocker" + } + "PIPE_HELPER" + { + "origin" "-8035.905273 -8131.730468 -481.552062" + "scale" "20 80 10" + "type" "env_physics_blocker" + } + } + "inputs" + { + "sound_alarm" "Kill" + "sound_floodgate_loop" "Kill" + "watergate_bottom" "BlockNav" + "gate_push_01" "Disable" + "gate_blocker" "Disable" + "gate_collide" "Enable" + "watergate" "UnblockNav" + } + } + "c14m1_junkyard" + { + "ents" + { + "C" + { + "origin" "-1101.485352 -4729.446777 -109.968750" + "scale" "25.0 25.00 30.0" + "type" "env_physics_blocker" + } + "A_PROP" + { + "origin" "-1100.091553 -4585 -300.641998" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 90 0" + } + "B" + { + "origin" "-4259.611328 2193.898682 119.894897" + "scale" "55.0 55.00 100.0" + "type" "env_physics_blocker" + } + } + } + "c1m1_hotel" + { + "buttons" "no" + "ents" + { + "A" + { + "origin" "2164.177246 5723.599609 2526.031250" + "scale" "60 20 50" + "type" "env_physics_blocker" + } + } + "inputs" + { + "elevator_1_door2" "close" + "elevator_1_door1" "close" + } + } + "c2m2_fairgrounds" + { + "sets" + { + "rides" { + "spawnpoint" "362.696716 -268.582977 -16.631347" + } + } + "ents" + { + "END_STOP" + { + "origin" "495.141967 -279.631744 0.031250" + "scale" "5.000000 220.000000 200.000000" + "type" "env_physics_blocker" + } + "END_PROP" + { + "origin" "474.110717 -191.851898 -3.251148" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "END_PROP_2" + { + "origin" "474.110717 -323.851898 -3.251148" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "STAIRS" + { + "type" "prop_dynamic" + "origin" "1951.127319 -317.584213 5.031250" + "rotation" "0.843326 90.637062 0.000000" + "model" "props_exteriors/wood_stairs_120.mdl" + } + "HELPER" + { + "origin" "2108.085937 -463.634277 160.352081" + "rotation" "-26.078588 -90.851776 0.000000" + "type" "prop_dynamic" + "model" "props_junk/dumpster.mdl" + } + "HEDGE_SHOWER" + { + "set" "rides" + "origin" "-3043.151611 -5329.417480 -63.968750" + "rotation" "0.000000 1.148354 0.000000" + "type" "prop_dynamic" + "model" "props_junk/dumpster_2.mdl" + } + "NO_SAFEROOM" + { + "set" "rides" + "origin" "-3926.420166 -5486.845214 -66.968750" + "rotation" "0.000000 -11.019555 0.000000" + "type" "prop_dynamic" + "model" "props_fairgrounds\kiddyland_ridestructure_closed.mdl" + } + "binning_fence_explainer" + { + "set" "rides" + "origin" "-1559.084960 -1815.552001 128.996826" + "rotation" "0.185535 -60.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "binning_fence_explainer_inner" + { + "set" "rides" + "origin" "-702.269836 -2566.092041 128.031250" + "rotation" "0.185535 -90.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "binning_fence_explainer_innerb" + { + "set" "rides" + "origin" "-830.394409 -2502.136230 128.031250" + "rotation" "0.185535 -119.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "binning_fence_explainer_innerc" + { + "set" "rides" + "origin" "-572.269836 -2536.092041 128.031250" + "rotation" "0.185535 -80.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "shelf" + { + "set" "rides" + "origin" "-3134.213378 -336.267608 128.031250" + "rotation" "0.581893 89.038597 0.000000" + "type" "prop_dynamic" + "model" "props\cs_office\shelves_metal.mdl" + } + "HEDGE_SHOWER" + { + "set" "rides_short" + "origin" "-3043.151611 -5329.417480 -63.968750" + "rotation" "0.000000 1.148354 0.000000" + "type" "prop_dynamic" + "model" "props_junk/dumpster_2.mdl" + } + "NO_SAFEROOM" + { + "set" "rides_short" + "origin" "-3926.420166 -5486.845214 -66.968750" + "rotation" "0.000000 -11.019555 0.000000" + "type" "prop_dynamic" + "model" "props_fairgrounds\kiddyland_ridestructure_closed.mdl" + } + "binning_fence_explainer" + { + "set" "rides_short" + "origin" "-1559.084960 -1815.552001 128.996826" + "rotation" "0.185535 -60.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "binning_fence_explainer_inner" + { + "set" "rides_short" + "origin" "-702.269836 -2566.092041 128.031250" + "rotation" "0.185535 -90.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "binning_fence_explainer_innerb" + { + "set" "rides_short" + "origin" "-830.394409 -2502.136230 128.031250" + "rotation" "0.185535 -119.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "binning_fence_explainer_innerc" + { + "set" "rides_short" + "origin" "-572.269836 -2536.092041 128.031250" + "rotation" "0.185535 -80.982719 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications\police_barrier001_128_reference.mdl" + } + "shelf" + { + "set" "rides_short" + "origin" "-3134.213378 -336.267608 128.031250" + "rotation" "0.581893 89.038597 0.000000" + "type" "prop_dynamic" + "model" "props\cs_office\shelves_metal.mdl" + } + "short_bottom_block" + { + "origin" "-2300.978027 -3836.044189 -128.968750" + "rotation" "0 -90 0" + "type" "prop_dynamic" + "model" "props_urban\fence_gate001_256.mdl" + "set" "rides_short" + } + "short_bottom_block2" + { + "origin" "-2394.099365 -3841.655029 -126.968750" + "rotation" "0 -90 0" + "type" "prop_dynamic" + "model" "props_urban\fence_cover001_64.mdl" + "set" "rides_short" + } + "short_top_block" + { + "origin" "-2496.688232 -3847.620117 32.031250" + "rotation" "0 -90 0" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + "set" "rides_short" + } + "stairs_trains" + { + "origin" "-600.644897 520.514068 -82.156204" + "rotation" "0.000000 -90.962295 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors\wood_stairs_120.mdl" + } + "stairs_trains2" + { + "origin" "-600.644897 665.611511 20.675038" + "rotation" "0.000000 -90.962295 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors\wood_stairs_120.mdl" + } + "train_pole" + { + "origin" "-2723.161621 -784.884704 134.031250" + "rotation" "80.000000 172.499984 0.000000" + "type" "prop_dynamic" + "model" "props_c17\utilitypole01d.mdl" + } + } + "inputs" + { + "coop_prop" "kill" + "anv_mapfixes_dispcollision_fairgrounds" "Kill" + "func_breakable" "Break" + "anv_mapfixes_cliprework_beanbinninga" "Kill" + "coop_blocker" "Kill" + "!3749406" "Kill" + "!3762835" "Kill" + "tol_clip_brush" "Kill" + } + } + "c2m3_coaster" + { + "spawnpoint" "2829.782958 2042.384155 21.309265" + "defaultset" "large" + "ents" + { + "SAFEROOM_BLOCK_PROP" + { + "origin" "3012.181884 2051.005371 60.447525" + "rotation" "0.000000 -175.885253 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "VENT_SUS_1" + { + "origin" "437.521789 3700.031250 208.031250" + "rotation" "0.000000 -151.672363 0.000000" + "type" "prop_dynamic" + "model" "props_foliage\flower_barrel.mdl" + } + "VENT_SUS_2" + { + "origin" "179.974365 3701.934082 218.263107" + "rotation" "0.000000 93.777389 0.000000" + "type" "prop_dynamic" + "model" "props_waterfront\footlocker01.mdl" + } + "COASTER_STOP" + { + "origin" "-1971.579467 2021.431396 0.031250" + "rotation" "0.000000 -168.560409 0.000000" + "type" "prop_dynamic" + "model" "props_vehicles\deliveryvan_armored.mdl" + } + "COASTER_STOP_BLOCKER" + { + "origin" "-1816.031250 2094.495849 18.641880" + "type" "env_physics_blocker" + "scale" "20 20 100" + } + "END_PORTAL_INBOUNDS" + { + "origin" "-111.468742 3868.442138 -30.968750" + "type" "_portal_xen" + "offset" "-218.711853 3872.825927 -16.254243" + } + "END_PORTAL_OUTBOUNDS" + { + "origin" "-175.322891 3874.135742 -25.896236" + "type" "_portal_xen" + "offset" "-6.273283 3868.246337 -39.968750" + } + "ENT_PORTAL_OUTBOUNDS" + { + "origin" "781.968750 5089.447265 -12.105030" + "type" "_portal_xen" + "offset" "848.368774 4996.333496 44.031250" + } + "ENT_PORTAL_INBOUNDS" + { + "origin" "818.531250 5120.259765 5.968750" + "type" "_portal_xen" + "offset" "693.952026 5122.255859 2.038572" + "set" "large" + } + "NO_JUMP_HOLE_PROP" + { + "origin" "298.292388 3772.014892 200.059875" + "rotation" "-84.000000 90.560409 -10.000000" + "type" "prop_dynamic" + "model" "props\cs_militia\sheetrock_leaning.mdl" + "set" "short" + } + "NO_JUMP_WALL_PROP" + { + "origin" "-60.321926 3621.998046 208.031250" + "rotation" "0.000000 177.283248 0.000000" + "type" "prop_dynamic" + "model" "props\cs_assault\box_stack1.mdl" + "set" "short" + } + } + "inputs" + { + "finale_alarm_sound" "Kill" + "relay_start_onslaught" "Trigger" + "prop_gate_coaster" "Kill" + "navblock_coop" "Kill" + "func_detail_blocker" "Kill" + "brushes_coop" "Kill" + "func_brush" "Kill" + "breakwall" "Break" + } + } + "c2m4_barns" + { + "ents" + { + "gate_stop" + { + "origin" "-2251.308349 1434.023315 -255.968750" + "scale" "20 100 100" + } + "lol" + { + "origin" "-255.596389 712.626953 -205.968750" + "rotation" "0.000000 180.269416 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_teenangst.mdl" + } + } + "inputs" + { + "brushes_coop" "Kill" + "clips_coop" "Kill" + "navblock_coop" "Kill" + "props_coop" "Kill" + "minifinale_gates_door1" "Lock" + "minifinale_gates_door1" "Close" + "minifinale_gates_door2" "Lock" + "minifinale_gates_door2" "Close" + "minifinale_gates_door3" "Lock" + "minifinale_gates_door3" "Close" + "minifinale_gates_door4" "Lock" + "minifinale_gates_door4" "Close" + "minifinale_gates_door5" "Lock" + "minifinale_gates_door5" "Close" + "minifinale_gates_door6" "Lock" + "minifinale_gates_door6" "Close" + } + } + "c1m2_streets" + { + "climbing" "off" + "sets" + { + "cola" + { + "spawnpoint" "-5427.254882 938.835754 568.031250" + } + } + "ents" + { + "A_PROP" + { + "origin" "-2536 2258 0" + "type" "prop_dynamic" + "model" "props_junk/dumpster.mdl" + "rotation" "0 0 0" + } + "A_PROP2" + { + "origin" "-2536 2418 0" + "type" "prop_dynamic" + "model" "props_junk/dumpster.mdl" + "rotation" "0 0 0" + } + "B_PROP" + { + "origin" "-2305 2159 0" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "B_PROP2" + { + "origin" "-2305 2159 40" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "B_PROP3" + { + "origin" "-2305 2200 0" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "C_PROP" + { + "origin" "-4377.309570 1749.962646 80.593964" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 10 0" + } + "C_PROP2" + { + "origin" " -4383.500488 2161.401611 226.530548" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 10 0" + } + "C_PROP2" + { + "origin" " -4383.500488 2161.401611 266.530548" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 10 0" + } + "C_PROP2" + { + "origin" " -4383.500488 2121.401611 226.530548" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 10 0" + } + "D_Prop" + { + "origin" "-5170.352051 870.512817 465.251526" + "type" "prop_dynamic" + "model" "props_street/police_barricade.mdl" + "rotation" "0 180 0" + } + "D" + { + "origin" "-5180.282227 905.176453 540.750977" + "scale" "80 70 80" + } + "E_Prop" + { + "origin" "1399.475464 2483.173096 572.186157" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "E_Prop2" + { + "origin" "1315.670288 2500.615234 670.690247" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "BUSH_BLOCK" + { + "origin" "800.609313 2733.161376 695.719726" + "scale" "190 50 100" + } + "G_Prop" + { + "origin" "-2219.452637 1219.065308 2.395943" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 90 0" + } + "cola_replace" + { + "origin" "-7376.00 -1338.00 395.00" + "type" "prop_physics_multiplayer" + "model" "w_models/weapons/w_cola.mdl" + "rotation" "0 0 0" + } + "fence" + { + "origin" "-5458.898437 823.603088 610.031250" + "rotation" "0.000000 -89.520973 0.000000" + "type" "prop_dynamic" + "model" "props_urban\fence002_128.mdl" + } + "fence_stop" + { + "origin" "-5250.609375 824.685974 746.281250" + "scale" "60 10 80" + } + "lol" + { + "origin" "-7634.699218 -373.631134 752.381225" + "rotation" "90.000000 -90.269416 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_teenangst.mdl" + } + "tug" + { + "origin" "-5836.837890 2780.815917 391.636169" + "rotation" "0.000000 -90.999050 -15.000000" + "type" "prop_dynamic" + "model" "props_vehicles\boat_rescue_tug.mdl" + } + } + "inputs" + { + "store_door01_dynamic" "open" + "store_door02_dynamic" "open" + "store_alarm_generic" "StopSound" + "store_alarm_generic" "Kill" + "cola" "Kill" + "!100452" "_setteam" + "InstanceAuto36-gunshop.ent" "Disable" + "InstanceAuto36-stairwell.ent" "Disable" + "InstanceAuto36-stairwell.ent" "Disable" + "stripmall_door1_breakable" "Break" + "stripmall_door2_breakable" "Break" + "tanker_destroy_relay" "Trigger" + } + } + "c1m4_atrium" + { + "spawnpoint" "-4440.582519 -3930.253417 136.031250" + "ents" + { + "exitportalwarp" + { + "origin" "-4445.884277 -2288.304687 30.806552" + "scale" "40 65 80" + "offset" "0 60 0" + "type" "_relportal" + } + "lol" + { + "origin" "-5760.802246 -3997.028320 1024.031250" + "rotation" "0.608940 26.964090 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_teenangst.mdl" + } + "lol2" + { + "origin" "-3363.302001 -4017.320068 744.781250" + "rotation" "0.608940 159.964090 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_namvet.mdl" + } + "lol3" + { + "origin" "-5184.031250 -2790.462402 280.031250" + "rotation" "0.000000 0.649614 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_biker.mdl" + } + "lol4" + { + "origin" "-3024.509521 -4495.127929 536.031250" + "rotation" "0.000000 123.649614 0.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_manager.mdl" + } + "lol4_block" + { + "origin" "-3024.509521 -4495.127929 536.031250" + "scale" "40 25 100" + } + "cheater_warp" + { + "origin" "-3295.968750 -4299.645019 650.031250" + "type" "_portal" + "scale" "40 25 10" + "offset" "-3358.754394 -4298.374511 640" + } + "gnome" + { + "origin" "-4735.599609 -3408.180175 86.600860" + "rotation" "59.756366 -110.296585 0.000000" + "type" "prop_physics_multiplayer" + "model" "props_junk/gnome.mdl" + } + } + "inputs" + { + "anv_mapfixes_collision_atrium" "Kill" + "elevator" "SetMaxSpeed 1000" + "elevator" "MoveToFloor bottom" + "event_elevator_deny" "Kill" + "exitdoor_portal" "Trigger" + "fx_intro" "Kill" + "fade_outro_3" "Kill" + "camera_outro_wide" "Disable" + "camera_outro_wide" "Kill" + "camera_outro_tele" "Disable" + "camera_outro_tele" "Kill" + "trigger_finale" "Kill" + "trigger_finale" "Kill" + "escape_3" "Enable" + "escape_4" "Enable" + "escape_2" "Enable" + "escape_6" "Enable" + "escape_7" "Enable" + "escape_1" "Enable" + "env_player_blocker" "Kill" + "env_physics_blocker" "Kill" + "gas_nozzle" "Kill" + "relay_outro_endseq" "Trigger" + "cam_selector_2" "Trigger" + "exitdoor_portal" "Open" + "mall_directory" "Enable" + "charger_hurt" "Kill" + } + } + "c8m5_rooftop" + { + "ents" + { + "A_PROP" + { + "origin" "7255 8925 6085" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP2" + { + "origin" "7255 8925 6125" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP3" + { + "origin" "7300 8925 6085" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + } + } + "c8m2_subway" + { + "ents" + { + "A_PROP" + { + "origin" "7498 3020 18" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 0 0" + } + "A_PROP2" + { + "origin" "7342 3020 130" + "type" "prop_dynamic" + "model" "props_exteriors/wood_stairs_120.mdl" + "rotation" "0 0 0" + } + "C" + { + "origin" "8670 4958 200" + "scale" "50 700 200" + "type" "env_physics_blocker" + } + "B_PROP" + { + "origin" "8480 4970 15" + "type" "prop_dynamic" + "model" "props_vehicles/semi_trailer_wrecked.mdl" + "rotation" "0 -25 -2" + } + "B_PROP2" + { + "origin" "8595 5355 12" + "type" "prop_dynamic" + "model" "props_vehicles/taxi_rural.mdl" + "rotation" "0 -25 3" + } + "B_PROP3" + { + "origin" "8393 4642 12" + "type" "prop_dynamic" + "model" "props_junk/trashcluster01b_corner.mdl" + "rotation" "0 0 0" + } + } + } + "c11m3_garage" + { + "ents" + { + "A_PROP" + { + "origin" "-6055 -2213 12" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP2" + { + "origin" "-6055 -2213 52" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP3" + { + "origin" "-6055 -2213 92" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROPB" + { + "origin" "-6055 -2253 12" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP2B" + { + "origin" "-6055 -2253 52" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROPC" + { + "origin" "-6095 -2213 12" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP2C" + { + "origin" "-6095 -2213 52" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "A_PROP2D" + { + "origin" "-6095 -2253 12" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + "rotation" "0 0 0" + } + "B_PROP" + { + "origin" "-2326.5 2005 29" + "type" "prop_dynamic" + "model" "props_vehicles/taxi_rural.mdl" + "rotation" "0 180 -10" + } + "B" + { + "origin" "-2396.5 2005 29" + "scale" "100 5 150" + "type" "env_physics_blocker" + } + "C_PROP2" + { + "origin" "-2165.216797 1856.723877 16" + "rotation" "0 0 0 " + "type" "prop_dynamic" + "model" "props_junk/dumpster_2.mdl" + } + "C_PROP3" + { + "origin" "-2165.216797 1946.723877 16" + "rotation" "0 0 0 " + "type" "prop_dynamic" + "model" "props_junk/dumpster_2.mdl" + } + "C" + { + "origin" "-2210.216797 1900.723877 35" + "scale" "15 100 100" + "type" "env_physics_blocker" + } + "gnome" + { + + "origin" "-5489.493164 1160.628540 36.031250" + "rotation" "0.000000 90.606277 0.000000" + "type" "prop_physics_multiplayer" + "model" "props_junk/gnome.mdl" + } + } + "inputs" + { + "construction_clip" "kill" + "fuel_barricade" "kill" + "barricade_gas_can" "kill" + "fuel_barricade_break1" "kill" + "fuel_barricade_break2" "kill" + "fuel_barricade_break3" "kill" + "door_exitl" "Lock" + "door_exitr" "Lock" + } + } + "c11m4_terminal" + { + "spawnpoint" "-482.813659 3566.486572 296.031250" + "sets" + { + "terminal" + { + "spawnpoint" "1811.834716 1570.712402 264.607604" + } + } + "ents" + { + "BAG_HOLE_A" + { + "origin" "382.787200 2708.387207 40.031250" + "rotation" "0.000000 -174.077285 0.000000" + "type" "prop_dynamic" + "model" "props_unique/airport/luggage_pile1.mdl" + } + "BAG_HOLE_B" + { + "origin" "402.307434 2415.856201 40.031250" + "rotation" "0.000000 -174.077285 0.000000" + "type" "prop_dynamic" + "model" "props_unique/airport/luggage_pile1.mdl" + } + "BAG_HOLE_C" + { + "origin" "401.137786 2110.304199 40.031250" + "rotation" "0.000000 -174.077285 0.000000" + "type" "prop_dynamic" + "model" "props_unique/airport/luggage_pile1.mdl" + } + "DETECTOR_NO_DETECT" + { + "origin" "1023.898742 1750.977294 16.031250" + "scale" "20 650 300" + "set" "terminal" + } + "DETECTOR_PROP" + { + "origin" "1030.929931 1755.157714 37.031250" + "rotation" "90 0 0" + "type" "prop_dynamic" + "model" "props_interiors\chairs_airport.mdl" + "set" "terminal" + } + "lol" + { + "origin" "2350.819335 1851.536376 152.235565" + "rotation" "10.137485 -178.424728 15.000000" + "type" "prop_dynamic" + "model" "survivors/survivor_teenangst.mdl" + "set" "terminal" + } + } + "inputs" + { + "van_blocker" "Kill" + "van_start_relay" "Trigger" + "!3098419" "Kill" + "breakwall01" "Break" + "func_breakable" "Kill" + "breakwall01_illusionary" "Kill" + "!6802112" "Open" + "!6765323" "Kill" + "!6765365" "Kill" + "securityalarmlight1" "TurnOn" + "securityspotlight1" "LightOn" + "securityrotator1" "StopSound" + "securityalarmbase1" "Skin 1" + "securityalarmsprite1" "ShowSprite" + "alarm_safety_relay" "Kill" + "env_soundscape" "Kill" + } + } + "c12m1_hilltop" + { + "sets" + { + "A" + { + "spawnpoint" "-6506.025878 -6803.962402 377.974670" + } + } + } + "c12m4_barn" + { + "spawnpoint" "10523.914062 -6057.256347 -63.968750" + "ents" + { + "BRIDGE_STOP" + { + "origin" "10485.244140 -3690.727294 -60.199607" + "rotation" "0.000000 -87.237983 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/barricade001_128_reference.mdl" + } + "BRIDGE_STOP2" + { + "origin" "10403.553710 -3663.791503 -63.968750" + "rotation" "0.000000 89.303184 0.000000" + "type" "prop_dynamic" + "model" "props_street/police_barricade.mdl" + } + "BRIDGE_BLOCK" + { + "origin" "10463 -3604 -63" + "scale" "120 100 200" + "type" "env_physics_blocker" + } + "FENCE_SKIP_HELPER" + { + "origin" "11317.451171 -4665.616210 -365.052124" + "rotation" "0.895275 90.865699 15.000000" + "type" "prop_dynamic" + "model" "props_vehicles\deliveryvan_glass.mdl" + } + "FENCE_SKIP_HELPER" + { + "origin" "11317.451171 -4665.616210 -365.052124" + "rotation" "0.895275 90.865699 15.000000" + "type" "prop_dynamic" + "model" "props_vehicles\deliveryvan.mdl" + } + "FENCE_SKIP_HELPER_B" + { + "origin" "11358.471679 -4625.372070 -259.812072" + "rotation" "15.114483 0.347351 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "FENCE_SKIP_HELPER_B2_TOP" + { + "origin" "11358.471679 -4625.372070 -220.812072" + "rotation" "15.114483 0.347351 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "FENCE_SKIP_HELPER_B2_TOP2" + { + "origin" "11368.471679 -4625.372070 -170.812072" + "rotation" "15.114483 0.347351 0.000000" + "type" "prop_dynamic" + "model" "props\cs_militia\footlocker01_closed.mdl" + } + "FENCE_SKIP_HELPER_B3" + { + "origin" "11318.471679 -4625.372070 -249.812072" + "rotation" "15.114483 0.347351 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "FENCE_SKIP_EXIT_STAIRS" + { + "origin" "11307.600585 -4320.291992 -325.535629" + "rotation" "0.901843 90.274330 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/stairs_house_01.mdl" + } + "FENCE_SKIP_EXIT_STAIRS_2" + { + "origin" "11306.600585 -4108.039062 -498.862701" + "rotation" "0.901843 90.274330 0.000000" + "type" "prop_dynamic" + "model" "props_exteriors/stairs_house_01.mdl" + } + "FENCE_SKIP_EXIT_STAIRS_SUPPORT" + { + + "origin" "11324.499023 -4397.913574 -469.508117" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_interiors\concretepillar01.mdl" + } + "FENCE_SKIP_EXIT_STAIRS_SUPPORT" + { + "origin" "11324.499023 -4397.913574 -341.508117" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_interiors\concretepillar01.mdl" + } + "MY_SKIP_SUPPORT" + { + "origin" "11070.869140 -5625.584960 -65.968738" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_swamp\plank001b_192.mdl" + } + "HOUSE_PLANKS" + { + "origin" "11070.869140 -5817.584960 -65.968738" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_swamp\plank001b_192.mdl" + } + "HOUSE_PLANKS" + { + "origin" "11070.869140 -6009.24960 -65.968738" + "rotation" "0 0 0" + "type" "prop_dynamic" + "model" "props_swamp\plank001b_192.mdl" + } + "ROOF_ACCESS" + { + "origin" "10692.570312 -7545.357910 -76.285079" + "rotation" "0.000000 -105.753463 0.000000" + "type" "prop_dynamic" + "model" "props\de_train\pallet_barrels.mdl" + } + "ROOF_ACCESS_TOP" + { + "origin" "10692.570312 -7545.357910 -26.285079" + "rotation" "0.000000 -105.753463 0.000000" + "type" "prop_dynamic" + "model" "props\de_train\pallet_barrels.mdl" + } + "ROOF_ACCESS_2" + { + "origin" "10692.479492 -7470.440917 -76.285079" + "rotation" "0.000000 -105.753463 0.000000" + "type" "prop_dynamic" + "model" "props\de_train\pallet_barrels.mdl" + } + "OUT_OF_BOUNDS_ROOF" + { + "origin" "10630.428710 -7433.587890 274.640625" + "rotation" "86.179300 -90.960174 0.000000" + "type" "prop_dynamic" + "model" "props_c17\utilitypole01d.mdl" + "set" "outbounds" + } + "ROOF_HELPER" + { + "origin" "10693.650390 -7695.398925 195.193389" + "rotation" "54.007286 -84.799293 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "BLOCK_SPAWN" + { + "type" "env_physics_blocker" + "origin" "10222.888671 -8366.800781 233.956771" + "scale" "55 400 300" + } + + "MYPROP" + { + "origin" "10693.677734 -7559.968750 25.075805" + "rotation" "0.000000 0.139984 0.000000" + "type" "_lantern" + "model" "props_unique/spawn_apartment/lantern.mdl" + } + } + } + "c13m2_southpinestream" + { + "spawnpoint" "7472.512695 2728.908203 454.170593" + "sets" + { + "A" + { + "spawnpoint" "631.415039 3729.930664 329.250244" + } + } + "ents" + { + "A_HELPER" + { + "origin" "3266.013671 2010.126708 458.291046" + "rotation" "0.000000 148.362182 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "FENCE_JUMPER" + { + "origin" "1832.684692 2264.726562 422.658752" + "rotation" "0.000000 70.022712 -4.000000" + "type" "prop_dynamic" + "model" "props_vehicles/cement_truck01.mdl" + } + "RETURNER" + { + "origin" "539.416015 2654.438476 177.077484" + "rotation" "-30.582356 8.396564 0.000000" + "type" "prop_dynamic" + "model" "props_vehicles/airplane_piperwreck.mdl" + } + "RETURNER_SUPPORT_A" + { + "origin" "630.816955 2635.709228 196.630294" + "rotation" "-8.000000 120.049987 -32.000000" + "type" "prop_dynamic" + "model" "props_vehicles/car005a.mdl" + } + "RETURNER_SUPPORT_B" + { + "origin" "539.403564 2561.882568 129.099700" + "rotation" "-30.000000 32.022949 0.000000" + "type" "prop_dynamic" + "model" "props_vehicles/car001a_phy.mdl" + } + "WALL" + { + "origin" "-837.842651 5280.024414 272.031250" + "rotation" "0.202026 -89.108253 0.000000" + "type" "prop_dynamic" + "model" "props_fortifications/concrete_wall001_96_reference.mdl" + } + "WALL_BLOCK" + { + "origin" "-837.842651 5280.024414 272.031250" + "type" "env_physics_blocker" + "scale" "66 26 200" + } + "RETURN_A" + { + "origin" "3874.732421 1896.033325 405.846710" + "rotation" "0.000000 37.927692 0.000000" + "type" "prop_dynamic" + "model" "props_crates/static_crate_40.mdl" + } + "SPAWN_BLOCK_PROP" + { + "origin" "7883.347167 3302.165527 534.600952" + "rotation" "0.000000 -5.696259 0.000000" + "type" "prop_dynamic" + "model" "props_wasteland/rock_cliff01.mdl" + } + "SPAWN_BLOCK" + { + + "origin" "7848.883300 3287.961914 794.680236" + "type" "env_physics_blocker" + "scale" "900 900 900" + } + "TANKER_SKIP" + { + "origin" "443.717864 4325.977050 497.610931" + "type" "env_physics_blocker" + "scale" "100 100 150" + } + "TANKER_SKIP_2" + { + "origin" "673.124267 4100.726562 558.114318" + "type" "env_physics_blocker" + "scale" "100 100 150" + } + } + } +} \ No newline at end of file diff --git a/data/prophunt/maps.cfg b/data/prophunt/maps.cfg new file mode 100644 index 0000000..1324fa5 --- /dev/null +++ b/data/prophunt/maps.cfg @@ -0,0 +1,28 @@ +"prophunt" +{ + "c1m1_hotel" + { + "props" + { + "SOFA_1" + { + "model" "props_urban/hotel_chair001.mdl" + "origin" "1532.456787 4609 1184" + "rotation" "0 323.5 0" + } + "SOFA_2" + { + "origin" "1649 4529 1184" + "rotation" "0 170 0" + "model" "props_urban/hotel_chair001.mdl" + } + } + } + "c8m1_apartments" + { + "props" + { + + } + } +} \ No newline at end of file diff --git a/data/prophunt/props.cfg b/data/prophunt/props.cfg new file mode 100644 index 0000000..c524e38 --- /dev/null +++ b/data/prophunt/props.cfg @@ -0,0 +1,23 @@ +"props" +{ + "props/cs_office/Fire_Extinguisher.mdl" "5" + "props_urban/ashtray_stand001.mdl" "5" + "props_furniture/hotel_chair.mdl" "10" + "props_urban/hotel_chair001.mdl" "20" + "props_interiors/tv.mdl" "10" + "props_downtown/ironing_board.mdl" "15" + "props_urban/hotel_lamp001.mdl" "10" + "props_windows/hotel_window_glass001.mdl" "30" + "props/cs_office/shelves_metal1.mdl" "50" + "props/cs_office/shelves_metal.mdl" "50" + "props_downtown/dresser.mdl" "50" + "props_interiors_Hotel_Cart.mdl" "40" + "props_downtown/side_table.mdl" "10" + "props_interiors/ac_wallunit.mdl" "30" + "props_downtown/bed_motel01.mdl" "50" + "props_interiors/coffee_table_oval.mdl" "20" + "props_downtown/mini_fridge.mdl" "10" + "props_interiors/fridge_mini.mdl" "10" + "props/cs_office/vending_machine.mdl" "50" + "props_interiors/toilet.mdl" "30" +} \ No newline at end of file diff --git a/data/randomizer/c1m1_hotel.json b/data/randomizer/c1m1_hotel.json new file mode 100644 index 0000000..43398dc --- /dev/null +++ b/data/randomizer/c1m1_hotel.json @@ -0,0 +1,26 @@ +{ + "group1": { + "chance": 0.1, + "exclusions": ["group2"], + "variants": [ + { + "weight": 1, + "entities": [ + + { + "origin": [1421.24, 5780.23, 2881.16], + "angles": [0.00, 0.00, 0.00], + "size": [5.00, 5.00, 5.00], + "model": "models/props/cs_assault/forklift.mdl" + }, + { + "origin": [1139.59, 5685.23, 2883.25], + "angles": [0.00, 0.00, 0.00], + "size": [5.00, 5.00, 5.00], + "model": "models/props_unique/airportdeparturescreen01.mdl" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/data/randomizer/c8m1_apartment.json b/data/randomizer/c8m1_apartment.json new file mode 100644 index 0000000..f9ae71b --- /dev/null +++ b/data/randomizer/c8m1_apartment.json @@ -0,0 +1,123 @@ +{ + "alleyskip": { + "chance": 0.30, + "variants": [ + { + "weight": 1, + "entities": [ + { + "model": "models/props_urban/fire_escape_wide_lower.mdl", + "origin": [2203.81, 2381.96, 212.84], + "angles": [0.00, 1.07, 0.00], + "size": [181.27, 2.22, 132.22] + }, + { + "model": "models/props_vehicles/ambulance.mdl", + "origin": [2317.06, 2282.30, 16.03], + "angles": [0.00, 270.39, 0.00], + "size": [90.09, 115.60, 109.48] + }, + { + "model": "models/props/cs_militia/boxes_garage_lower.mdl", + "origin": [2265.46, 2308.65, 124.13], + "angles": [0.00, 92.14, 0.00], + "size": [37.36, 35.15, 65.06] + }, + { + "model": "models/props_fortifications/barricade001_128_reference.mdl", + "origin": [2013.47, 2254.53, 15.83], + "angles": [0.00, 178.81, 0.00], + "size": [21.75, 48.25, 144.25] + }, + { + "model": "models/props_fortifications/barricade001_64_reference.mdl", + "origin": [2001.55, 2345.92, 15.51], + "angles": [0.00, 177.42, 0.00], + "size": [24.25, 24.25, 144.25] + } + ] + } + ] + }, + "mainblock": { + "chance": 0.5, + "variants": [ + { + "weight": 1, + "entities": [ + { + "model": "models/props_street/police_barricade2.mdl", + "origin": [2744.79, 3975.41, 16.03], + "angles": [0.00, 105.00, 0.00], + "size": [28.70, 71.14, 119.31] + }, + { + "model": "models/props_street/police_barricade_496in.mdl", + "origin": [2428.55, 3960.12, 8.03], + "angles": [0.00, 89.61, 0.00], + "size": [28.77, 245.37, 119.31] + }, + { + "model": "models/props_street/police_barricade2.mdl", + "origin": [2120.48, 3963.20, 16.03], + "angles": [0.00, 87.27, 0.00], + "size": [28.70, 71.14, 119.31] + } + ] + } + ] + }, + "subwayblock": { + "chance": 0.2, + "variants": [ + { + "entities": [ + { + "model": "models/props_vehicles/hmmwv.mdl", + "origin": [2755.60, 4139.53, 12.72], + "angles": [0.00, -180.00, 0.00], + "size": [57.97, 105.86, 124.61] + } + ] + }, + { + "entities": [ + { + "model": "models/props_vehicles/pickup_truck_78.mdl", + "origin": [2755.60, 4139.53, 12.72], + "angles": [0.00, -180.00, 0.00], + "size": [57.97, 105.86, 124.61] + } + ] + } + ] + }, + "doorblock": { + "chance": 0.2, + "variants": [ + { + "weight": 2, + "entities": [ + { + "model": "models/props_junk/dumpster.mdl", + "origin": [1519.27, 2626.97, 55.79], + "angles": [0.00, -86.23, 90.00], + "size": [26.37, 40.17, 54.13] + } + ] + }, + { + "weight": 1, + "entities": [ + { + "model": "models/props_junk/dumpster.mdl", + "origin": [1498.78, 2630.72, 16.03], + "angles": [0.00, 3.76, 0.00], + "size": [26.37, 40.17, 54.13] + } + ] + } + ] + } +} + diff --git a/data/walls_data.cfg b/data/walls_data.cfg new file mode 100644 index 0000000..a38dc1a --- /dev/null +++ b/data/walls_data.cfg @@ -0,0 +1,50 @@ +"WallData" +{ + "Shelter Fence" + { + "sizes" + { + "Small (64u)" + { + "model" "models/props_urban/fence_cover001_64.mdl" + } + "Medium (128u)" "models/props_urban/fence_cover001_128.mdl" + "Large (256u)" "models/props_urban/fence_cover001_256.mdl" + } + } + "Chain Link" + { + "sizes" + { + "Small (64u)" "models/props_urban/fence001_64.mdl" + "Medium (128u)" "models/props_urban/fence002_128.mdl" + "Large (256u)" "models/props_urban/fence002_256.mdl" + } + } + "Crash Barrier" + { + "sizes" + { + "Small" "models/props_fortifications/concrete_barrier01.mdl" + "Medium (96u)" "models/props_fortifications/concrete_barrier001_96_reference.mdl" + "Large (128u)" "models/props_fortifications/concrete_barrier001_128_reference.mdl" + } + } + "Sandbags" + { + "sizes" + { + "Normal (6l)" "models/props_fortifications/sandbags_line2.mdl" + "Corner (4l)" "models/props_fortifications/sandbags_corner3.mdl" + "Large (6l)" "models/props_fortifications/sandbags_corner2.mdl" + } + } + "Wooden Wall" + { + "sizes" + { + "Medium (128u)" "models/props_update/wood_128.mdl" + "Large (128u)" "models/props_update/wood_256.mdl" + } + } +} \ No newline at end of file diff --git a/gamedata/feedthetrolls.txt b/gamedata/feedthetrolls.txt new file mode 100644 index 0000000..e9c3305 --- /dev/null +++ b/gamedata/feedthetrolls.txt @@ -0,0 +1,16 @@ +"Games" +{ + "left4dead2" + { + "Signatures" + { + "WitchAttack::WitchAttack" + { + /* 55 8B EC 53 56 8B F1 C7 46 04 ? ? ? ? C7 46 2C 01 00 00 00 33 DB 33 C0 89 46 20 33 C9 89 4E 24 57 33 D2 89 56 28 33 FF 89 5E 0C 89 5E 10 89 5E 14 89 5E 18 89 5E 1C 89 5E 08 66 89 5E 30 89 7E 2C C7 06 ? ? ? ? C7 46 04 ? ? ? ? 53 */ + + "windows" "\x55\x8B\xEC\x53\x56\x8B\xF1\xC7\x46\x04\x2A\x2A\x2A\x2A\xC7\x46\x2C\x01\x00\x00\x00\x33\xDB\x33\xC0\x89\x46\x20\x33\xC9\x89\x4E\x24\x57\x33\xD2\x89\x56\x28\x33\xFF\x89\x5E\x0C\x89\x5E\x10\x89\x5E\x14\x89\x5E\x18\x89\x5E\x1C\x89\x5E\x08\x66\x89\x5E\x30\x89\x7E\x2C\xC7\x06\x2A\x2A\x2A\x2A\xC7\x46\x04\x2A\x2A\x2A\x2A\x53" + "linux" "@_ZN11WitchAttackC2EP11CBaseEntity" + } + } + } +} \ No newline at end of file diff --git a/gamedata/l4d2_turret.txt b/gamedata/l4d2_turret.txt new file mode 100644 index 0000000..b2d19e6 --- /dev/null +++ b/gamedata/l4d2_turret.txt @@ -0,0 +1,31 @@ +"Games" +{ + "left4dead2" + { + "Offsets" + { + "CBaseAnimating::StudioHdr" + { + "linux" "68" + } + } + "Signatures" + { + "CBaseAnimating::LookupPoseParameter" + { + "library" "server" + "linux" "@_ZN14CBaseAnimating19LookupPoseParameterEP10CStudioHdrPKc" + } + "ModelSoundsCache_LoadModel" + { + "library" "server" + "linux" "@_Z26ModelSoundsCache_LoadModelPKc" + } + "ModelSoundsCache_FinishModel" + { + "library" "server" + "linux" "@_Z28ModelSoundsCache_FinishModelP10CStudioHdr" + } + } + } +} \ No newline at end of file diff --git a/gamedata/l4d2tools.txt b/gamedata/l4d2tools.txt new file mode 100644 index 0000000..7b69321 --- /dev/null +++ b/gamedata/l4d2tools.txt @@ -0,0 +1,58 @@ +"Games" { + + "#default" { + "Offsets" { + "OS" { // Thank you Sammy-ROCK! + "windows" "1" + "linux" "0" + } + } + } + + // Big thanks to cravenge and Spirit_12 on AlliedModders for being awesome :D + + "left4dead2" { + "Signatures" { + "State_Transition" { + "library" "server" + "linux" "@_ZN9CCSPlayer16State_TransitionE13CSPlayerState" + "windows" "\x55\x8B\xEC\x56\x8B\xF1\x8B\x86\x2A\x2A\x2A\x2A\x57\x8B\x7D\x2A\x85\xC0\x74\x2A\x83" + /* 55 8B EC 56 8B F1 8B 86 ? ? ? ? 57 8B 7D ? 85 C0 74 ? 83 */ + } + + "TakeOverZombieBot" { + "library" "server" + "linux" "@_ZN13CTerrorPlayer17TakeOverZombieBotEPS_" + "windows" "\x55\x8B\xEC\x81\xEC\x2A\x2A\x2A\x2A\xA1\xD8\x2A\x2A\x2A\x33\xC5\x89\x45\x2A\x53\x8B\x5D\x2A\x80" + /* 55 8B EC 81 EC ? ? ? ? ? D8 ? ? ? 33 C5 89 45 ? 53 8B 5D ? 80 */ + } + + "RoundRespawn" { + "library" "server" + "linux" "@_ZN13CTerrorPlayer12RoundRespawnEv" + "windows" "\x56\x8B\xF1\xE8\x2A\x2A\x2A\x2A\xE8\x2A\x2A\x2A\x2A\x84\xC0\x75" + /* 56 8B F1 E8 ? ? ? ? E8 ? ? ? ? 84 C0 75 */ + } + + "SetHumanSpec" { + "library" "server" + "linux" "@_ZN11SurvivorBot17SetHumanSpectatorEP13CTerrorPlayer" + "windows" "\x55\x8B\xEC\x56\x8B\xF1\x83\xBE\x2A\x2A\x2A\x2A\x00\x7E\x07\x32\xC0\x5E\x5D\xC2\x04\x00\x8B\x0D" + /* 55 8B EC 56 8B F1 83 BE ? ? ? ? 00 7E 07 32 C0 5E 5D C2 04 00 8B 0D */ + } + "TakeOverBot" { + "library" "server" + "linux" "@_ZN13CTerrorPlayer11TakeOverBotEb" + "windows" "\x55\x8B\xEC\x81\xEC\x2A\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x33\xC5\x89\x45\xFC\x53\x56\x8D\x85" + /* 55 8B EC 81 EC ? ? ? ? A1 ? ? ? ? 33 C5 89 45 FC 53 56 8D 85 */ + } + "GoAwayFromKeyboard" + { + "library" "server" + "linux" "@_ZN13CTerrorPlayer18GoAwayFromKeyboardEv" + "windows" "\x2A\x2A\x2A\x2A\x2A\x2A\x53\x56\x57\x8B\xF1\x8B\x06\x8B\x90\xC8\x08\x00\x00" + /* ? ? ? ? ? ? 53 56 57 8B F1 8B 06 8B 90 C8 08 00 00 */ + } + } + } +} \ No newline at end of file diff --git a/plugins/200IQBots_FlyYouFools.smx b/plugins/200IQBots_FlyYouFools.smx new file mode 100644 index 0000000..35a605d Binary files /dev/null and b/plugins/200IQBots_FlyYouFools.smx differ diff --git a/plugins/AutoWarpBot.smx b/plugins/AutoWarpBot.smx new file mode 100644 index 0000000..c3d1b6e Binary files /dev/null and b/plugins/AutoWarpBot.smx differ diff --git a/plugins/BetterWitchAvoidance.smx b/plugins/BetterWitchAvoidance.smx new file mode 100644 index 0000000..be11d0c Binary files /dev/null and b/plugins/BetterWitchAvoidance.smx differ diff --git a/plugins/Block3Person.smx b/plugins/Block3Person.smx new file mode 100644 index 0000000..220db70 Binary files /dev/null and b/plugins/Block3Person.smx differ diff --git a/plugins/BumpMineGiver.smx b/plugins/BumpMineGiver.smx new file mode 100644 index 0000000..04a48d7 Binary files /dev/null and b/plugins/BumpMineGiver.smx differ diff --git a/plugins/CSGOTroll.smx b/plugins/CSGOTroll.smx new file mode 100644 index 0000000..5cae2d4 Binary files /dev/null and b/plugins/CSGOTroll.smx differ diff --git a/plugins/GrabEnt.smx b/plugins/GrabEnt.smx new file mode 100644 index 0000000..191128c Binary files /dev/null and b/plugins/GrabEnt.smx differ diff --git a/plugins/L4D2FFKickProtection.smx b/plugins/L4D2FFKickProtection.smx new file mode 100644 index 0000000..1c119ff Binary files /dev/null and b/plugins/L4D2FFKickProtection.smx differ diff --git a/plugins/L4D2PreventBotMovement.smx b/plugins/L4D2PreventBotMovement.smx new file mode 100644 index 0000000..2311438 Binary files /dev/null and b/plugins/L4D2PreventBotMovement.smx differ diff --git a/plugins/L4D2Template.smx b/plugins/L4D2Template.smx new file mode 100644 index 0000000..ae518c7 Binary files /dev/null and b/plugins/L4D2Template.smx differ diff --git a/plugins/L4D2Tools.smx b/plugins/L4D2Tools.smx new file mode 100644 index 0000000..9bd90f0 Binary files /dev/null and b/plugins/L4D2Tools.smx differ diff --git a/plugins/abm.smx b/plugins/abm.smx new file mode 100644 index 0000000..b316310 Binary files /dev/null and b/plugins/abm.smx differ diff --git a/plugins/activitymonitor.smx b/plugins/activitymonitor.smx new file mode 100644 index 0000000..69217ec Binary files /dev/null and b/plugins/activitymonitor.smx differ diff --git a/plugins/adminpanel.smx b/plugins/adminpanel.smx new file mode 100644 index 0000000..3c84337 Binary files /dev/null and b/plugins/adminpanel.smx differ diff --git a/plugins/basechat.smx b/plugins/basechat.smx new file mode 100644 index 0000000..c81a652 Binary files /dev/null and b/plugins/basechat.smx differ diff --git a/plugins/csgo-knifehp.smx b/plugins/csgo-knifehp.smx new file mode 100644 index 0000000..c3192c7 Binary files /dev/null and b/plugins/csgo-knifehp.smx differ diff --git a/plugins/csgo-misc.smx b/plugins/csgo-misc.smx new file mode 100644 index 0000000..fff0de8 Binary files /dev/null and b/plugins/csgo-misc.smx differ diff --git a/plugins/globalbans.smx b/plugins/globalbans.smx new file mode 100644 index 0000000..ffb780b Binary files /dev/null and b/plugins/globalbans.smx differ diff --git a/plugins/jutils.smx b/plugins/jutils.smx new file mode 100644 index 0000000..bba3408 Binary files /dev/null and b/plugins/jutils.smx differ diff --git a/plugins/l4d2-info-cmd.smx b/plugins/l4d2-info-cmd.smx new file mode 100644 index 0000000..c898c5c Binary files /dev/null and b/plugins/l4d2-info-cmd.smx differ diff --git a/plugins/l4d2-manual-director.smx b/plugins/l4d2-manual-director.smx new file mode 100644 index 0000000..c2e41db Binary files /dev/null and b/plugins/l4d2-manual-director.smx differ diff --git a/plugins/l4d2_TKStopper.smx b/plugins/l4d2_TKStopper.smx new file mode 100644 index 0000000..36f6926 Binary files /dev/null and b/plugins/l4d2_TKStopper.smx differ diff --git a/plugins/l4d2_ai_minigun.smx b/plugins/l4d2_ai_minigun.smx new file mode 100644 index 0000000..b1c23b1 Binary files /dev/null and b/plugins/l4d2_ai_minigun.smx differ diff --git a/plugins/l4d2_ai_tweaks.smx b/plugins/l4d2_ai_tweaks.smx new file mode 100644 index 0000000..0f561d8 Binary files /dev/null and b/plugins/l4d2_ai_tweaks.smx differ diff --git a/plugins/l4d2_autobotcrown.smx b/plugins/l4d2_autobotcrown.smx new file mode 100644 index 0000000..0d41327 Binary files /dev/null and b/plugins/l4d2_autobotcrown.smx differ diff --git a/plugins/l4d2_autorestart.smx b/plugins/l4d2_autorestart.smx new file mode 100644 index 0000000..1a6a5cd Binary files /dev/null and b/plugins/l4d2_autorestart.smx differ diff --git a/plugins/l4d2_avoid_minigun.smx b/plugins/l4d2_avoid_minigun.smx new file mode 100644 index 0000000..b8ebfd6 Binary files /dev/null and b/plugins/l4d2_avoid_minigun.smx differ diff --git a/plugins/l4d2_baseball.smx b/plugins/l4d2_baseball.smx new file mode 100644 index 0000000..623f516 Binary files /dev/null and b/plugins/l4d2_baseball.smx differ diff --git a/plugins/l4d2_crescendo_control.smx b/plugins/l4d2_crescendo_control.smx new file mode 100644 index 0000000..511a4d8 Binary files /dev/null and b/plugins/l4d2_crescendo_control.smx differ diff --git a/plugins/l4d2_detections.smx b/plugins/l4d2_detections.smx new file mode 100644 index 0000000..29e8fae Binary files /dev/null and b/plugins/l4d2_detections.smx differ diff --git a/plugins/l4d2_drop_secondary.smx b/plugins/l4d2_drop_secondary.smx new file mode 100644 index 0000000..d67c828 Binary files /dev/null and b/plugins/l4d2_drop_secondary.smx differ diff --git a/plugins/l4d2_extraplayeritems.smx b/plugins/l4d2_extraplayeritems.smx new file mode 100644 index 0000000..c00f92c Binary files /dev/null and b/plugins/l4d2_extraplayeritems.smx differ diff --git a/plugins/l4d2_feedthetrolls.smx b/plugins/l4d2_feedthetrolls.smx new file mode 100644 index 0000000..1003165 Binary files /dev/null and b/plugins/l4d2_feedthetrolls.smx differ diff --git a/plugins/l4d2_forceset.smx b/plugins/l4d2_forceset.smx new file mode 100644 index 0000000..71c5021 Binary files /dev/null and b/plugins/l4d2_forceset.smx differ diff --git a/plugins/l4d2_guesswho.smx b/plugins/l4d2_guesswho.smx new file mode 100644 index 0000000..267d711 Binary files /dev/null and b/plugins/l4d2_guesswho.smx differ diff --git a/plugins/l4d2_hats.smx b/plugins/l4d2_hats.smx new file mode 100644 index 0000000..fc5d48a Binary files /dev/null and b/plugins/l4d2_hats.smx differ diff --git a/plugins/l4d2_hideandseek.smx b/plugins/l4d2_hideandseek.smx new file mode 100644 index 0000000..c688540 Binary files /dev/null and b/plugins/l4d2_hideandseek.smx differ diff --git a/plugins/l4d2_perms.smx b/plugins/l4d2_perms.smx new file mode 100644 index 0000000..c7bee8e Binary files /dev/null and b/plugins/l4d2_perms.smx differ diff --git a/plugins/l4d2_population_control.smx b/plugins/l4d2_population_control.smx new file mode 100644 index 0000000..87c9c97 Binary files /dev/null and b/plugins/l4d2_population_control.smx differ diff --git a/plugins/l4d2_prophunt.smx b/plugins/l4d2_prophunt.smx new file mode 100644 index 0000000..d6f4a1a Binary files /dev/null and b/plugins/l4d2_prophunt.smx differ diff --git a/plugins/l4d2_randomizer.smx b/plugins/l4d2_randomizer.smx new file mode 100644 index 0000000..3d318d2 Binary files /dev/null and b/plugins/l4d2_randomizer.smx differ diff --git a/plugins/l4d2_rollback.smx b/plugins/l4d2_rollback.smx new file mode 100644 index 0000000..ca615c2 Binary files /dev/null and b/plugins/l4d2_rollback.smx differ diff --git a/plugins/l4d2_sb_fix.smx b/plugins/l4d2_sb_fix.smx new file mode 100644 index 0000000..e550586 Binary files /dev/null and b/plugins/l4d2_sb_fix.smx differ diff --git a/plugins/l4d2_skill_detect.smx b/plugins/l4d2_skill_detect.smx new file mode 100644 index 0000000..c1eca08 Binary files /dev/null and b/plugins/l4d2_skill_detect.smx differ diff --git a/plugins/l4d2_spawn_props.smx b/plugins/l4d2_spawn_props.smx new file mode 100644 index 0000000..89de08d Binary files /dev/null and b/plugins/l4d2_spawn_props.smx differ diff --git a/plugins/l4d2_special_control.smx b/plugins/l4d2_special_control.smx new file mode 100644 index 0000000..1421f26 Binary files /dev/null and b/plugins/l4d2_special_control.smx differ diff --git a/plugins/l4d2_swarm.smx b/plugins/l4d2_swarm.smx new file mode 100644 index 0000000..bdb7389 Binary files /dev/null and b/plugins/l4d2_swarm.smx differ diff --git a/plugins/l4d2_tank_priority.smx b/plugins/l4d2_tank_priority.smx new file mode 100644 index 0000000..9a69bef Binary files /dev/null and b/plugins/l4d2_tank_priority.smx differ diff --git a/plugins/l4d2_target_test.smx b/plugins/l4d2_target_test.smx new file mode 100644 index 0000000..12792f7 Binary files /dev/null and b/plugins/l4d2_target_test.smx differ diff --git a/plugins/l4d2_turret.smx b/plugins/l4d2_turret.smx new file mode 100644 index 0000000..f8e87f1 Binary files /dev/null and b/plugins/l4d2_turret.smx differ diff --git a/plugins/l4d2_vocalize_control.smx b/plugins/l4d2_vocalize_control.smx new file mode 100644 index 0000000..5c09fda Binary files /dev/null and b/plugins/l4d2_vocalize_control.smx differ diff --git a/plugins/l4d2_witch_force_attack_cmd.smx b/plugins/l4d2_witch_force_attack_cmd.smx new file mode 100644 index 0000000..599f950 Binary files /dev/null and b/plugins/l4d2_witch_force_attack_cmd.smx differ diff --git a/plugins/l4d_anti_rush.smx b/plugins/l4d_anti_rush.smx new file mode 100644 index 0000000..5450b62 Binary files /dev/null and b/plugins/l4d_anti_rush.smx differ diff --git a/plugins/l4d_reservetheserver.smx b/plugins/l4d_reservetheserver.smx new file mode 100644 index 0000000..89cc467 Binary files /dev/null and b/plugins/l4d_reservetheserver.smx differ diff --git a/plugins/l4d_survivor_identity_fix.smx b/plugins/l4d_survivor_identity_fix.smx new file mode 100644 index 0000000..c3835b9 Binary files /dev/null and b/plugins/l4d_survivor_identity_fix.smx differ diff --git a/plugins/l4d_tank_hp_sprite.smx b/plugins/l4d_tank_hp_sprite.smx new file mode 100644 index 0000000..5461441 Binary files /dev/null and b/plugins/l4d_tank_hp_sprite.smx differ diff --git a/plugins/l4d_target_override.smx b/plugins/l4d_target_override.smx new file mode 100644 index 0000000..c3887a0 Binary files /dev/null and b/plugins/l4d_target_override.smx differ diff --git a/plugins/l4dunreservelobby.smx b/plugins/l4dunreservelobby.smx new file mode 100644 index 0000000..8e92eca Binary files /dev/null and b/plugins/l4dunreservelobby.smx differ diff --git a/plugins/left4dhooks.smx b/plugins/left4dhooks.smx new file mode 100644 index 0000000..9d923b1 Binary files /dev/null and b/plugins/left4dhooks.smx differ diff --git a/plugins/misc.smx b/plugins/misc.smx new file mode 100644 index 0000000..07b1162 Binary files /dev/null and b/plugins/misc.smx differ diff --git a/plugins/sceneprocessor.smx b/plugins/sceneprocessor.smx new file mode 100644 index 0000000..80f9f3d Binary files /dev/null and b/plugins/sceneprocessor.smx differ diff --git a/plugins/sm_namespamblock.smx b/plugins/sm_namespamblock.smx new file mode 100644 index 0000000..bb0d236 Binary files /dev/null and b/plugins/sm_namespamblock.smx differ diff --git a/plugins/sm_player_notes.smx b/plugins/sm_player_notes.smx new file mode 100644 index 0000000..0c73931 Binary files /dev/null and b/plugins/sm_player_notes.smx differ diff --git a/plugins/sm_player_recorder.smx b/plugins/sm_player_recorder.smx new file mode 100644 index 0000000..ff4be29 Binary files /dev/null and b/plugins/sm_player_recorder.smx differ diff --git a/plugins/spray_control.smx b/plugins/spray_control.smx new file mode 100644 index 0000000..8697727 Binary files /dev/null and b/plugins/spray_control.smx differ diff --git a/scripting/200IQBots_FlyYouFools.sp b/scripting/200IQBots_FlyYouFools.sp new file mode 100644 index 0000000..e648d07 --- /dev/null +++ b/scripting/200IQBots_FlyYouFools.sp @@ -0,0 +1,202 @@ +#pragma semicolon 1 +#include +#include +#define PLUGIN_VERSION "1.5" +#pragma newdecls required + +#define MAX_TANK_DISTANCE_FROM_SURVIVOR 1000 +#define MAX_TANK_DIST_SQUARED MAX_TANK_DISTANCE_FROM_SURVIVOR^2 + +//#define DEBUG + +static bool bEscapeReady = false; +static int iAliveTanks; +static bool bIsTank[MAXPLAYERS+1]; + +public Plugin myinfo = +{ + name = "Fly You Fools", + author = "ConnerRia & Jackzmc", + description = "Survivor bots will retreat from tank. Improved version.", + version = PLUGIN_VERSION, + url = "N/A" +} + + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("Plugin supports Left 4 Dead series only."); + } + + CreateConVar("FlyYouFools_Version", PLUGIN_VERSION, "FlyYouFools Version", FCVAR_NOTIFY|FCVAR_REPLICATED|FCVAR_DONTRECORD); + + HookEvent("map_transition", Event_RoundStart, EventHookMode_PostNoCopy); + HookEvent("round_start", Event_RoundStart, EventHookMode_PostNoCopy); + HookEvent("tank_spawn", Event_TankSpawn); + HookEvent("tank_killed", Event_TankDeath); + HookEvent("finale_vehicle_incoming", Event_FinaleArriving, EventHookMode_PostNoCopy); +} + + +public void OnMapStart() { + resetPlugin(); +} + +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + resetPlugin(); +} + +public void Event_TankSpawn(Event event, const char[] name, bool dontBroadcast) { + int userID = GetClientOfUserId(GetEventInt(event, "userid")); + bIsTank[userID] = true; + if(iAliveTanks == 0 && !bEscapeReady) { + CreateTimer(0.1, BotControlTimerV2, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + } + iAliveTanks++; +} +public void Event_TankDeath(Event event, const char[] name, bool dontBroadcast) { + int userID = GetClientOfUserId(GetEventInt(event, "userid")); + bIsTank[userID] = false; + iAliveTanks--; +} +public void Event_FinaleArriving(Event event, const char[] name, bool dontBroadcast) { + bEscapeReady = true; +} +/* +CommandABot: +0 -> ATTACK +1 -> MOVETO +2 -> RUN AWAY +3 -> RESET + +New logic overview: +1. Loop all valid survivors +2. Loop all tanks per survivor +3. Find the closest tank +4. Retreat if in close range (~300 units) +*/ +Action BotControlTimerV2(Handle timer) +{ + //remove timer once tanks no longer exists/are all dead or finale escape vehicle arrived + if(bEscapeReady || iAliveTanks == 0) { + //Check if there is any existing bots, if escape NOT ready + if(!bEscapeReady) FindExistingTank(); + return Plugin_Stop; + } + if(iAliveTanks == 0 || GetClientCount(true) == 0) return Plugin_Continue; + + int botHealth, closestTank, tank_target; + float BotPosition[3], TankPosition[3], smallestDistance, distanceFromSurvivor; + + //Loop all players, finding survivors. (survivor team, bots, not tank.) + for (int i = 1; i <= MaxClients; i++) { + if (IsClientInGame(i) && IsPlayerAlive(i) && IsFakeClient(i) && !bIsTank[i] && GetClientTeam(i) == 2) { + //Grab health of bot and current position + botHealth = GetClientHealth(i); + GetClientAbsOrigin(i, BotPosition); + + smallestDistance = 0.0; + closestTank = -1; + //Loop all players, finding tanks (alive, bot, tank) + for(int tankID = 1; tankID <= MaxClients; tankID++) { + if (IsClientInGame(tankID) && IsPlayerAlive(tankID) && IsFakeClient(tankID) && bIsTank[tankID]) { + //Check if tank has a target. tank_target will be -1 if not activated + tank_target = GetEntPropEnt(tankID, Prop_Send, "m_lookatPlayer", 0); + if(tank_target > -1) { + + //Fetch the tank's position + GetClientAbsOrigin(tankID, TankPosition); + //Get distance to survivor, and compare to get closest tank + distanceFromSurvivor = GetVectorDistance(BotPosition, TankPosition, true); + if(distanceFromSurvivor <= MAX_TANK_DIST_SQUARED && smallestDistance > distanceFromSurvivor || smallestDistance == 0.0) { + smallestDistance = distanceFromSurvivor; + closestTank = tankID; + } + + } + } + } + //If the closest tank exists (-1 means no tank.) and is close, avoid. + if(closestTank > -1 && smallestDistance <= 300 && botHealth >= 40) { + //L4D2_RunScript("CommandABot({cmd=3,bot=GetPlayerFromUserID(%i)})", GetClientUserId(i)); + L4D2_RunScript("CommandABot({cmd=2,bot=GetPlayerFromUserID(%i),target=GetPlayerFromUserID(%i)})", GetClientUserId(i), GetClientUserId(closestTank)); + } + } + } + return Plugin_Continue; +} + +void resetPlugin() { + bEscapeReady = false; + iAliveTanks = 0; + FindExistingTank(); +} + + +void FindExistingTank() { + //Loop all valid clients, check if they a BOT and an infected. Check for a name that contains "Tank" + iAliveTanks = 0; + char name[16]; + for (int i = 1; i < MaxClients+1 ;i++) { + if(IsClientInGame(i) && IsFakeClient(i) && IsPlayerAlive(i) && GetClientTeam(i) == 3) { + GetClientName(i, name, sizeof(name)); + if(StrContains(name, "Tank", true) > -1) { + bIsTank[i] = true; + //PrintToServer("Found existing tank: %N (%i)", i, i); + iAliveTanks++; + continue; + } + } + bIsTank[i] = false; + + } + if(iAliveTanks > 0) { + CreateTimer(0.1, BotControlTimerV2, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + } +} + +//Credits to Timocop for the stock :D +/** +* Runs a single line of vscript code. +* NOTE: Dont use the "script" console command, it starts a new instance and leaks memory. Use this instead! +* +* @param sCode The code to run. +* @noreturn +*/ +stock void L4D2_RunScript(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} +/** +* Get the classname of an item in a slot +* +* @param client The client to check inventory from +* @param slot The item slot index +* @param buffer The char[] buffer to set text to +* @param bufferSize The size of the buffer +* @return True if item, false if no item +*/ +stock bool GetItemSlotClassName(int client, int slot, char[] buffer, int bufferSize) { + int item = GetPlayerWeaponSlot(client, slot); + if(item > -1) { + GetEdictClassname(item, buffer, bufferSize); + return true; + }else{ + return false; + } +} diff --git a/scripting/AutoWarpBot.sp b/scripting/AutoWarpBot.sp new file mode 100644 index 0000000..d79d17d --- /dev/null +++ b/scripting/AutoWarpBot.sp @@ -0,0 +1,81 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG + +#define PLUGIN_NAME "L4D2 Auto Warp Survivors" +#define PLUGIN_DESCRIPTION "" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +//#include + +#pragma newdecls required + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + +ConVar g_EnteredCheckpoint; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + HookEvent("player_entered_checkpoint", Event_PlayerEnteredCheckpoint); + HookEvent("player_left_start_area",Event_RoundStart); + g_EnteredCheckpoint = CreateConVar("awb_status", "0", "Get status of plugin", FCVAR_SPONLY | FCVAR_DONTRECORD, true, 0.0, true, 1.0); +} + +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + if(g_EnteredCheckpoint.BoolValue) g_EnteredCheckpoint.BoolValue = false; +} +public void Event_PlayerEnteredCheckpoint(Event event, const char[] name, bool dontBroadcast) { + PrintToChatAll("boolvalue %d | client %d", g_EnteredCheckpoint.BoolValue, GetClientOfUserId(event.GetInt("userid"))); + if(!g_EnteredCheckpoint.BoolValue) { + + int client = GetClientOfUserId(event.GetInt("userid")); + bool playersLeft = false; + for (int i = 1; i < MaxClients;i++) { + if (client == i) continue; + if (!IsClientInGame(i)) continue; + if (GetClientTeam(i) != 2) continue; + PrintToChatAll("playersLeft: %d . clientr %d", playersLeft, i); + if(!IsFakeClient(i)) { + playersLeft = true; + break; + } + } + if(!playersLeft) { + g_EnteredCheckpoint.BoolValue = true; + CheatCommand(client,"warp_all_survivors_to_checkpoint","",""); + } + } +} +stock bool IsPlayerIncapped(int client) +{ + if (GetEntProp(client, Prop_Send, "m_isIncapacitated", 1)) return true; + return false; +} + +stock void CheatCommand(int client, char[] command, char[] argument1, char[] argument2) +{ + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s %s", command, argument1, argument2); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} \ No newline at end of file diff --git a/scripting/BetterWitchAvoidance.sp b/scripting/BetterWitchAvoidance.sp new file mode 100644 index 0000000..095c9a2 --- /dev/null +++ b/scripting/BetterWitchAvoidance.sp @@ -0,0 +1,126 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define PLUGIN_NAME "Better Witch Avoidance" +#define PLUGIN_DESCRIPTION "Makes bots avoid witches better" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +//#include + + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + +static int iWitchEntity = -1; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + HookEvent("witch_spawn", Event_WitchSpawn); + HookEvent("witch_killed", Event_WitchKilled, EventHookMode_PostNoCopy); + //todo: existing witch find + //m_rage +} + + +public void Event_WitchSpawn(Event event, const char[] name, bool dontBroadcast) { + iWitchEntity = GetEventInt(event, "witchid"); + CreateTimer(0.1, BotControlTimer, _, TIMER_REPEAT); +} + +public void Event_WitchKilled(Event event, const char[] name, bool dontBroadcast) { + iWitchEntity = -1; +} +public Action BotControlTimer(Handle timer) +{ + //remove timer once witch is dead + if(iWitchEntity == -1 || !IsValidEntity(iWitchEntity)) { + //incase any other witches are available + //FindExistingWitch(); + return Plugin_Stop; + } + if(HasEntProp(iWitchEntity,Prop_Send,"m_rage")) { + float witch_anger = GetEntPropFloat(iWitchEntity, Prop_Send, "m_rage", 0); + if(FloatCompare(witch_anger,0.4) == 1) { + float WitchPosition[3]; + GetEntPropVector(iWitchEntity, Prop_Send, "m_vecOrigin", WitchPosition); + for (int i = 1; i < MaxClients; i++) { + if (IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2 && IsFakeClient(i)) { + float BotPosition[3]; + GetClientAbsOrigin(i, BotPosition); + + float distance = GetVectorDistance(BotPosition, WitchPosition); + if(distance <= 120 || (FloatCompare(witch_anger,0.6) == 1 && distance <= 220)) { + L4D2_RunScript("CommandABot({cmd=2,bot=GetPlayerFromUserID(%i),target=EntIndexToHScript(%d)})", GetClientUserId(i), iWitchEntity); + } + } + } + } + } + + return Plugin_Handled; +} +public void FindExistingWitch() { + for (int i = MaxClients + 1; i < GetMaxEntities(); i++) { + if(IsValidEntity(i)) { + char name[16]; + GetEntityClassname(i, name, sizeof(name)); + if(StrContains(name,"Witch",true) > -1) { + PrintToServer("Found existing witch with id %d", i); + iWitchEntity = i; + CreateTimer(0.1, BotControlTimer, _, TIMER_REPEAT); + break; + } + } + + } +} + +//Credits to Timocop for the stock :D +/** +* Runs a single line of vscript code. +* NOTE: Dont use the "script" console command, it starts a new instance and leaks memory. Use this instead! +* +* @param sCode The code to run. +* @noreturn +*/ +stock void L4D2_RunScript(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} +stock void ShowHintToAll(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + static int hintInt = 0; + if(hintInt >= 9) { + PrintHintTextToAll("%s",buffer); + hintInt = 0; + } + hintInt++; +} \ No newline at end of file diff --git a/scripting/Block3Person.sp b/scripting/Block3Person.sp new file mode 100644 index 0000000..cdf3a96 --- /dev/null +++ b/scripting/Block3Person.sp @@ -0,0 +1,123 @@ +#define PLUGIN_VERSION "1.1" + +#pragma semicolon 1 +#pragma newdecls required + +#include + +public Plugin myinfo = +{ + name = "Block3person", + author = "Dragokas", + description = "Block 3-rd person view by creating blindness", + version = PLUGIN_VERSION, + url = "https://github.com/dragokas" +} + +bool aBlinded[MAXPLAYERS]; +UserMsg g_FadeUserMsgId; + +static const int BLIND_DURATION = 50; + + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + char sGameName[12]; + GetGameFolderName(sGameName, sizeof(sGameName)); + if( strcmp(sGameName, "left4dead", false) ) + { + strcopy(error, err_max, "Plugin only supports Left 4 Dead 1."); + return APLRes_SilentFailure; + } + g_FadeUserMsgId = GetUserMessageId("Fade"); + if (g_FadeUserMsgId == INVALID_MESSAGE_ID) { + strcopy(error, err_max, "Cannot find Fade user message ID."); + return APLRes_SilentFailure; + } + return APLRes_Success; +} + +public void OnPluginStart() +{ + LoadTranslations("Block3Person.phrases"); + HookEvent("round_start", OnRoundStart, EventHookMode_PostNoCopy); +} + +public Action OnRoundStart(Event event, const char[] name, bool dontBroadcast) +{ + CreateTimer(0.9, Timer_CheckClientViewState, _, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); + return Plugin_Continue; +} + +public Action Timer_CheckClientViewState(Handle timer) +{ + for (int i = 1; i <= MaxClients; i++) + { + if(IsClientInGame(i) && GetClientTeam(i) == 2 && !IsFakeClient(i) && IsPlayerAlive(i)) + QueryClientConVar(i, "c_thirdpersonshoulder", QueryClientConVarCallback); + } + return Plugin_Continue; +} + +public void QueryClientConVarCallback(QueryCookie cookie, int client, ConVarQueryResult result, const char[] sCvarName, const char[] bCvarValue) +{ + if (StringToInt(bCvarValue) != 0) { + if (!aBlinded[client]) { + aBlinded[client] = true; + BlindClient(client, true); + PrintHintText(client, "%t", "Blind_Warning"); + } + } else { + if (aBlinded[client]) { + aBlinded[client] = false; + PrintHintText(client, "%t", "Unblind_tip"); + BlindClient(client, false); + } + } +} + +void BlindClient(int target, bool bDoBlind = true) +{ + int targets[2]; + targets[0] = target; + + int holdtime; + + int flags; + if (!bDoBlind) + { + flags = (0x0001 | 0x0010); + holdtime = 10000; + } + else + { + flags = (0x0002 | 0x0008); + holdtime = 10; + } + + int color[4] = { 0, 0, 0, 0 }; + color[3] = 255; + + Handle message = StartMessageEx(g_FadeUserMsgId, targets, 1); + if (GetUserMessageType() == UM_Protobuf) + { + Protobuf pb = UserMessageToProtobuf(message); + pb.SetInt("duration", BLIND_DURATION); + pb.SetInt("hold_time", holdtime); + pb.SetInt("flags", flags); + pb.SetColor("clr", color); + } + else + { + BfWrite bf = UserMessageToBfWrite(message); + bf.WriteShort(BLIND_DURATION); + bf.WriteShort(holdtime); + bf.WriteShort(flags); + bf.WriteByte(color[0]); + bf.WriteByte(color[1]); + bf.WriteByte(color[2]); + bf.WriteByte(color[3]); + } + + EndMessage(); +} \ No newline at end of file diff --git a/scripting/BumpMineGiver.sp b/scripting/BumpMineGiver.sp new file mode 100644 index 0000000..73b70e1 --- /dev/null +++ b/scripting/BumpMineGiver.sp @@ -0,0 +1,114 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_AUTHOR "" +#define PLUGIN_VERSION "0.00" + +#include +#include +#include +//#include + +#pragma newdecls required + +ConVar g_bmgTTeam, g_bmgEnabled, g_bmgCmdLimit; + +int g_bmgBumpsGiven[MAXPLAYERS+1]; + +public Plugin myinfo = +{ + name = "BumpMineGiver", + author = PLUGIN_AUTHOR, + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_CSGO && g_Game != Engine_CSS) + { + SetFailState("This plugin is for CSGO/CSS only."); + } + g_bmgEnabled = CreateConVar("bmg_enabled", "1", "Should BumpMineGiver be enabled?", FCVAR_NONE, true, 0.0, true, 1.0); + g_bmgTTeam = CreateConVar("bmg_restrict_team", "0", "Should BumpMineGiver be restricted to a team? 0 - All, 1 - Terrorists, 2 - CounterTerrorists", FCVAR_NONE, true, 0.0, true, 3.0); + g_bmgCmdLimit = CreateConVar("bmg_cmdlimit", "0", "Limit of amount of bumpmines to be given with !bmp. 0: Disabled, -1: Infinity", FCVAR_NONE); + HookEvent("round_start", Event_RoundStart); + HookEvent("player_spawn", Event_PlayerSpawn); + + RegConsoleCmd("sm_bmp", Command_GiveBMP, "Give yourself a bump mine"); + RegConsoleCmd("sm_bmg", Command_GiveBMP, "Give yourself a bump mine"); + RegAdminCmd("sm_givebmp", Command_GiveOthersBMP, ADMFLAG_CHEATS, "Give someone x amount of bump mines. Usage: sm_givebmp "); + AutoExecConfig(); +} + +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + for (int i = 0; i < sizeof(g_bmgBumpsGiven); i++) { + g_bmgBumpsGiven[i] = 0; + } +} + +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + if(g_bmgEnabled.BoolValue) { + int client = GetClientOfUserId(event.GetInt("userid")); + int wpn_id = GetPlayerWeaponSlot(client, 4); + int team = GetClientTeam(client); + if(g_bmgTTeam.IntValue > 0) { //1 or 2 + if (team != g_bmgTTeam.IntValue) return; + } + if(wpn_id == -1) { + GivePlayerItem(client, "weapon_bumpmine"); + } + } +} + +public Action Command_GiveBMP(int client, int args) { + if(g_bmgCmdLimit.IntValue == 0) { + ReplyToCommand(client, "You have hit the limit of bumpmines"); + return Plugin_Handled; + } + //limit is enabled, check + if(g_bmgCmdLimit.IntValue > 0) { + if(g_bmgBumpsGiven[client] > g_bmgCmdLimit.IntValue) { + ReplyToCommand(client, "You have hit the limit of bumpmines"); + return Plugin_Handled; + } + } + GivePlayerItem(client, "weapon_bumpmine"); + g_bmgBumpsGiven[client]++; + return Plugin_Handled; +} + +public Action Command_GiveOthersBMP(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_givebmp "); + }else{ + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) + { + GivePlayerItem(target_list[i], "weapon_bumpmine"); + LogAction(client, target_list[i], "\"%L\" gave \"%L\" a bumpmine", client, target_list[i]); + } + } + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/CSGOTroll.sp b/scripting/CSGOTroll.sp new file mode 100644 index 0000000..565415d --- /dev/null +++ b/scripting/CSGOTroll.sp @@ -0,0 +1,112 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_AUTHOR "" +#define PLUGIN_VERSION "0.00" + +#include +#include +#include +#include + +EngineVersion g_Game; +ConVar hTrollEnableState, hShotFailPercentage, hTrollTargets, hGunType; +bool TrollTargets[MAXPLAYERS+1], lateLoaded; + +public Plugin myinfo = +{ + name = "", + author = PLUGIN_AUTHOR, + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + if(late) { + lateLoaded = true; + } +} + +public OnPluginStart() +{ + g_Game = GetEngineVersion(); + if(g_Game != Engine_CSGO && g_Game != Engine_CSS) + { + SetFailState("This plugin is for CSGO/CSS only."); + } + //convars + hTrollEnableState = CreateConVar("troll_enable", "1.0", "Enable troll. 0 -> OFF, 1 -> Shots", FCVAR_NONE, true, 0.0, true, 1.0); + hShotFailPercentage = CreateConVar("troll_shot_fail_percentage", "0.4", "The percentage that the troll acts (shots fail). float 0-1", FCVAR_NONE, true, 0.0, true, 1.0); + hTrollTargets = CreateConVar("troll_targets", "", "comma seperated list of steamid64 targets (ex: STEAM_0:0:75141700)", FCVAR_NONE); + hGunType = CreateConVar("troll_shot_mode", "0", "0 -> ALL Weapons, 1 -> AWP", FCVAR_NONE, true, 0.0, true, 1.0); + + if(lateLoaded) FindExistingVictims(); +} + +public void OnClientAuthorized(int client, const char[] auth) { + if(hTrollEnableState.IntValue > 0) { + if(StrContains(auth, "BOT", true) == -1) { + TestForTrollUser(client, auth); + } + } +} +public void OnClientPutInServer(int client) { + SDKHook(client, SDKHook_OnTakeDamage, OnTakeDamage); +} +public OnClientDisconnect(int client) { + TrollTargets[client] = false; +} +public void FindExistingVictims() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientInGame(i) && IsClientAuthorized(i)) { + if(!IsFakeClient(i)) { + char auth[64]; + GetClientAuthId(i, AuthId_Steam2, auth, sizeof(auth)); + TestForTrollUser(i, auth); + } + SDKHook(i, SDKHook_OnTakeDamage, OnTakeDamage); + } + } +} +public bool TestForTrollUser(int client, const char[] auth) { + char targets[32][8]; + char raw_targets[64]; + hTrollTargets.GetString(raw_targets, sizeof(raw_targets)); + ExplodeString(raw_targets, ",", targets, 8, 32, false); + for(int i = 0; i < 8; i++) { + if(StrEqual(targets[i], auth, true)) { + PrintToServer("Troll victim detected with id %d and steamid %s", client, auth); + TrollTargets[client] = true; + return true; + } + } + return false; +} +public Action OnTakeDamage(int victim, int& attacker, int& inflictor, float& damage, int& damagetype, int& weapon, float damageForce[3], float damagePosition[3]) { + if(hTrollEnableState.IntValue == 1) { + if(TrollTargets[attacker]) { + bool try_failure = false; + char weapon_name[64]; + GetClientWeapon(victim, weapon_name, sizeof(weapon_name)); + + if(hGunType.IntValue == 0) { + try_failure = true; + }else{ + if(StrEqual(weapon_name, "weapon_awp", true)) { + try_failure = true; + } + + } + float random_float = GetURandomFloat(); + if(try_failure) { + if(FloatCompare(random_float, hShotFailPercentage.FloatValue) == -1) { + damage = 0.0; + return Plugin_Handled; + } + } + } + } + return Plugin_Continue; +} \ No newline at end of file diff --git a/scripting/GrabEnt.sp b/scripting/GrabEnt.sp new file mode 100644 index 0000000..80c94d1 --- /dev/null +++ b/scripting/GrabEnt.sp @@ -0,0 +1,594 @@ +#define DEBUG + +#define PLUGIN_AUTHOR "Stugger" +#define PLUGIN_VERSION "2.2" + +#include +#include +#include +#include + +public Plugin myinfo = +{ + name = "GrabEnt", + author = PLUGIN_AUTHOR, + description = "Grab then Move, Push/Pull or Rotate the entity you're looking at until released", + version = PLUGIN_VERSION, + url = "" +}; + +int g_pGrabbedEnt[MAXPLAYERS + 1]; +int g_eRotationAxis[MAXPLAYERS + 1] = { -1, ... }; +int g_eOriginalColor[MAXPLAYERS + 1][4]; + +float g_pLastButtonPress[MAXPLAYERS + 1]; +float g_fGrabOffset[MAXPLAYERS + 1][3]; +float g_fGrabDistance[MAXPLAYERS + 1]; + +MoveType g_pLastMoveType[MAXPLAYERS + 1]; +bool g_pInRotationMode[MAXPLAYERS + 1]; +bool g_eReleaseFreeze[MAXPLAYERS + 1] = { true, ... }; +bool g_bHighlightEntity[MAXPLAYERS+1]; + +Handle g_eGrabTimer[MAXPLAYERS+1]; + +int g_BeamSprite; +int g_HaloSprite; +int g_iLaserIndex; + +#define MAX_FORBIDDEN_CLASSNAMES 9 +static char FORBIDDEN_CLASSNAMES[MAX_FORBIDDEN_CLASSNAMES][] = { + // "env_physics_blocker", + // "env_player_blocker", + "func_brush", + "func_simpleladder", + "func_button", + "func_elevator", + "func_button_timed", + "func_movelinear", + "func_tracktrain", + // "infected", + "func_lod", + "prop_ragdoll" +}; + +#define MAX_FORBIDDEN_MODELS 1 +char FORBIDDEN_MODELS[MAX_FORBIDDEN_MODELS][] = { + "models/props_vehicles/c130.mdl", +}; + +#define MAX_HIGHLIGHTED_CLASSNAMES 3 +static char HIGHLIGHTED_CLASSNAMES[MAX_HIGHLIGHTED_CLASSNAMES][] = { + "env_physics_blocker", + "env_player_blocker", + "func_brush" +} + + +public void OnPluginStart() +{ + RegAdminCmd("sm_grabent_freeze", Cmd_ReleaseFreeze, ADMFLAG_CHEATS, "<0/1> - Toggle entity freeze/unfreeze on release."); + RegAdminCmd("sm_grab", Cmd_Grab, ADMFLAG_CHEATS, "Toggle Grab the entity in your crosshair."); + RegAdminCmd("+grabent", Cmd_Grab, ADMFLAG_CHEATS, "Grab the entity in your crosshair."); + RegAdminCmd("-grabent", Cmd_Release, ADMFLAG_CHEATS, "Release the grabbed entity."); +} + +public void OnMapStart() +{ + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt"); + g_BeamSprite = PrecacheModel("materials/sprites/laser.vmt", true); + g_HaloSprite = PrecacheModel("materials/sprites/halo01.vmt", true); + + for (int i = 0; i < MAXPLAYERS; i++) { + g_pGrabbedEnt[i] = -1; + g_eRotationAxis[i] = -1; + g_pLastButtonPress[i] = 0.0; + + g_pInRotationMode[i] = false; + g_eReleaseFreeze[i] = true; + + g_eGrabTimer[i] = null; + } +} +public void OnClientDisconnect(client) +{ + if (g_pGrabbedEnt[client] != -1 && IsValidEntity(g_pGrabbedEnt[client])) + Cmd_Release(client, 0); + + g_eRotationAxis[client] = -1; + + g_pLastButtonPress[client] = 0.0; + + g_pInRotationMode[client] = false; + g_eReleaseFreeze[client] = true; +} + +//============================================================================ +// FREEZE SETTING COMMAND // +//============================================================================ +public Action Cmd_ReleaseFreeze(client, args) +{ + if (args < 1) { + ReplyToCommand(client, "\x04[SM]\x01 \x05sm_grabent_freeze <0/1>\x01 -- \x050\x01: Entity unfreeze on release, \x051\x01: Entity freeze on release"); + return Plugin_Handled; + } + + char sArg[16]; + GetCmdArg(1, sArg, sizeof(sArg)); TrimString(sArg); + + if (!StrEqual(sArg, "0") && !StrEqual(sArg, "1")) { + ReplyToCommand(client, "\x04[SM]\x01 ERROR: Value can only be either 0 or 1"); + return Plugin_Handled; + } + + g_eReleaseFreeze[client] = StrEqual(sArg, "1"); + + PrintToChat(client, "\x04[SM]\x01 Entities will now be \x05%s\x01 on Release!", g_eReleaseFreeze[client] == true ? "Frozen" : "Unfrozen"); + return Plugin_Handled; +} + +//============================================================================ +// GRAB ENTITY COMMAND // +//============================================================================ +public Action Cmd_Grab(client, args) { + if (client < 1 || client > MaxClients || !IsClientInGame(client)) + return Plugin_Handled; + + if (g_pGrabbedEnt[client] > 0 && IsValidEntity(g_pGrabbedEnt[client])) { + Cmd_Release(client, 0); + return Plugin_Handled; + } + + // int ent = GetClientAimTarget(client, false); + int ent = GetLookingEntity(client, Filter_IgnoreForbidden); + + if (ent == -1 || !IsValidEntity(ent)) + return Plugin_Handled; //<-- timer to allow search for entity?? + + // Grab the parent + int parent = GetEntPropEnt(ent, Prop_Data, "m_hParent"); + if(parent > 0) { + ent = parent; + } + if(!CheckBlacklist(ent)) { + return Plugin_Handled; + } + + float entOrigin[3], playerGrabOrigin[3]; + GetEntPropVector(ent, Prop_Send, "m_vecOrigin", entOrigin); + GetClientEyePosition(client, playerGrabOrigin); + + g_pGrabbedEnt[client] = ent; + + // Get the point at which the ray first hit the entity + float initialRay[3]; + GetInitialRayPosition(client, initialRay); + + // Calculate the offset between intitial ray hit and the entities origin + g_fGrabOffset[client][0] = entOrigin[0] - initialRay[0]; + g_fGrabOffset[client][1] = entOrigin[1] - initialRay[1]; + g_fGrabOffset[client][2] = entOrigin[2] - initialRay[2]; + + // Calculate the distance between ent and player + float xDis = Pow(initialRay[0]-(playerGrabOrigin[0]), 2.0); + float yDis = Pow(initialRay[1]-(playerGrabOrigin[1]), 2.0); + float zDis = Pow(initialRay[2]-(playerGrabOrigin[2]), 2.0); + g_fGrabDistance[client] = SquareRoot((xDis)+(yDis)+(zDis)); + + // Get and Store entities original color (useful if colored) + int entColor[4]; + int colorOffset = GetEntSendPropOffs(ent, "m_clrRender"); + + if (colorOffset > 0) + { + entColor[0] = GetEntData(ent, colorOffset, 1); + entColor[1] = GetEntData(ent, colorOffset + 1, 1); + entColor[2] = GetEntData(ent, colorOffset + 2, 1); + entColor[3] = GetEntData(ent, colorOffset + 3, 1); + } + + g_eOriginalColor[client][0] = entColor[0]; + g_eOriginalColor[client][1] = entColor[1]; + g_eOriginalColor[client][2] = entColor[2]; + g_eOriginalColor[client][3] = entColor[3]; + + // Set entities color to grab color (green and semi-transparent) + SetEntityRenderMode(ent, RENDER_TRANSALPHA); + SetEntityRenderColor(ent, 0, 255, 0, 235); + + // Freeze entity + char sClass[64]; + GetEntityClassname(ent, sClass, sizeof(sClass)); TrimString(sClass); + + if (StrEqual(sClass, "player", false)) { + g_pLastMoveType[ent] = GetEntityMoveType(ent); + SetEntityMoveType(ent, MOVETYPE_NONE); + } else + AcceptEntityInput(ent, "DisableMotion"); + + + g_pLastMoveType[client] = GetEntityMoveType(client); + // Disable weapon prior to timer + SetWeaponDelay(client, 1.0); + + // Make sure rotation mode can immediately be entered + g_pLastButtonPress[client] = GetGameTime() - 2.0; + g_pInRotationMode[client] = false; + + g_bHighlightEntity[client] = false; + for(int i = 0; i < MAX_HIGHLIGHTED_CLASSNAMES; i++) { + if(StrEqual(HIGHLIGHTED_CLASSNAMES[i], sClass)) { + g_bHighlightEntity[client] = true; + break; + } + } + + DataPack pack; + g_eGrabTimer[client] = CreateDataTimer(0.1, Timer_UpdateGrab, pack, TIMER_REPEAT); + pack.WriteCell(client); + + return Plugin_Handled; +} + +//============================================================================ +// TIMER FOR GRAB ENTITY // +//============================================================================ +public Action Timer_UpdateGrab(Handle timer, DataPack pack) { + int client; + pack.Reset(); + client = pack.ReadCell(); + + if (!IsValidEntity(client) || client < 1 || client > MaxClients || !IsClientInGame(client)) + return Plugin_Stop; + + if (g_pGrabbedEnt[client] == -1 || !IsValidEntity(g_pGrabbedEnt[client])) + return Plugin_Stop; + + // Continuously delay use of weapon, as to not fire any bullets when pushing/pulling/rotating + SetWeaponDelay(client, 1.0); + + if(g_bHighlightEntity[client]) { + char targetname[64]; + GetEntPropString(g_pGrabbedEnt[client], Prop_Data, "m_iName", targetname, sizeof(targetname)); + PrintCenterText(client, "%s", targetname); + GlowEntity(client, g_pGrabbedEnt[client]); + } + + // *** Enable/Disable Rotation Mode + if (GetClientButtons(client) & IN_RELOAD) { + // Avoid instant enable/disable of rotation mode by requiring a one second buffer + if (GetGameTime() - g_pLastButtonPress[client] >= 1.0) { + g_pLastButtonPress[client] = GetGameTime(); + g_pInRotationMode[client] = g_pInRotationMode[client] == true ? false : true; + PrintToChat(client, "\x04[SM]\x01 Rotation Mode \x05%s\x01", g_pInRotationMode[client] == true ? "Enabled" : "Disabled"); + + // Restore the entities color and alpha if enabling + if(g_pInRotationMode[client]) { + SetEntityRenderColor(g_pGrabbedEnt[client], 255, 255, 255, 255); + PrintToChat(client, "\x05[A]\x01 RED \x05[S]\x01 GREEN \x05[D]\x01 BLUE \x05[W]\x01 SHOW RINGS"); + } + // Change back to grabbed color if disabling + else + SetEntityRenderColor(g_pGrabbedEnt[client], 0, 255, 0, 235); + } + } + // ***In Rotation Mode + if (g_pInRotationMode[client]) { + SetEntityMoveType(client, MOVETYPE_NONE); + + float ang[3], pos[3], mins[3], maxs[3]; + GetEntPropVector(g_pGrabbedEnt[client], Prop_Send, "m_angRotation", ang); + GetEntPropVector(g_pGrabbedEnt[client], Prop_Send, "m_vecOrigin", pos); + GetEntPropVector(g_pGrabbedEnt[client], Prop_Send, "m_vecMins", mins); + GetEntPropVector(g_pGrabbedEnt[client], Prop_Send, "m_vecMaxs", maxs); + + // If the entity is a child, it will have a null position, so we'll hesitantly use the parents position + int parent = GetEntPropEnt(g_pGrabbedEnt[client], Prop_Data, "m_hMoveParent"); + if (parent > 0 && IsValidEntity(parent)) + GetEntPropVector(parent, Prop_Send, "m_vecOrigin", pos); + + // Get rotation axis from button press + int buttonPress = GetClientButtons(client); + switch(buttonPress) { + case IN_FORWARD: { + g_eRotationAxis[client] = -1; // [W] = Show Rings + PrintToChat(client, "\x04[SM]\x01 Show Rings \x05On\x01"); + } + case IN_MOVELEFT: { + g_eRotationAxis[client] = 0; // [A] = x axis + PrintToChat(client, "\x04[SM]\x01 Rotation Axis \x05X\x01"); + } + case IN_BACK: { + g_eRotationAxis[client] = 1; // [S] = y axis + PrintToChat(client, "\x04[SM]\x01 Rotation Axis \x05Y\x01"); + } + case IN_MOVERIGHT: { + g_eRotationAxis[client] = 2; // [D] = z axis + PrintToChat(client, "\x04[SM]\x01 Rotation Axis \x05Z\x01"); + } + } + + + // Reset angles when A+S+D is pressed + if((buttonPress & IN_MOVELEFT) && (buttonPress & IN_BACK) && (buttonPress & IN_MOVERIGHT)) { + ang[0] = 0.0; ang[1] = 0.0; ang[2] = 0.0; + g_eRotationAxis[client] = -1; + } + + // Largest side should dictate the diameter of the rings + float diameter, sendAng[3]; + diameter = (maxs[0] > maxs[1]) ? (maxs[0] + 10.0) : (maxs[1] + 10.0); + diameter = ((maxs[2] + 10.0) > diameter) ? (maxs[2] + 10.0) : diameter; + + // Sending original ang will cause non-stop rotation issue + sendAng = ang; + + // Draw rotation rings + switch(g_eRotationAxis[client]) { + case -1: CreateRing(client, sendAng, pos, diameter, 0, true); // all 3 rings + case 0: CreateRing(client, sendAng, pos, diameter, 0, false); // red (x) + case 1: CreateRing(client, sendAng, pos, diameter, 1, false); // green (y) + case 2: CreateRing(client, sendAng, pos, diameter, 2, false); // blue (z) + } + + // Rotate with mouse if on a rotation axis (A,S,D) + if (g_eRotationAxis[client] != -1) { + // + Rotate + if (GetClientButtons(client) & IN_ATTACK) + ang[g_eRotationAxis[client]] += 10.0; + // - Rotate + else if (GetClientButtons(client) & IN_ATTACK2) + ang[g_eRotationAxis[client]] -= 10.0; + } + + TeleportEntity(g_pGrabbedEnt[client], NULL_VECTOR, ang, NULL_VECTOR); + } + // ***Not in Rotation Mode + if (!g_pInRotationMode[client] || g_eRotationAxis[client] == -1) { + // Keep track of player noclip as to avoid forced enable/disable + if(!g_pInRotationMode[client]) { + SetEntityMoveType(client, g_pLastMoveType[client]) + } + // Push entity (Allowed if we're in rotation mode, not on a rotation axis (-1)) + if (GetClientButtons(client) & IN_ATTACK) + { + if (g_fGrabDistance[client] < 80) + g_fGrabDistance[client] += 10; + else + g_fGrabDistance[client] += g_fGrabDistance[client] / 25; + } + // Pull entity (Allowed if we're in rotation mode, not on a rotation axis (-1)) + else if (GetClientButtons(client) & IN_ATTACK2 && g_fGrabDistance[client] > 25) + { + if (g_fGrabDistance[client] < 80) + g_fGrabDistance[client] -= 10; + else + g_fGrabDistance[client] -= g_fGrabDistance[client] / 25; + } + + g_eRotationAxis[client] = -1; + } + + // *** Runs whether in rotation mode or not + float entNewPos[3]; + int buttons = GetClientButtons(client); + GetEntNewPosition(client, entNewPos, buttons & IN_SPEED == 0); + entNewPos[0] += g_fGrabOffset[client][0]; + entNewPos[1] += g_fGrabOffset[client][1]; + entNewPos[2] += g_fGrabOffset[client][2]; + + + float mins[3]; + GetEntPropVector(g_pGrabbedEnt[client], Prop_Data, "m_vecMins", mins); + entNewPos[2] -= mins[2]; + + TeleportEntity(g_pGrabbedEnt[client], entNewPos, NULL_VECTOR, NULL_VECTOR); + + return Plugin_Handled; +} + +//============================================================================ +// RELEASE ENTITY COMMAND // +//============================================================================ +public Action Cmd_Release(client, args) { + if (!IsValidEntity(client) || client < 1 || client > MaxClients || !IsClientInGame(client)) + return Plugin_Handled; + + if (g_pGrabbedEnt[client] == -1 || !IsValidEntity(g_pGrabbedEnt[client])) + return Plugin_Handled; + + // Allow near-immediate use of weapon + SetWeaponDelay(client, 0.2); + + SetEntityMoveType(client, g_pLastMoveType[client]); + + + // Unfreeze if target was a player and unfreeze if setting is set to 0 + char sClass[64]; + GetEntityClassname(g_pGrabbedEnt[client], sClass, sizeof(sClass)); TrimString(sClass); + + if (StrEqual(sClass, "player", false)) + SetEntityMoveType(g_pGrabbedEnt[client], g_pLastMoveType[g_pGrabbedEnt[client]]); + else if (g_eReleaseFreeze[client] == false) + AcceptEntityInput(g_pGrabbedEnt[client], "EnableMotion"); + + // Restore color and alpha to original prior to grab + SetEntityRenderColor(g_pGrabbedEnt[client], g_eOriginalColor[client][0], g_eOriginalColor[client][1], g_eOriginalColor[client][2], g_eOriginalColor[client][3]); + + // Kill the grab timer and reset control values + if (IsValidHandle(g_eGrabTimer[client])) { + delete g_eGrabTimer[client]; + } + + g_pGrabbedEnt[client] = -1; + g_eRotationAxis[client] = -1; + g_pInRotationMode[client] = false; + + return Plugin_Handled; +} + +//============================================================================ +// *** UTILITIES *** // +//============================================================================ +int GetLookingEntity(int client, TraceEntityFilter filter) { + static float pos[3], ang[3]; + GetClientEyePosition(client, pos); + GetClientEyeAngles(client, ang); + TR_TraceRayFilter(pos, ang, MASK_ALL, RayType_Infinite, filter, client); + if(TR_DidHit()) { + return TR_GetEntityIndex(); + } + return -1; +} + +stock bool GetEntNewPosition(int client, float endPos[3], bool doCollision = true) +{ + if (client > 0 && client <= MaxClients && IsClientInGame(client)) { + float clientEye[3], clientAngle[3], direction[3]; + GetClientEyePosition(client, clientEye); + GetClientEyeAngles(client, clientAngle); + + GetAngleVectors(clientAngle, direction, NULL_VECTOR, NULL_VECTOR); + ScaleVector(direction, g_fGrabDistance[client]); + AddVectors(clientEye, direction, endPos); + + if(doCollision) { + TR_TraceRayFilter(clientEye, endPos, MASK_OPAQUE, RayType_EndPoint, TraceRayFilterEnt, client); + if (TR_DidHit(INVALID_HANDLE)) { + TR_GetEndPosition(endPos); + } + } + return true; + } + + return false; +} +///// +stock bool GetInitialRayPosition(int client, float endPos[3]) +{ + if (client > 0 && client <= MaxClients && IsClientInGame(client)) { + float clientEye[3], clientAngle[3]; + GetClientEyePosition(client, clientEye); + GetClientEyeAngles(client, clientAngle); + + TR_TraceRayFilter(clientEye, clientAngle, MASK_SOLID, RayType_Infinite, TraceRayFilterActivator, client); + if (TR_DidHit(INVALID_HANDLE)) + TR_GetEndPosition(endPos); + return true; + } + return false; +} +///// +stock void SetWeaponDelay(int client, float delay) +{ + if (IsValidEntity(client) && client > 0 && client <= MaxClients && IsClientInGame(client)) { + int pWeapon = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"); + + if (IsValidEntity(pWeapon) && pWeapon != -1) { + SetEntPropFloat(pWeapon, Prop_Send, "m_flNextPrimaryAttack", GetGameTime() + delay); + SetEntPropFloat(pWeapon, Prop_Send, "m_flNextSecondaryAttack", GetGameTime() + delay); + } + } +} +///// +stock void CreateRing(int client, float ang[3], float pos[3], float diameter, int axis, bool trio) +{ + if (!IsValidEntity(client) || client < 1 || client > MaxClients || !IsClientInGame(client)) + return; + + float ringVecs[26][3]; + int ringColor[3][4]; + + ringColor[0] = { 255, 0, 0, 255 }; + ringColor[1] = { 0, 255, 0, 255 }; + ringColor[2] = { 0, 0, 255, 255 }; + + int numSides = (!trio) ? 26 : 17; + float angIncrement = (!trio) ? 15.0 : 24.0; + + for (int i = 1; i < numSides; i++) { + float direction[3], endPos[3]; + switch(axis) { + case 0: GetAngleVectors(ang, direction, NULL_VECTOR, NULL_VECTOR); + case 1: + { + ang[2] = 0.0; + GetAngleVectors(ang, NULL_VECTOR, direction, NULL_VECTOR); + } + case 2: GetAngleVectors(ang, NULL_VECTOR, NULL_VECTOR, direction); + } + + ScaleVector(direction, diameter); + AddVectors(pos, direction, endPos); + + if (i == 1) ringVecs[0] = endPos; + + ringVecs[i] = endPos; + ang[axis] += angIncrement; + + TE_SetupBeamPoints(ringVecs[i-1], ringVecs[i], g_BeamSprite, g_HaloSprite, 0, 15, 0.2, 2.5, 2.5, 1, 0.0, ringColor[axis], 10); + TE_SendToClient(client, 0.0); + + if(trio && i == numSides-1 && axis < 2) { + i = 0; + ang[axis] -= angIncrement * (numSides-1); + axis += 1; + } + } +} + +void GlowEntity(int client, int entity) { + float pos[3], mins[3], maxs[3], angles[3]; + GetEntPropVector(entity, Prop_Send, "m_angRotation", angles); + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + GetEntPropVector(entity, Prop_Send, "m_vecMins", mins); + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", maxs); + Effect_DrawBeamBoxRotatableToClient(client, pos, mins, maxs, angles, g_iLaserIndex, 0, 0, 30, 0.1, 0.4, 0.4, 0, 0.1, { 0, 255, 0, 235 }, 0); +} + +//============================================================================ +// *** FILTERS *** // +//============================================================================ + +public bool TraceRayFilterEnt(int entity, int mask, any:client) +{ + if (entity == client || entity == g_pGrabbedEnt[client]) + return false; + return true; +} +///// +public bool TraceRayFilterActivator(int entity, int mask, any:activator) +{ + if (entity == activator) + return false; + return true; +} + +bool Filter_IgnoreForbidden(int entity, int mask, int data) { + if(entity == data || entity == 0) return false; + if(entity <= MaxClients) return true; + return CheckBlacklist(entity); +} + +bool CheckBlacklist(int entity) { + static char buffer[64]; + GetEntityClassname(entity, buffer, sizeof(buffer)); + for(int i = 0; i < MAX_FORBIDDEN_CLASSNAMES; i++) { + if(StrEqual(FORBIDDEN_CLASSNAMES[i], buffer)) { + return false; + } + } + if(StrContains(buffer, "prop_") > -1) { + GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, sizeof(buffer)); + for(int i = 0; i < MAX_FORBIDDEN_MODELS; i++) { + if(StrEqual(FORBIDDEN_MODELS[i], buffer)) { + return false; + } + } + } + GetEntPropString(entity, Prop_Data, "m_iName", buffer, sizeof(buffer)); + if(StrEqual(buffer, "l4d2_randomizer")) { + return false; + } + return true; +} \ No newline at end of file diff --git a/scripting/L4D2FFKickProtection.sp b/scripting/L4D2FFKickProtection.sp new file mode 100644 index 0000000..aef8057 --- /dev/null +++ b/scripting/L4D2FFKickProtection.sp @@ -0,0 +1,141 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define ANTI_ADMIN_KICK_MIN_TIME 120 // The number of seconds after joining where vote kicking an admin, kicks the caller +#define PLUGIN_VERSION "1.1" + +#include +#include +#include + +static int disableFFClient = -1, ffDamageCount; //client to disable FF for +static ConVar forceKickFFThreshold; + +public Plugin myinfo = { + name = "L4D2 FF Kick Protection", + author = "jackzmc", + description = "Prevents friendly firing from players being voted off and admins from being kicked", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + AddCommandListener(VoteStart, "callvote"); + HookUserMessage(GetUserMessageId("VotePass"), VotePassFail); + HookUserMessage(GetUserMessageId("VoteFail"), VotePassFail); + + forceKickFFThreshold = CreateConVar("sm_votekick_force_threshold","30.0","The threshold of amount of FF to then automatically kick.\n0: Any attempted damage\n -1: No auto kick.\n>0: When FF count > this", FCVAR_NONE, true, -1.0); +} + + +int iJoinTime[MAXPLAYERS+1]; +public void OnClientPutInServer(int client) { + int team = GetClientTeam(client); + if(team == 2) { + SDKHook(client, SDKHook_OnTakeDamageAlive, OnTakeDamage); + } + iJoinTime[client] = GetTime(); +} + +public void Event_PlayerTeam(Event event, const char[] name, bool dontBroadcast) { + if(!event.GetBool("disconnect")) { + int team = event.GetInt("team"); + int userid = GetClientOfUserId(event.GetInt("userid")); + if(team == 2) { + SDKHook(userid, SDKHook_OnTakeDamageAlive, OnTakeDamage); + //add new hook + }else{ + SDKUnhook(userid, SDKHook_OnTakeDamageAlive, OnTakeDamage); + } + } +} +public Action VoteStart(int client, const char[] command, int argc) { + if(!IsClientInGame(client)) { + PrintToServer("Preventing vote from user not in game: %N", client); + return Plugin_Handled; + } + if(GetClientCount(true) == 0 || client == 0 || client >= MaxClients) return Plugin_Handled; //prevent votes while server is empty or if server tries calling vote + if(argc >= 1) { + char issue[32]; + + GetCmdArg(1, issue, sizeof(issue)); + + if(StrEqual(issue, "Kick", false)) { + char option[32]; + GetCmdArg(2, option, sizeof(option)); + + if(strlen(option) > 1) { //empty userid/console can't call votes + int target = GetClientOfUserId(StringToInt(option)); + if(target <= 0 || target >= MaxClients || !IsClientInGame(target)) return Plugin_Continue; //invalid, pass it through + AdminId targetAdmin = GetUserAdmin(target); + bool isCallerAdmin = GetUserFlagBits(client) != 0; + bool isTargetAdmin = GetUserFlagBits(target) != 0; + PrintToServer("Caller Admin: %b | Target admin: %b", isCallerAdmin, isTargetAdmin); + //Only run if vote is against an admin + if(isTargetAdmin) { + for(int i = 1; i <= MaxClients; i++) { + if(target != i && IsClientInGame(i) && GetUserAdmin(i) != INVALID_ADMIN_ID) { + PrintToChat(i, "%N attempted to vote-kick admin %N", client, target); + } + } + // Kick player if they are not an admin and just recently joined. + // Else, just tell the target + if(!isCallerAdmin && GetTime() - iJoinTime[client] <= ANTI_ADMIN_KICK_MIN_TIME) { + if(GetClientTeam(target) >= 2) { + KickClient(client, "No."); + PrintToChat(target, "%N has attempted to vote kick you and was kicked.", client); + } else { + PrintToChat(client, "%N is an admin and cannot be vote kicked", target); + PrintToChat(target, "%N has attempted to kick you while you were afk.", client); + } + } else { + PrintToChat(target, "%N has attempted to vote kick you.", client); + } + // TODO: remove debug + targetAdmin.GetUsername(option, sizeof(option)); + PrintToServer("debug: admin immunity is %d. username: %s", targetAdmin.ImmunityLevel, option); + PrintToServer("ADMIN VOTE KICK BLOCKED | Target=%N | Caller=%N", target, client); + return Plugin_Handled; + } else if(isCallerAdmin) { + PrintToServer("Vote kick by admin, instantly passing"); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i) && GetClientTeam(i) == GetClientTeam(target)) { + ClientCommand(i, "vote Yes"); + } + } + } + if(GetClientTeam(target) == 2) { + disableFFClient = target; + ffDamageCount = 0; + } + PrintToServer("VOTE KICK STARTED | Target=%N | Caller=%N", target, client); + return Plugin_Continue; + } + } + } + return Plugin_Continue; +} + +public Action VotePassFail(UserMsg msg_id, BfRead msg, const int[] players, int playersNum, bool reliable, bool init) { + disableFFClient = -1; + ffDamageCount = 0; + return Plugin_Continue; +} + +public Action OnTakeDamage(int victim, int& attacker, int& inflictor, float& damage, int& damagetype, int& weapon, float damageForce[3], float damagePosition[3]) { + if(disableFFClient == attacker && damage > 0.0 && victim > 0 && victim <= MaxClients && GetClientTeam(victim) == 2) { + if(forceKickFFThreshold.IntValue > -1 && ffDamageCount > 0.0) { + //auto kick + if(ffDamageCount > forceKickFFThreshold.FloatValue) { + BanClient(disableFFClient, 0, 0, "Kicked for excessive friendly fire", "Dick-Be-Gone", "noFF"); + } + } + return Plugin_Handled; + } + return Plugin_Continue; +} diff --git a/scripting/L4D2PreventBotMovement.sp b/scripting/L4D2PreventBotMovement.sp new file mode 100644 index 0000000..822071e --- /dev/null +++ b/scripting/L4D2PreventBotMovement.sp @@ -0,0 +1,57 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_NAME "L4D2 Prevent Bot Movement" +#define PLUGIN_DESCRIPTION "Prevents bots from moving in the beginning of the round for a set period of time." +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +//#include + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + +static ConVar hSBStop, hStopTime; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + HookEvent("round_start",Event_RoundStart); + + hStopTime = CreateConVar("sm_freeze_bot_time","20.0","How long should the bots be frozen for on beginning of round? 0 to disable",FCVAR_NONE,true,0.0); + hSBStop = FindConVar("sb_stop"); +} +public void OnMapStart() { + if(hStopTime.IntValue != 0) { + PrintToChatAll("round start"); + hSBStop.BoolValue = true; + CreateTimer(hStopTime.FloatValue, ResumeBots); + } +} + +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + if(hStopTime.IntValue != 0) { + PrintToChatAll("round start"); + hSBStop.BoolValue = true; + CreateTimer(hStopTime.FloatValue, ResumeBots); + } +} +public Action ResumeBots(Handle timer) { + PrintToChatAll("Resuming bots"); + hSBStop.BoolValue = false; +} diff --git a/scripting/L4D2Tools.sp b/scripting/L4D2Tools.sp new file mode 100644 index 0000000..5125faa --- /dev/null +++ b/scripting/L4D2Tools.sp @@ -0,0 +1,836 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG 1 + +#define PLUGIN_VERSION "1.0" + +#define PRECACHE_SOUNDS_COUNT 5 +char PRECACHE_SOUNDS[PRECACHE_SOUNDS_COUNT][] = { + "custom/meow1.mp3", + "custom/xen_teleport.mp3", + "custom/mariokartmusic.mp3", + "custom/spookyscaryskeletons.mp3", + "custom/wearenumberone2.mp3" +}; + +#include +#include +#include +#include +#include +#include +#include "l4d_survivor_identity_fix.inc" + +char MODELS[8][] = { + "models/survivors/survivor_gambler.mdl", + "models/survivors/survivor_producer.mdl", + "models/survivors/survivor_mechanic.mdl", + "models/survivors/survivor_coach.mdl", + "models/survivors/survivor_namvet.mdl", + "models/survivors/survivor_teenangst.mdl", + "models/survivors/survivor_biker.mdl", + "models/survivors/survivor_manager.mdl" +}; + +enum L4DModelId { + Model_Nick, + Model_Rochelle, + Model_Ellis, + Model_Coach, + Model_Bill, + Model_Zoey, + Model_Francis, + Model_Louis +} + +static ArrayList LasersUsed; +static ConVar hLaserNotice, hFinaleTimer, hFFNotice, hPingDropThres, hForceSurvivorSet, hPlayerLimit, hSVMaxPlayers, hHideMotd, hGamemode; +static int iFinaleStartTime, botDropMeleeWeapon[MAXPLAYERS+1], iHighPingCount[MAXPLAYERS+1]; +static bool isHighPingIdle[MAXPLAYERS+1], isL4D1Survivors; +static Handle hGoAwayFromKeyboard; +static StringMap SteamIDs; +static char lastSound[MAXPLAYERS+1][64], gamemode[32]; + +static float OUT_OF_BOUNDS[3] = {0.0, -1000.0, 0.0}; + +public Plugin myinfo = { + name = "L4D2 Misc Tools", + author = "Includes: Notice on laser use, Timer for gauntlet runs", + description = "jackzmc", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +//TODO: On pickup ammo pack, mark dropped kit/defib + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + MarkNativeAsOptional("IdentityFix_SetPlayerModel"); + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + LoadTranslations("common.phrases"); + Handle hConfig = LoadGameConfigFile("l4d2tools"); + if(hConfig == INVALID_HANDLE) SetFailState("Could not load l4d2tools gamedata."); + + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(hConfig, SDKConf_Signature, "GoAwayFromKeyboard"); + hGoAwayFromKeyboard = EndPrepSDKCall(); + delete hConfig; + + if(hGoAwayFromKeyboard == INVALID_HANDLE) { + SetFailState("GoAwayFromKeyboard signature is invalid"); + } + + hLaserNotice = CreateConVar("sm_laser_use_notice", "1.0", "Enable notification of a laser box being used", FCVAR_NONE, true, 0.0, true, 1.0); + hFinaleTimer = CreateConVar("sm_time_finale", "0.0", "Record the time it takes to complete finale. 0 -> OFF, 1 -> Gauntlets Only, 2 -> All finales", FCVAR_NONE, true, 0.0, true, 2.0); + hFFNotice = CreateConVar("sm_ff_notice", "0.0", "Notify players if a FF occurs. 0 -> Disabled, 1 -> In chat, 2 -> In Hint text", FCVAR_NONE, true, 0.0, true, 2.0); + hPingDropThres = CreateConVar("sm_autoidle_ping_max", "0.0", "The highest ping a player can have until they will automatically go idle.\n0=OFF, Min is 30", FCVAR_NONE, true, 0.0, true, 1000.0); + hForceSurvivorSet = FindConVar("l4d_force_survivorset"); + hHideMotd = CreateConVar("sm_hidemotd", "1", "Hide the MOTD when the server is running", FCVAR_NONE, true, 0.0, true, 1.0); + + hSVMaxPlayers = FindConVar("sv_maxplayers"); + if(hSVMaxPlayers != null) { + hPlayerLimit = CreateConVar("sm_player_limit", "0", "Overrides sv_maxplayers. 0 = off, > 0: limit", FCVAR_NONE, true, 0.0, false); + hPlayerLimit.AddChangeHook(Event_PlayerLimitChange); + hSVMaxPlayers.IntValue = hPlayerLimit.IntValue; + } + + hFFNotice.AddChangeHook(CVC_FFNotice); + if(hFFNotice.IntValue > 0) { + HookEvent("player_hurt", Event_PlayerHurt); + } + + LasersUsed = new ArrayList(1, 0); + SteamIDs = new StringMap(); + + hGamemode = FindConVar("mp_gamemode"); + hGamemode.GetString(gamemode, sizeof(gamemode)); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, gamemode, gamemode); + + HookEvent("player_use", Event_PlayerUse); + HookEvent("round_end", Event_RoundEnd); + HookEvent("gauntlet_finale_start", Event_GauntletStart); + HookEvent("finale_start", Event_FinaleStart); + HookEvent("finale_vehicle_leaving", Event_FinaleEnd); + HookEvent("player_bot_replace", Event_BotPlayerSwap); + HookEvent("bot_player_replace", Event_BotPlayerSwap); + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + HookEvent("weapon_drop", Event_WeaponDrop); + HookEvent("player_disconnect", Event_PlayerDisconnect); + + AutoExecConfig(true, "l4d2_tools"); + + for(int client = 1; client < MaxClients; client++) { + if(IsClientConnected(client) && IsClientInGame(client) && GetClientTeam(client) == 2) { + if(IsFakeClient(client)) { + SDKHook(client, SDKHook_OnTakeDamage, Event_OnTakeDamageBot); + SDKHook(client, SDKHook_WeaponDrop, Event_OnWeaponDrop); + } else { + SDKHook(client, SDKHook_WeaponEquip, Event_OnWeaponEquip); + } + } + } + + HookUserMessage(GetUserMessageId("VGUIMenu"), VGUIMenu, true); + + RegAdminCmd("sm_model", Command_SetClientModel, ADMFLAG_KICK); + RegAdminCmd("sm_surv", Cmd_SetSurvivor, ADMFLAG_KICK); + RegAdminCmd("sm_respawn_all", Command_RespawnAll, ADMFLAG_CHEATS, "Makes all dead players respawn in a closet"); + RegAdminCmd("sm_playsound", Command_PlaySound, ADMFLAG_KICK, "Plays a gamesound for player"); + RegAdminCmd("sm_stopsound", Command_StopSound, ADMFLAG_GENERIC, "Stops the last played gamesound for player"); + RegAdminCmd("sm_swap", Command_SwapPlayer, ADMFLAG_KICK, "Swarms two player's locations"); + RegConsoleCmd("sm_pmodels", Command_ListClientModels, "Lists all player's models"); + RegAdminCmd("sm_skipoutro", Command_SkipOutro, ADMFLAG_KICK, "Skips the outro"); + + CreateTimer(8.0, Timer_CheckPlayerPings, _, TIMER_REPEAT); +} + +void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); +} + +void Event_PlayerLimitChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + if(cvar.IntValue > 0) { + hSVMaxPlayers.IntValue = cvar.IntValue; + } +} + +Action Timer_CheckPlayerPings(Handle timer) { + if(StrEqual(gamemode, "hideandseek")) return Plugin_Continue; + if(hPingDropThres.IntValue != 0) { + for (int i = 1; i <= MaxClients; i++ ) { + if(IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i) && IsPlayerAlive(i) && GetClientTeam(i) > 1) { + int ping = GetEntProp(GetPlayerResourceEntity(), Prop_Send, "m_iPing", _, i); + if(isHighPingIdle[i] && ping <= hPingDropThres.IntValue) { + L4D_TakeOverBot(i); + isHighPingIdle[i] = false; + iHighPingCount[i] = 0; + }else if(ping > hPingDropThres.IntValue) { + if(iHighPingCount[i]++ > 2) { + PrintToChat(i, "Due to your high ping (%d ms) you have been moved to AFK.", ping); + PrintToChat(i, "You will be automatically switched back once your ping restores"); + SDKCall(hGoAwayFromKeyboard, i); + //PrintToChat(i, "Type /pingignore to disable this feature."); + // L4D_ReplaceWithBot(i); + isHighPingIdle[i] = true; + iHighPingCount[i] = 0; + } + + } + } + } + } + return Plugin_Continue; +} + +void CVC_FFNotice(ConVar convar, const char[] oldValue, const char[] newValue) { + if(convar.IntValue > 0) { + HookEvent("player_hurt", Event_PlayerHurt); + } else { + UnhookEvent("player_hurt", Event_PlayerHurt); + } +} + +public void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) { + LasersUsed.Clear(); +} + +Action Command_RespawnAll(int client, int args) { + L4D_CreateRescuableSurvivors(); + return Plugin_Handled; +} + +Action Command_SwapPlayer(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_swap [another player (default: self)] [\"silent\"]"); + } else { + char arg1[64], arg2[64], arg3[8]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_CONNECTED | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + int target = target_list[0]; + int target2 = client; + if(args == 2) { + if ((target_count = ProcessTargetString( + arg2, + client, + target_list, + 1, + COMMAND_FILTER_CONNECTED | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + } + target2 = target_list[0]; + } + float pos1[3], pos2[3]; + float ang1[3], ang2[3]; + GetClientAbsOrigin(target, pos1); + GetClientAbsOrigin(target2, pos2); + GetClientAbsAngles(target, ang1); + GetClientAbsAngles(target2, ang2); + TeleportEntity(target, pos2, ang2, NULL_VECTOR); + TeleportEntity(target2, pos1, ang1, NULL_VECTOR); + if(args < 3 || !StrEqual(arg3, "silent") && !StrEqual(arg2, "silent")) { + EmitSoundToClient(target, "custom/xen_teleport.mp3", target, 0); + EmitSoundToClient(target2, "custom/xen_teleport.mp3", target2); + } + } + return Plugin_Handled; +} + +Action Command_SkipOutro(int client, int args) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + ClientCommand(i, "skipouttro"); + } + } + return Plugin_Handled; +} +Action Command_ListClientModels(int client, int args) { + char model[64]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + GetClientModel(i, model, sizeof(model)); + ReplyToCommand(client, "%N's model: %s", i, model); + } + } + return Plugin_Handled; +} +Action Command_PlaySound(int client, int args) { + if(args < 2) { + ReplyToCommand(client, "Usage: sm_playsound "); + }else{ + char arg1[32], arg2[64], arg3[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_CONNECTED, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + int target; + for (int i = 0; i < target_count; i++) { + target = target_list[i]; + StopSound(target, 0, lastSound[target]); + } + PrecacheSound(arg2); + for (int i = 0; i < target_count; i++) { + target = target_list[i]; + if(IsClientConnected(target) && IsClientInGame(target) && !IsFakeClient(target)) { + if(StrEqual(arg3, "direct")) + ClientCommand(target, "playgamesound %s", arg2); + else + EmitSoundToClient(target, arg2, target); + strcopy(lastSound[target], 64, arg2); + } + } + CShowActivity2(client, "[SM] ", "playing sound {olive}%s{default} to {yellow}%s", arg2, target_name); + } + return Plugin_Handled; +} + +Action Command_StopSound(int client, int args) { + if(args < 2) { + ReplyToCommand(client, "Usage: sm_stopsound [soundpath or leave blank for previous]"); + } else { + char arg1[32], arg2[64]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_CONNECTED | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + int target; + for (int i = 0; i < target_count; i++) { + target = target_list[i]; + if(IsClientConnected(target) && IsClientInGame(target) && !IsFakeClient(target)) { + if(args < 2) + StopSound(target, 0, lastSound[target]); + else + StopSound(target, 0, arg2); + } + } + } + return Plugin_Handled; +} + +Action Command_SetClientModel(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_model [player] ['keep']"); + } else { + char arg1[2], arg2[16], arg3[8]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + + int survivorId; + L4DModelId modelId; + + + bool isL4D1 = isL4D1Survivors; + if(hForceSurvivorSet != null && hForceSurvivorSet.IntValue > 0) isL4D1 = hForceSurvivorSet.IntValue == 1; + + char s = CharToLower(arg1[0]); + if(s == 'b') { + survivorId = isL4D1 ? 0 : 4; + modelId = Model_Bill; + } else if(s == 'z') { + survivorId = isL4D1 ? 1 : 5; + modelId = Model_Zoey; + } else if(s == 'l') { + survivorId = isL4D1 ? 2 : 7; + modelId = Model_Louis; + } else if(s == 'f') { + survivorId = isL4D1 ? 3 : 6; + modelId = Model_Francis; + } else if(s == 'n') { + survivorId = 0; + modelId = Model_Nick; + if(isL4D1) PrintToChat(client, "Note: Only models for L4D2 characters are supported in L4D1 maps."); + } else if(s == 'r') { + survivorId = 1; + modelId = Model_Rochelle; + if(isL4D1) PrintToChat(client, "Note: Only models for L4D2 characters are supported in L4D1 maps."); + } else if(s== 'e') { + survivorId = 3; + modelId = Model_Ellis; + if(isL4D1) PrintToChat(client, "Note: Only models for L4D2 characters are supported in L4D1 maps."); + } else if(s == 'c') { + survivorId = 2; + modelId = Model_Coach; + if(isL4D1) PrintToChat(client, "Note: Only models for L4D2 characters are supported in L4D1 maps."); + } else { + ReplyToCommand(client, "Unknown survivor \"%s\". Syntax changed: model [player or none for self]", arg1); + return Plugin_Handled; + } + + bool keep = StrEqual(arg2, "keep", false) || StrEqual(arg3, "keep", false); + + if(args > 1) { + char target_name[1]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg2, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_ALIVE | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + int team = GetClientTeam(target); + if(team == 2 || team == 4) { + SetCharacter(target, survivorId, modelId, keep); + } + } + } else { + SetCharacter(client, survivorId, modelId, keep); + } + } + return Plugin_Handled; +} + +void SetCharacter(int target, int survivorIndex, L4DModelId modelIndex, bool keepModel) { + SetEntProp(target, Prop_Send, "m_survivorCharacter", survivorIndex); + SetEntityModel(target, MODELS[view_as(modelIndex)]); + if (IsFakeClient(target)) { + char name[32]; + GetSurvivorName(target, name, sizeof(name)); + SetClientInfo(target, "name", name); + } + UpdatePlayerIdentity(target, view_as(survivorIndex), keepModel); + + DataPack pack = new DataPack(); + pack.WriteCell(GetClientUserId(target)); + bool dualWield = false; + for(int slot = 0; slot <= 4; slot++) { + int weapon = AddWeaponSlot(target, slot, pack); + if(weapon > 0) { + if(slot == 1 && HasEntProp(weapon, Prop_Send, "m_isDualWielding")) { + dualWield = GetEntProp(weapon, Prop_Send, "m_isDualWielding") == 1; + SetEntProp(weapon, Prop_Send, "m_isDualWielding", 0); + } + SDKHooks_DropWeapon(target, weapon, NULL_VECTOR); + } + } + pack.WriteCell(dualWield); + CreateTimer(0.1, Timer_RequipWeapon, pack); +} + +int AddWeaponSlot(int target, int slot, DataPack pack) { + int weapon = GetPlayerWeaponSlot(target, slot); + if( weapon > 0 ) { + pack.WriteCell(EntIndexToEntRef(weapon)); // Save last held weapon to switch back + return weapon; + } else { + pack.WriteCell(-1); // Save last held weapon to switch back + return -1; + } +} + +public Action Timer_RequipWeapon(Handle hdl, DataPack pack) { + pack.Reset(); + int client = GetClientOfUserId(pack.ReadCell()); + if(client == 0) return Plugin_Handled; + + int weapon, pistolSlotItem = -1; + + for(int slot = 0; slot <= 4; slot++) { + weapon = pack.ReadCell(); + if(EntRefToEntIndex(weapon) != INVALID_ENT_REFERENCE) { + if(slot == 1) { + pistolSlotItem = weapon; + } + EquipPlayerWeapon(client, weapon); + } + } + bool isDualWield = pack.ReadCell() == 1; + if(isDualWield && pistolSlotItem != -1 && HasEntProp(pistolSlotItem, Prop_Send, "m_isDualWielding")) { + SetEntProp(pistolSlotItem, Prop_Send, "m_isDualWielding", 1); + } + return Plugin_Handled; +} + +Action Cmd_SetSurvivor(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_surv "); + } else { + char arg1[32], arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + int modelID = GetSurvivorId(arg2); + if(modelID == -1) { + ReplyToCommand(client, "Invalid survivor type entered. Case-sensitive, full name required."); + return Plugin_Handled; + } + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_CONNECTED | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + int target; + for (int i = 0; i < target_count; i++) { + target = target_list[i]; + SetEntProp(target, Prop_Send, "m_survivorCharacter", modelID); + } + } + return Plugin_Handled; +} + +// Hide MOTD +Action VGUIMenu(UserMsg msg_id, Handle bf, const int[] players, int playersNum, bool reliable, bool init) { + if(!hHideMotd.BoolValue) return Plugin_Continue; + static char buffer[8]; + // Show MOTD on versus games + hGamemode.GetString(buffer, sizeof(buffer)); + if(StrEqual(buffer, "versus", false)) return Plugin_Continue; + + BfReadString(bf, buffer, sizeof(buffer)); + return strcmp(buffer, "info") == 0 ? Plugin_Handled : Plugin_Continue; +} + +public void OnClientPutInServer(int client) { + if(!IsFakeClient(client)) + SDKHook(client, SDKHook_WeaponEquip, Event_OnWeaponEquip); + else + SDKHook(client, SDKHook_OnTakeDamage, Event_OnTakeDamageBot); +} + +public void OnClientDisconnect(int client) { + isHighPingIdle[client] = false; + iHighPingCount[client] = 0; + if(IsClientConnected(client) && IsClientInGame(client) && botDropMeleeWeapon[client] > -1 && IsValidEntity(botDropMeleeWeapon[client])) { + float pos[3]; + GetClientAbsOrigin(client, pos); + TeleportEntity(botDropMeleeWeapon[client], pos, NULL_VECTOR, NULL_VECTOR); + botDropMeleeWeapon[client] = -1; + } +} + +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && !IsFakeClient(client)) { + char auth[32]; + GetClientAuthId(client, AuthId_Steam2, auth, sizeof(auth)); + SteamIDs.Remove(auth); + } +} + +int disabledItem[2048]; +//Can also probably prevent kit drop to pick them up +public void Event_WeaponDrop(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int weapon = event.GetInt("propid"); + char newWpn[32]; + GetEntityClassname(client, newWpn, sizeof(newWpn)); + if(StrEqual(newWpn, "weapon_ammo_pack")) { + // prevent weapon from being picked up? + disabledItem[weapon] = client; + CreateTimer(10.0, Timer_AllowKitPickup, weapon); + } +} +public Action Event_OnWeaponEquip(int client, int weapon) { + if(disabledItem[weapon] > 0 && disabledItem[weapon] != client) return Plugin_Handled; + return Plugin_Continue; +} +public Action Timer_AllowKitPickup(Handle h, int entity) { + disabledItem[entity] = 0; + return Plugin_Handled; +} +public void OnMapStart() { + #if PRECACHE_SOUNDS_COUNT > 0 + char buffer[128]; + for(int i = 0; i < PRECACHE_SOUNDS_COUNT; i++) { + Format(buffer, sizeof(buffer), "sound/%s", PRECACHE_SOUNDS[i]); + AddFileToDownloadsTable(buffer); + PrecacheSound(PRECACHE_SOUNDS[i]); + } + #endif + + HookEntityOutput("info_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); + HookEntityOutput("trigger_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); +} +public void OnConfigsExecuted() { + isL4D1Survivors = L4D2_GetSurvivorSetMap() == 1; + if(hSVMaxPlayers != null && hPlayerLimit.IntValue > 0) { + hSVMaxPlayers.IntValue = hPlayerLimit.IntValue; + } +} + +public void OnSceneStageChanged(int scene, SceneStages stage) { + if(stage == SceneStage_Started) { + int activator = GetSceneInitiator(scene); + if(activator == 0) { + static char sceneFile[64]; + GetSceneFile(scene, sceneFile, sizeof(sceneFile)); + if(StrContains(sceneFile, "scenes/mechanic/dlc1_c6m1_initialmeeting") > -1 || StrEqual(sceneFile, "scenes/teengirl/dlc1_c6m1_initialmeeting07.vcd")) { + CancelScene(scene); + }else if(StrEqual(sceneFile, "scenes/teengirl/dlc1_c6m1_initialmeeting13.vcd") && activator == 0) { + CancelScene(scene); + } + } + } +} +///AFK BOT WEAPON FIX +public void Event_BotPlayerSwap(Event event, const char[] name, bool dontBroadcast) { + int bot = GetClientOfUserId(event.GetInt("bot")); + if(StrEqual(name, "player_bot_replace")) { + // Bot replaced player, hook any drop events + SDKHook(bot, SDKHook_WeaponDrop, Event_OnWeaponDrop); + } else { + // Player replaced a bot + int client = GetClientOfUserId(event.GetInt("player")); + if(client && botDropMeleeWeapon[bot] > 0) { + int meleeOwnerEnt = GetEntPropEnt(botDropMeleeWeapon[bot], Prop_Send, "m_hOwnerEntity"); + if(meleeOwnerEnt == -1) { + int currentWeapon = GetPlayerWeaponSlot(client, 1); + if(currentWeapon > 0) { + char buffer[32]; + GetEntityClassname(currentWeapon, buffer, sizeof(buffer)); + // Only delete their duplicate pistols, let melees get thrown out (into the world) + if(!StrEqual(buffer, "weapon_melee")) + RemoveEntity(currentWeapon); + } + EquipPlayerWeapon(client, botDropMeleeWeapon[bot]); + botDropMeleeWeapon[bot] = -1; + } + } + SDKUnhook(bot, SDKHook_WeaponDrop, Event_OnWeaponDrop); + } +} +Action Event_OnWeaponDrop(int client, int weapon) { + if(!IsValidEntity(weapon) || !IsFakeClient(client)) return Plugin_Continue; + if(GetEntProp(client, Prop_Send, "m_humanSpectatorUserID") > 0) { + char wpn[32]; + GetEdictClassname(weapon, wpn, sizeof(wpn)); + if(StrEqual(wpn, "weapon_melee") || StrEqual(wpn, "weapon_pistol_magnum")) { + #if defined DEBUG + PrintToServer("Bot %N dropped melee weapon %s", client, wpn); + #endif + RequestFrame(Frame_HideEntity, weapon); + botDropMeleeWeapon[client] = weapon; + } + } + return Plugin_Continue; +} +void Frame_HideEntity(int entity) { + if(IsValidEntity(entity)) + TeleportEntity(entity, OUT_OF_BOUNDS, NULL_VECTOR, NULL_VECTOR); +} +// Only called for bots, kills zombies behind bots, preventing them being stuck when their AI doesn't want to keep them alive +Action Event_OnTakeDamageBot(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + if(attacker > MaxClients) { + static char name[16]; + GetEdictClassname(attacker, name, sizeof(name)); + if(!StrEqual(name, "infected", true)) { + return Plugin_Continue; + } + + bool attackerVisible = IsEntityInSightRange(victim, attacker, 130.0, 10000.0); + if(!attackerVisible) { + //Zombie is behind the bot, reduce damage taken and slowly kill zombie (1/10 of default hp per hit) + damage /= 2.0; + SDKHooks_TakeDamage(attacker, victim, victim, 30.0); + return Plugin_Changed; + } + } + return Plugin_Continue; +} +//MINOR FIXES +void EntityOutput_OnStartTouchSaferoom(const char[] output, int caller, int client, float time) { + if(client > 0 && client <= MaxClients && IsValidClient(client) && GetClientTeam(client) == 2) { + if(StrEqual(gamemode, "coop", false)) { + if(botDropMeleeWeapon[client] > 0) { + PrintToServer("Giving melee weapon back to %N", client); + float pos[3]; + GetClientAbsOrigin(client, pos); + TeleportEntity(botDropMeleeWeapon[client], pos, NULL_VECTOR, NULL_VECTOR); + EquipPlayerWeapon(client, botDropMeleeWeapon[client]); + botDropMeleeWeapon[client] = -1; + } + } else if(StrEqual(gamemode, "tankrun", false)) { + if(!IsFakeClient(client)) { + CreateTimer(1.0, Timer_TPBots, client, TIMER_FLAG_NO_MAPCHANGE); + } + } + } +} + +Action Timer_TPBots(Handle timer, int user) { + float pos[3]; + GetClientAbsOrigin(user, pos); + for(int i = 1; i < MaxClients + 1; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsFakeClient(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + TeleportEntity(i, pos, NULL_VECTOR, NULL_VECTOR); + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", GetClientUserId(i), pos[0], pos[1], pos[2]); + + } + } + return Plugin_Handled; +} +//FRIENDLY FIRE NOTICE +public void Event_PlayerHurt(Event event, const char[] name, bool dontBroadcast) { + if(hFFNotice.IntValue > 0) { + int victim = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + int dmg = event.GetInt("dmg_health"); + if(dmg > 0) { + if(attacker > 0 && !IsFakeClient(attacker) && attacker != victim) { + if(GetClientTeam(attacker) == 2 && GetClientTeam(victim) == 2) { + if(hFFNotice.IntValue == 1) { + PrintHintTextToAll("%N has done %d HP of friendly fire damage to %N", attacker, dmg, victim); + }else{ + PrintToChatAll("%N has done %d HP of friendly fire damage to %N", attacker, dmg, victim); + } + } + } + } + } +} +//LASER SIGHT NOTICE +void Event_PlayerUse(Event event, const char[] name, bool dontBroadcast) { + if(hLaserNotice.BoolValue) { + int client = GetClientOfUserId(event.GetInt("userid")); + int targetEntity = event.GetInt("targetid"); + + char classname[32]; + GetEntityClassname(targetEntity, classname, sizeof(classname)); + + if(StrEqual(classname, "upgrade_laser_sight")) { + if(LasersUsed.FindValue(targetEntity) == -1) { + LasersUsed.Push(targetEntity); + PrintToChatAll("%N picked up laser sights", client); + } + } + } +} +//FINALE TIME INFO +void Event_GauntletStart(Event event, const char[] name, bool dontBroadcast) { + if(hFinaleTimer.IntValue > 0) { + iFinaleStartTime = GetTime(); + } +} +void Event_FinaleStart(Event event, const char[] name, bool dontBroadcast) { + if(hFinaleTimer.IntValue == 2) { + iFinaleStartTime = GetTime(); + } +} +void Event_FinaleEnd(Event event, const char[] name, bool dontBroadcast) { + if(hFinaleTimer.IntValue != 0) { + if(iFinaleStartTime != 0) { + int difference = GetTime() - iFinaleStartTime; + + char time[32]; + FormatSeconds(difference, time, sizeof(time)); + PrintToChatAll("Finale took %s to complete", time); + iFinaleStartTime = 0; + } + } +} +//Give kits to bots that replace kicked player +void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && IsFakeClient(client) && HasEntProp(client, Prop_Send, "m_humanSpectatorUserID") && GetEntProp(client, Prop_Send, "m_humanSpectatorUserID") < 0) { + int ent = GivePlayerItem(client, "weapon_first_aid_kit"); + EquipPlayerWeapon(client, ent); + } +} +/** + * Prints human readable duration from milliseconds + * + * @param ms The duration in milliseconds + * @param str The char array to use for text + * @param strSize The size of the string + */ +stock void FormatSeconds(int raw_sec, char[] str, int strSize) { + int hours = raw_sec / 3600; + int minutes = (raw_sec -(3600*hours))/60; + int seconds = (raw_sec -(3600*hours)-(minutes*60)); + if(hours >= 1) { + Format(str, strSize, "%d hours, %d.%d minutes", hours, minutes, seconds); + }else if(minutes >= 1) { + Format(str, strSize, "%d minutes and %d seconds", minutes, seconds); + }else { + Format(str, strSize, "%d seconds", seconds); + } + +} \ No newline at end of file diff --git a/scripting/abm.sp b/scripting/abm.sp new file mode 100644 index 0000000..aa50dc1 --- /dev/null +++ b/scripting/abm.sp @@ -0,0 +1,3774 @@ +//# vim: set filetype=cpp : + +/* +ABM a SourceMod L4D2 Plugin +Copyright (C) 2016-2017 Victor "NgBUCKWANGS" Gonzalez + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the + +Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include +#include +#include +#undef REQUIRE_EXTENSIONS +#include +#undef REQUIRE_PLUGIN +#include + +#pragma semicolon 1 +#pragma newdecls required + +#define PLUGIN_VERSION "0.1.97q" +#define LOGFILE "addons/sourcemod/logs/abm.log" // TODO change this to DATE/SERVER FORMAT? + +Handle g_GameData = null; +ArrayList g_sQueue; +ArrayList g_iQueue; + +// menu parameters +#define menuArgs g_menuItems[client] // Global argument tracking for the menu system +#define menuArg0 g_menuItems[client][0] // GetItem(1...) +#define menuArg1 g_menuItems[client][1] // GetItem(2...) +int g_menuItems[MAXPLAYERS + 1][2]; + +// menu tracking +#define g_callBacks g_menuStack[client] +ArrayStack g_menuStack[MAXPLAYERS + 1]; +Function callBack; + +char g_QKey[64]; // holds players by STEAM_ID +StringMap g_QDB; // holds player records linked by STEAM_ID +StringMap g_QRecord; // changes to an individual STEAM_ID mapping +StringMap g_QRtmp; // temporary QRecord holder for checking records without changing the main +StringMap g_Cvars; // locked cvars end up here + +char g_InfectedNames[6][] = {"Boomer", "Smoker", "Hunter", "Spitter", "Jockey", "Charger"}; +char g_SurvivorNames[8][] = {"Nick", "Rochelle", "Coach", "Ellis", "Bill", "Zoey", "Francis", "Louis"}; +char g_SurvivorPaths[8][] = { + "models/survivors/survivor_gambler.mdl", + "models/survivors/survivor_producer.mdl", + "models/survivors/survivor_coach.mdl", + "models/survivors/survivor_mechanic.mdl", + "models/survivors/survivor_namvet.mdl", + "models/survivors/survivor_teenangst.mdl", + "models/survivors/survivor_biker.mdl", + "models/survivors/survivor_manager.mdl", +}; + +int g_OS; // 0: Linux, 1: Windows (Prevent crash on Windows /w Zoey) +char g_sB[512]; // generic catch all string buffer +char g_pN[128]; // a dedicated buffer to storing a temporary name +char g_name[128], g_tmpName[128]; // g_QDB client name +int g_client, g_tmpClient; // g_QDB client id +int g_target, g_tmpTarget; // g_QDB player (human or bot) id +int g_lastid, g_tmpLastid; // g_QDB client's last known bot id +int g_onteam, g_tmpOnteam = 1; // g_QDB client's team +bool g_queued, g_tmpQueued; // g_QDB client's takeover state +bool g_inspec, g_tmpInspec; // g_QDB check client's specator mode +bool g_status, g_tmpStatus; // g_QDB client life state +bool g_update, g_tmpUpdate; // g_QDB should we update this record? +char g_model[32], g_tmpModel[32]; // g_QDB client's model +char g_ghost[32], g_tmpGhost[32]; // g_QDB queued model for SwitchTeam +float g_origin[3], g_tmpOrigin[3]; // g_QDB client's origin vector +float g_rdelay, g_tmpRdelay; // g_QDB delay time for SI respawn +Handle g_rDelays[MAXPLAYERS + 1]; // Individual respawn SI timers +int g_models[8]; + +Handle g_MkBotsTimer; +Handle g_ADAssistant; // Tries to make sure the AD starts +Handle g_AD; // Assistant Director Timer +int g_survivorSet; // 0 = l4d2 survivors, 4 = l4d1 survivors +bool g_survivorSetScan; // Check to discover the survivor set + +bool g_IsVs; +bool g_IsCoop; +bool g_AssistedSpawning = false; +bool g_ADFreeze = true; +bool g_AutoWave; +int g_ADInterval; + +ConVar g_cvVersion; // abm_version +ConVar g_cvLogLevel; int g_LogLevel; // abm_loglevel +ConVar g_cvMinPlayers; int g_MinPlayers; // abm_minplayers +ConVar g_cvPrimaryWeapon; char g_PrimaryWeapon[64]; // abm_primaryweapon +ConVar g_cvSecondaryWeapon; char g_SecondaryWeapon[64]; // abm_secondaryweapon +ConVar g_cvThrowable; char g_Throwable[64]; // abm_throwable +ConVar g_cvHealItem; char g_HealItem[64]; // abm_healitem +ConVar g_cvConsumable; char g_Consumable[64]; // abm_consumable +ConVar g_cvTankChunkHp; int g_TankChunkHp; // abm_tankchunkhp +ConVar g_cvSpawnInterval; int g_SpawnInterval; // abm_spawninterval +ConVar g_cvAutoHard; int g_AutoHard; // abm_autohard +ConVar g_cvUnlockSI; int g_UnlockSI; // abm_unlocksi +ConVar g_cvJoinMenu; int g_JoinMenu; // abm_joinmenu +ConVar g_cvTeamLimit; int g_TeamLimit; // abm_teamlimit +ConVar g_cvOfferTakeover; int g_OfferTakeover; // abm_offertakeover +ConVar g_cvStripKick; int g_StripKick; // abm_stripkick +ConVar g_cvAutoModel; int g_AutoModel; // abm_automodel +ConVar g_cvKeepDead; int g_KeepDead; // abm_keepdead +ConVar g_cvIdentityFix; int g_IdentityFix; // abm_identityfix +ConVar g_cvZoey; int g_Zoey; // abm_zoey +ConVar g_cvRespawnDelay; float g_RespawnDelay; // abm_respawndelay +ConVar g_cvWrapSwitch; int g_WrapSwitch; // _abm_wrapswitch +ConVar g_cvMaxMinions; // z_minion_limit +ConVar g_cvMaxSurvivors; // survivor_limit +ConVar g_cvMaxInfecteds; // z_max_player_zombies +int g_MaxMates; // X vs X +int g_SILimits; + +ConVar g_cvTankHealth; +ConVar g_cvMaxSwitches; +ConVar g_cvGameMode; +ConVar g_cvVDOUHandle; +ConVar g_cvVDOUOrigin; +ConVar g_cvConsistency; char g_consistency[2]; +char g_VDOUCurVal[2048]; +char g_VDOUOrigin[2048]; + +public Plugin myinfo= { + name = "ABM", + author = "Victor \"NgBUCKWANGS\" Gonzalez", + description = "A 5+ Player Enhancement Plugin for L4D2", + version = PLUGIN_VERSION, + url = "https://gitlab.com/vbgunz/ABM" +} + +public void OnPluginStart() { + Echo(2, "OnPluginStart"); + + g_GameData = LoadGameConfigFile("abm"); + if (g_GameData == null) { + SetFailState("[ABM] Game data missing!"); + } + + HookEvent("player_first_spawn", OnSpawnHook); + HookEvent("player_spawn", OnAllSpawnHook); + HookEvent("player_death", OnDeathHook, EventHookMode_Pre); + HookEvent("player_disconnect", CleanQDBHook); + HookEvent("player_afk", GoIdleHook); + HookEvent("player_team", QTeamHook); + HookEvent("player_bot_replace", QAfkHook); + HookEvent("bot_player_replace", QBakHook); + HookEvent("player_activate", PlayerActivateHook, EventHookMode_Pre); + HookEvent("player_connect", PlayerActivateHook, EventHookMode_Pre); + HookEvent("round_end", RoundFreezeEndHook, EventHookMode_Pre); + HookEvent("mission_lost", RoundFreezeEndHook, EventHookMode_Pre); + HookEvent("round_freeze_end", RoundFreezeEndHook, EventHookMode_Pre); + HookEvent("map_transition", RoundFreezeEndHook, EventHookMode_Pre); + HookEvent("round_start", RoundStartHook, EventHookMode_Pre); + + // base the following on a cvar + HookUserMessage(GetUserMessageId("SayText2"), UserMessageHook, true); + + RegAdminCmd("abm", MainMenuCmd, ADMFLAG_GENERIC); + RegAdminCmd("abm-menu", MainMenuCmd, ADMFLAG_GENERIC, "Menu: (Main ABM menu)"); + RegAdminCmd("abm-join", SwitchTeamCmd, ADMFLAG_GENERIC, "Menu/Cmd: | "); + RegAdminCmd("abm-takeover", SwitchToBotCmd, ADMFLAG_GENERIC, "Menu/Cmd: | "); + RegAdminCmd("abm-respawn", RespawnClientCmd, ADMFLAG_GENERIC, "Menu/Cmd: [ID]"); + RegAdminCmd("abm-model", AssignModelCmd, ADMFLAG_GENERIC, "Menu/Cmd: | "); + RegAdminCmd("abm-strip", StripClientCmd, ADMFLAG_GENERIC, "Menu/Cmd: [SLOT]"); + RegAdminCmd("abm-teleport", TeleportClientCmd, ADMFLAG_GENERIC, "Menu/Cmd: "); + RegAdminCmd("abm-cycle", CycleBotsCmd, ADMFLAG_GENERIC, "Menu/Cmd: | "); + RegAdminCmd("abm-reset", ResetCmd, ADMFLAG_GENERIC, "Cmd: (Use only in case of emergency)"); + RegAdminCmd("abm-info", QuickClientPrintCmd, ADMFLAG_GENERIC, "Cmd: (Print some diagnostic information)"); + RegAdminCmd("abm-mk", MkBotsCmd, ADMFLAG_GENERIC, "Cmd: "); + RegAdminCmd("abm-rm", RmBotsCmd, ADMFLAG_GENERIC, "Cmd: | "); + RegAdminCmd("abm-debug", DebugCmd, ADMFLAG_GENERIC, ""); + RegConsoleCmd("takeover", SwitchToBotCmd, "Menu/Cmd: | "); + RegConsoleCmd("join", SwitchTeamCmd, "Menu/Cmd: | "); + + g_OS = GetOS(); // 0: Linux 1: Windows + g_QDB = new StringMap(); + g_QRecord = new StringMap(); + g_QRtmp = new StringMap(); + g_Cvars = new StringMap(); + g_sQueue = new ArrayList(2); + g_iQueue = new ArrayList(2); + + char zoeyId[2]; + switch(g_OS) { + case 0: zoeyId = "5"; // 5 is the real Zoey + case 1: zoeyId = "1"; // Zoey crashes Windows servers, 1 is Rochelle + } + + // remember vscript director options unlocker settings between reloads + g_cvVDOUHandle = FindConVar("l4d2_directoroptions_overwrite"); + SetupCvar(g_cvVDOUOrigin, "_abm_vdouorigin", ";", "DO NOT EDIT"); + + if (g_cvVDOUHandle != null) { + HookConVarChange(g_cvVDOUHandle, UpdateConVarsHook); + GetConVarString(g_cvVDOUOrigin, g_VDOUOrigin, sizeof(g_VDOUOrigin)); + GetConVarString(g_cvVDOUHandle, g_VDOUCurVal, sizeof(g_VDOUCurVal)); + + if(g_VDOUOrigin[0] != ';') + UpdateConVarsHook(g_cvVDOUHandle, g_VDOUOrigin, g_VDOUOrigin); + else + UpdateConVarsHook(g_cvVDOUHandle, g_VDOUCurVal, g_VDOUCurVal); + } + + g_cvTankHealth = FindConVar("z_tank_health"); + g_cvMaxSwitches = FindConVar("vs_max_team_switches"); + g_cvConsistency = FindConVar("sv_consistency"); + HookConVarChange(g_cvConsistency, UpdateConVarsHook); + g_cvGameMode = FindConVar("mp_gamemode"); + HookConVarChange(g_cvGameMode, UpdateConVarsHook); + UpdateGameMode(); + + float maxClients = float(MaxClients); + g_cvMaxMinions = FindConVar("z_minion_limit"); + SetConVarFloat(g_cvMaxMinions, maxClients); + + g_cvMaxInfecteds = FindConVar("z_max_player_zombies"); + SetConVarBounds(g_cvMaxInfecteds, ConVarBound_Upper, true, maxClients); + SetConVarFloat(g_cvMaxInfecteds, maxClients); + + g_cvMaxSurvivors = FindConVar("survivor_limit"); + SetConVarBounds(g_cvMaxSurvivors, ConVarBound_Upper, true, maxClients); + SetConVarFloat(g_cvMaxSurvivors, maxClients); + + // thanks to bl4nk + int flags = GetConVarFlags(g_cvMaxSurvivors); + flags &= ~FCVAR_NOTIFY; + SetConVarFlags(g_cvMaxSurvivors, flags); + + SetupCvar(g_cvVersion, "abm_version", PLUGIN_VERSION, "ABM plugin version"); + SetupCvar(g_cvLogLevel, "abm_loglevel", "-1", "Development logging level -1: Off, 6: Max"); + SetupCvar(g_cvMinPlayers, "abm_minplayers", "4", "Pruning extra survivors stops at this size"); + SetupCvar(g_cvPrimaryWeapon, "abm_primaryweapon", "shotgun_chrome", "5+ survivor primary weapon"); + SetupCvar(g_cvSecondaryWeapon,"abm_secondaryweapon", "baseball_bat", "5+ survivor secondary weapon"); + SetupCvar(g_cvThrowable, "abm_throwable", "", "5+ survivor throwable item"); + SetupCvar(g_cvHealItem, "abm_healitem", "", "5+ survivor healing item"); + SetupCvar(g_cvConsumable, "abm_consumable", "adrenaline", "5+ survivor consumable item"); + SetupCvar(g_cvTankChunkHp, "abm_tankchunkhp", "2500", "Health chunk per survivor on 5+ missions"); + SetupCvar(g_cvSpawnInterval, "abm_spawninterval", "36", "SI full team spawn in (5 x N)"); + SetupCvar(g_cvAutoHard, "abm_autohard", "1", "0: Off 1: Non-Vs > 4 2: Non-Vs >= 1"); + SetupCvar(g_cvUnlockSI, "abm_unlocksi", "0", "0: Off 1: Use Left 4 Downtown 2 2: Use VScript Director Options Unlocker"); + SetupCvar(g_cvJoinMenu, "abm_joinmenu", "1", "0: Off 1: Admins only 2: Everyone"); + SetupCvar(g_cvTeamLimit, "abm_teamlimit", "16", "Humans on team limit"); + SetupCvar(g_cvOfferTakeover, "abm_offertakeover", "1", "0: Off 1: Survivors 2: Infected 3: All"); + SetupCvar(g_cvStripKick, "abm_stripkick", "0", "0: Don't strip removed bots 1: Strip removed bots"); + SetupCvar(g_cvAutoModel, "abm_automodel", "1", "1: Full set of survivors 0: Map set of survivors"); + SetupCvar(g_cvKeepDead, "abm_keepdead", "0", "0: The dead return alive 1: the dead return dead"); + SetupCvar(g_cvIdentityFix, "abm_identityfix", "1", "0: Do not assign identities 1: Assign identities"); + SetupCvar(g_cvZoey, "abm_zoey", zoeyId, "0:Nick 1:Rochelle 2:Coach 3:Ellis 4:Bill 5:Zoey 6:Francis 7:Louis"); + SetupCvar(g_cvRespawnDelay, "abm_respawndelay", "1.0", "SI respawn delay time in non-competitive modes"); + SetupCvar(g_cvWrapSwitch, "abm_wrapswitch", "0", "Intercept chooseteam/jointeam commands"); + + // clean out client menu stacks + for (int i = 1; i <= MaxClients; i++) { + g_menuStack[i] = new ArrayStack(128); + } + + // Register everyone that we can find + for (int i = 1; i <= MaxClients; i++) { + SetQRecord(i, true); + } + + AddCommandListener(TeamSwitchIntercept, "jointeam"); + AddCommandListener(CmdIntercept, "z_spawn"); + AddCommandListener(CmdIntercept, "z_spawn_old"); + AddCommandListener(CmdIntercept, "z_add"); + AutoExecConfig(true, "abm"); + StartAD(); +} + +public void OnPluginEnd() { + Echo(2, "OnPluginEnd"); + + for (int i = 1; i <= MaxClients; i++) { + if (GetQRecord(i)) { + SetClientName(i, g_name); + } + } +} + +public Action UserMessageHook(UserMsg MsgId, Handle hBitBuffer, const int[] iPlayers, int iNumPlayers, bool bReliable, bool bInit) { + Echo(2, "UserMessageHook: %d %d %d", iNumPlayers, bReliable, bInit); + // thanks https://forums.alliedmods.net/showpost.php?p=914509&postcount=10 + + // Skip the first two bytes + BfReadByte(hBitBuffer); + BfReadByte(hBitBuffer); + + // Read the message + static char strMessage[1024]; + BfReadString(hBitBuffer, strMessage, sizeof(strMessage)); + + // If the message equals to the string we want to filter, skip. + if (StrEqual(strMessage, "#Cstrike_Name_Change")) { + return Plugin_Handled; + } + + return Plugin_Continue; +} + +public Action TeamSwitchIntercept(int client, const char[] cmd, int args) { + Echo(2, "TeamSwitchIntercept: %d %s %d", client, cmd, args); + + if (g_WrapSwitch) { + GetCmdArg(1, g_sB, sizeof(g_sB)); + + if (IsClientValid(client)) { + if (StrEqual(g_sB, "survivor", false) || StrEqual(g_sB, "2")) { + SwitchTeam(client, 2); + } + + else if (StrEqual(g_sB, "infected", false) || StrEqual(g_sB, "3")) { + if (g_IsVs || IsAdmin(client)) { + SwitchTeam(client, 3); + } + } + + else if (StrEqual(g_sB, "0") || StrEqual(g_sB, "1")) { + SwitchTeam(client, StringToInt(g_sB)); + } + + else { + SwitchTeamCmd(client, 0); + } + + return Plugin_Handled; + } + } + + return Plugin_Continue; +} + +void SetupCvar(Handle &cvHandle, char[] name, char[] value, char[] details) { + Echo(2, "SetupCvar: %s %s %s", name, value, details); + + cvHandle = CreateConVar(name, value, details); + HookConVarChange(cvHandle, UpdateConVarsHook); + UpdateConVarsHook(cvHandle, value, value); +} + +Action CmdIntercept(int client, const char[] cmd, int args) { + Echo(2, "CmdIntercept: %d %s %d", client, cmd, args); + + if (g_AssistedSpawning) { + GhostsModeProtector(); + } + return Plugin_Continue; +} + +public void OnMapStart() { + Echo(2, "OnMapStart:"); + PrecacheModels(); +} + +public void OnMapEnd() { + Echo(2, "OnMapEnd:"); + + StopAD(); + StringMapSnapshot keys = g_QDB.Snapshot(); + g_iQueue.Clear(); + g_sQueue.Clear(); + +// if (!g_IsVs) { +// SetConVarInt(g_cvMaxSurvivors, g_MinPlayers); +// } + + for (int i; i < keys.Length; i++) { + keys.GetKey(i, g_sB, sizeof(g_sB)); + g_QDB.GetValue(g_sB, g_QRecord); + + g_QRecord.GetValue("onteam", g_onteam); + g_QRecord.GetValue("client", g_client); + g_QRecord.GetValue("target", g_target); + g_QRecord.SetValue("status",true,true); + + if (g_onteam >= 2) { + g_QRecord.SetValue("inspec", false, true); + } + + if (g_IsVs) { + g_QRecord.SetString("model", "", true); + } + + else if (g_onteam == 3) { + //SwitchToSpec(g_client); + g_QRecord.SetValue("status",false, true); + g_QRecord.SetString("model", "", true); + QueueUp(g_client,3); + } + } + + delete keys; +} + +public void OnEntityCreated(int ent, const char[] clsName) { + Echo(2, "OnEntityCreated: %d %s", ent, clsName); + + if (clsName[0] == 'f') { + bool gClip = !StrEqual(clsName, "func_playerghostinfected_clip", false); + bool iClip = !StrEqual(clsName, "func_playerinfected_clip", false); + + if (!(gClip && iClip)) { + CreateTimer(2.0, KillEntTimer, EntIndexToEntRef(ent)); + } + } + + else if (clsName[0] == 's' && StrEqual(clsName, "survivor_bot")) { + SDKHook(ent, SDKHook_SpawnPost, AutoModel); + } +} + +public Action KillEntTimer(Handle timer, any ref) { + Echo(2, "KillEntTimer: %d", ref); + + int ent = EntRefToEntIndex(ref); + if (ent != INVALID_ENT_REFERENCE || IsEntityValid(ent)) { + AcceptEntityInput(ent, "kill"); + } + + return Plugin_Stop; +} + +public Action L4D_OnGetScriptValueInt(const char[] key, int &retVal) { + Echo(5, "L4D_OnGetScriptValueInt: %s, %d", key, retVal); + + // see UpdateConVarsHook "g_UnlockSI" for VScript Director Options Unlocker + + if (g_UnlockSI == 1 && g_MaxMates > 4) { + int val = retVal; + + if (StrEqual(key, "DominatorLimit")) val = g_MaxMates; + else if (StrEqual(key, "MaxSpecials")) val = g_MaxMates; + else if (StrEqual(key, "BoomerLimit")) val = g_SILimits; + else if (StrEqual(key, "SmokerLimit")) val = g_SILimits; + else if (StrEqual(key, "HunterLimit")) val = g_SILimits; + else if (StrEqual(key, "ChargerLimit")) val = g_SILimits; + else if (StrEqual(key, "SpitterLimit")) val = g_SILimits; + else if (StrEqual(key, "JockeyLimit")) val = g_SILimits; + + if (val != retVal) { + retVal = val; + return Plugin_Handled; + } + } + + return Plugin_Continue; +} + +public void RoundFreezeEndHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "RoundFreezeEndHook: %s", name); + OnMapEnd(); +} + +public void PlayerActivateHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "PlayerActivateHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int client = GetClientOfUserId(userid); + PlayerActivate(client); +} + +void PlayerActivate(int client) { + Echo(2, "PlayerActivate: %d", client); + + if (GetQRecord(client)) { + g_QRecord.SetString("model", "", true); + StartAD(); + + if (!g_IsVs && g_onteam == 3) { + //SwitchTeam(client, 3); + QueueUp(client, 3); + AddInfected(); + } + } +} + +int GetRealClient(int client) { + Echo(2, "GetRealClient: %d", client); + + if (IsClientValid(client, 0)) { + if (HasEntProp(client, Prop_Send, "m_humanSpectatorUserID")) { + int userid = GetEntProp(client, Prop_Send, "m_humanSpectatorUserID"); + int target = GetClientOfUserId(userid); + + if (IsClientValid(target)) { + client = target; + } + + else { + for (int i = 1; i <= MaxClients; i++) { + if (GetQRtmp(i) && g_tmpTarget == client) { + client = i; + break; + } + } + } + } + } + + else { + client = 0; + } + + return client; +} + +Action LifeCheckTimer(Handle timer, int target) { + Echo(2, "LifeCheckTimer: %d", target); + + if (GetQRecord(GetRealClient(target))) { + int status = IsPlayerAlive(target); + + if(g_model[0] != EOS) { + AssignModel(target, g_model, g_IdentityFix); + } else { + GetBotCharacter(target, g_model); + g_QRecord.SetString("model", g_model, true); + } + + g_QRecord.SetValue("status", status, true); + AssignModel(g_client, g_model, g_IdentityFix); + } + return Plugin_Handled; +} + +public void OnAllSpawnHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "OnAllSpawnHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int client = GetClientOfUserId(userid); + + if (GetQRtmp(client)) { + CreateTimer(0.5, LifeCheckTimer, client); + + if (!g_IsVs && g_tmpOnteam == 3 && !g_tmpStatus) { + g_QRtmp.SetValue("status", 1, true); + State_TransitionSig(client, 8); + } + } +} + +public void RoundStartHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "RoundStartHook: %s", name); + StartAD(); + + for (int i = 1; i <= MaxClients; i++) { + if (GetQRtmp(i)) { + if (!g_IsVs && g_tmpOnteam == 3) { + //SwitchTeam(i, 3); + QueueUp(i, 3); + AddInfected(); + } + } + } +} + +bool StopAD() { + Echo(2, "StopAD"); + + if (g_AD != null) { + g_ADFreeze = true; + g_AssistedSpawning = false; + g_survivorSetScan = true; + g_ADInterval = 0; + + for (int i = 1; i <= MaxClients; i++) { + if (g_rDelays[i] != null) { + KillTimer(g_rDelays[i]); + g_rDelays[i] = null; + } + } + + if (g_MkBotsTimer != null) { + KillTimer(g_MkBotsTimer); + g_MkBotsTimer = null; + } + + KillTimer(g_AD); // delete causes errors? + g_AD = null; + } + + return g_AD == null; +} + +bool StartAD(float interval=0.5) { + Echo(2, "StartAD"); + + if (g_ADAssistant == null) { + g_ADAssistant = CreateTimer(0.1, StartADTimer, _, TIMER_REPEAT); + } + + if (StopAD()) { + g_AD = CreateTimer(interval, ADTimer, _, TIMER_REPEAT); + } + + return g_AD != null; +} + +public Action StartADTimer(Handle timer) { + Echo(6, "StartADTimer"); + + if (g_AD == null) { + StartAD(); + return Plugin_Continue; + } + + g_ADAssistant = null; + return Plugin_Stop; +} + +bool AllClientsLoadedIn() { + Echo(2, "AllClientsLoadedIn"); + + for (int i = 1; i <= MaxClients; i++) { + if (IsClientConnected(i) && !IsClientInGame(i)) { + return false; + } + } + + return true; +} + +public Action ADTimer(Handle timer) { + Echo(6, "ADTimer"); + + g_MaxMates = CountTeamMates(2); + + if (g_MaxMates == 0) { + return Plugin_Continue; + } + + static bool takeover; + takeover = !g_IsVs || (g_IsVs && !g_ADFreeze); + + for (int i = 1; i <= MaxClients; i++) { + if (g_ADFreeze) { + g_ADInterval = 0; + + if (g_MaxMates >= 4 || AllClientsLoadedIn()) { + while (CountTeamMates(2) < g_MinPlayers) { + AddSurvivor(); + } + + if (AllClientsLoadedIn() && StartAD(5.0)) { + RmBots(g_MinPlayers * -1, 2); + //SetConVarInt(g_cvMaxSurvivors, MaxClients); + g_AssistedSpawning = false; + g_ADFreeze = false; + } + } + } + + if (IsClientValid(GetRealClient(i), 2, 0)) { + if (IsPlayerAlive(i)) { + _AutoModel(i); + } + } + + else if (GetQRtmp(i)) { + + //if (IsClientValid(g_tmpTarget, 2, 0)) { + // ResetClientSpecUserId(i, g_tmpTarget); + //} + + if (g_tmpOnteam == 3) { + if (!g_IsVs) { + g_AssistedSpawning = true; + + if (!g_tmpInspec && GetClientTeam(i) <= 1) { + QueueUp(i, 3); + AddInfected(); + } + } + } + + else if (!g_tmpInspec && GetClientTeam(i) <= 1) { + if (takeover) { + g_QRtmp.SetValue("onteam", 0,true); + CreateTimer(0.1, TakeoverTimer, i); + } + } + } + } + + static int lastSize; + + if (lastSize != g_MaxMates) { + lastSize = g_MaxMates; + + g_SILimits = 1; + while (g_SILimits * 6 < g_MaxMates) { + g_SILimits++; + } + + VDOUnlocker(); + g_AutoWave = false; + + if (g_IsCoop) { + g_AutoWave = (g_AutoHard == 2 || g_MaxMates > 4 && g_AutoHard == 1); + AutoSetTankHp(); + } + } + + if (g_AutoWave || g_AssistedSpawning) { + if (g_SpawnInterval > 0 && g_ADInterval >= g_SpawnInterval) { + if (g_ADInterval % g_SpawnInterval == 0) { + Echo(2, " -- Assisting SI %d: Matching Full Team", g_ADInterval); + MkBots(g_MaxMates * -1, 3); + } + + else if (g_ADInterval % (g_SpawnInterval / 2) == 0) { + Echo(2, " -- Assisting SI %d: Matching Half Team", g_ADInterval); + MkBots((g_MaxMates / 2) * -1, 3); + } + + else if (g_ADInterval % (g_SpawnInterval / 3) == 0) { + Echo(2, " -- Assisting SI %d: Matching a Quarter", g_ADInterval); + MkBots((g_MaxMates / 4) * -1, 3); + } + } + } + + g_ADInterval++; + return Plugin_Continue; +} + +public void UpdateConVarsHook(Handle convar, const char[] oldCv, const char[] newCv) { + GetConVarName(convar, g_sB, sizeof(g_sB)); + Echo(2, "UpdateConVarsHook: %s %s %s", g_sB, oldCv, newCv); + + static char name[32]; name = ""; + static char value[2048]; value = ""; + + Format(name, sizeof(name), g_sB); + Format(value, sizeof(value), "%s", newCv); + TrimString(value); + + if (StrContains(newCv, "-l") == 0) { + strcopy(value, sizeof(value), value[2]); + TrimString(value); + g_Cvars.SetString(name, value, true); + } + + else if (StrContains(newCv, "-u") == 0) { + strcopy(value, sizeof(value), value[2]); + TrimString(value); + g_Cvars.Remove(name); + } + + g_Cvars.GetString(name, value, sizeof(value)); + if (!StrEqual(newCv, value)) { + SetConVarString(convar, value); + return; + } + + if (name[0] == 'a') { + if (name[4] == 'a') { + if (name[8] == 'h' && StrEqual(name, "abm_autohard")) { + g_AutoHard = GetConVarInt(g_cvAutoHard); + AutoSetTankHp(); + } + + else if (name[8] == 'm' && StrEqual(name, "abm_automodel")) { + g_AutoModel = GetConVarInt(g_cvAutoModel); + } + } + + else if (name[4] == 'c' && StrEqual(name, "abm_consumable")) { + GetConVarString(g_cvConsumable, g_Consumable, sizeof(g_Consumable)); + } + + else if (name[4] == 'h' && StrEqual(name, "abm_healitem")) { + GetConVarString(g_cvHealItem, g_HealItem, sizeof(g_HealItem)); + } + + else if (name[4] == 'i' && StrEqual(name, "abm_identityfix")) { + g_IdentityFix = GetConVarInt(g_cvIdentityFix); + } + + else if (name[4] == 'j' && StrEqual(name, "abm_joinmenu")) { + g_JoinMenu = GetConVarInt(g_cvJoinMenu); + } + + else if (name[4] == 'k' && StrEqual(name, "abm_keepdead")) { + g_KeepDead = GetConVarInt(g_cvKeepDead); + } + + else if (name[4] == 'l' && StrEqual(name, "abm_loglevel")) { + g_LogLevel = GetConVarInt(g_cvLogLevel); + } + + else if (name[4] == 'm' && StrEqual(name, "abm_minplayers")) { + g_MinPlayers = GetConVarInt(g_cvMinPlayers); + } + + else if (name[4] == 'o' && StrEqual(name, "abm_offertakeover")) { + g_OfferTakeover = GetConVarInt(g_cvOfferTakeover); + } + + else if (name[4] == 'p' && StrEqual(name, "abm_primaryweapon")) { + GetConVarString(g_cvPrimaryWeapon, g_PrimaryWeapon, sizeof(g_PrimaryWeapon)); + } + + else if (name[4] == 'r' && StrEqual(name, "abm_respawndelay")) { + g_RespawnDelay = GetConVarFloat(g_cvRespawnDelay); + + StringMapSnapshot keys = g_QDB.Snapshot(); + for (int i; i < keys.Length; i++) { + keys.GetKey(i, g_sB, sizeof(g_sB)); + g_QDB.GetValue(g_sB, g_QRecord); + g_QRecord.SetValue("rdelay", g_RespawnDelay, true); + } + + delete keys; + } + + else if (name[4] == 's') { + if (name[5] == 'e' && StrEqual(name, "abm_secondaryweapon")) { + GetConVarString(g_cvSecondaryWeapon, g_SecondaryWeapon, sizeof(g_SecondaryWeapon)); + } + + else if (name[5] == 'p' && StrEqual(name, "abm_spawninterval")) { + g_SpawnInterval = GetConVarInt(g_cvSpawnInterval); + } + + else if (name[5] == 't' && StrEqual(name, "abm_stripkick")) { + g_StripKick = GetConVarInt(g_cvStripKick); + } + } + + else if (name[4] == 't') { + if (name[5] == 'a' && StrEqual(name, "abm_tankchunkhp")) { + g_TankChunkHp = GetConVarInt(g_cvTankChunkHp); + AutoSetTankHp(); + } + + else if (name[5] == 'e' && StrEqual(name, "abm_teamlimit")) { + g_TeamLimit = GetConVarInt(g_cvTeamLimit); + } + + else if (name[5] == 'h' && StrEqual(name, "abm_throwable")) { + GetConVarString(g_cvThrowable, g_Throwable, sizeof(g_Throwable)); + } + } + + else if (name[4] == 'u' && StrEqual(name, "abm_unlocksi")) { + g_UnlockSI = GetConVarInt(g_cvUnlockSI); + + switch (g_UnlockSI) { + case 2: VDOUnlocker(); + default: RestoreVDOU(); + } + } + + else if (name[4] == 'z' && StrEqual(name, "abm_zoey")) { + g_Zoey = GetConVarInt(g_cvZoey); + } + } + + else if (name[0] == 'l' && StrEqual(name, "l4d2_directoroptions_overwrite")) { + g_VDOUCurVal = value; + + if (g_UnlockSI != 2) { + g_VDOUOrigin = value; + SetConVarString(g_cvVDOUOrigin, value); + } + } + + else if (name[0] == 'm' && StrEqual(name, "mp_gamemode")) { + UpdateGameMode(); + } + + else if (name[0] == 's' && StrEqual(name, "sv_consistency")) { + GetConVarString(g_cvConsistency, g_consistency, sizeof(g_consistency)); + } + + else if (name[5] == 'w' && StrEqual(name, "_abm_wrapswitch")) { + g_WrapSwitch = GetConVarInt(g_cvWrapSwitch); + } +} + +int GetGameType() { + Echo(2, "GetGameType"); + + // 0: coop 1: versus 2: scavenge 3: survival + GetConVarString(g_cvGameMode, g_sB, sizeof(g_sB)); + + switch (g_sB[0]) { + case 'c': { + if (StrEqual(g_sB, "coop")) return 0; + else if (StrEqual(g_sB, "community1")) return 0; // Special Delivery + else if (StrEqual(g_sB, "community2")) return 0; // Flu Season + else if (StrEqual(g_sB, "community3")) return 1; // Riding My Survivor + else if (StrEqual(g_sB, "community4")) return 3; // Nightmare + else if (StrEqual(g_sB, "community5")) return 0; // Death's Door + } + + case 'm': { + if (StrEqual(g_sB, "mutation1")) return 0; // Last Man on Earth + else if (StrEqual(g_sB, "mutation2")) return 0; // Headshot! + else if (StrEqual(g_sB, "mutation3")) return 0; // Bleed Out + else if (StrEqual(g_sB, "mutation4")) return 0; // Hard Eight + else if (StrEqual(g_sB, "mutation5")) return 0; // Four Swordsmen + else if (StrEqual(g_sB, "mutation7")) return 0; // Chainsaw Massacre + else if (StrEqual(g_sB, "mutation8")) return 0; // Ironman + else if (StrEqual(g_sB, "mutation9")) return 0; // Last Gnome on Earth + else if (StrEqual(g_sB, "mutation10")) return 0; // Room for One + else if (StrEqual(g_sB, "mutation11")) return 1; // Healthpackalypse + else if (StrEqual(g_sB, "mutation12")) return 1; // Realism Versus + else if (StrEqual(g_sB, "mutation13")) return 2; // Follow the Liter + else if (StrEqual(g_sB, "mutation14")) return 0; // Gib Fest + else if (StrEqual(g_sB, "mutation15")) return 1; // Versus Survival + else if (StrEqual(g_sB, "mutation16")) return 0; // Hunting Party + else if (StrEqual(g_sB, "mutation17")) return 0; // Lone Gunman + else if (StrEqual(g_sB, "mutation18")) return 1; // Bleed Out Versus + else if (StrEqual(g_sB, "mutation19")) return 1; // Taaannnkk! + else if (StrEqual(g_sB, "mutation20")) return 0; // Healing Gnome + } + + case 'r': { + if (StrEqual(g_sB, "realism")) return 0; + } + + case 's': { + if (StrEqual(g_sB, "scavenge")) return 2; + else if (StrEqual(g_sB, "survival")) return 3; + } + + case 't': { + if (StrEqual(g_sB, "teamscavenge")) return 2; + else if (StrEqual(g_sB, "teamversus")) return 1; + } + + case 'v': { + if (StrEqual(g_sB, "versus")) return 1; + } + } + + return -1; +} + +void UpdateGameMode() { + Echo(2, "UpdateGameMode"); + + switch (GetGameType()) { + case 0: { + g_IsCoop = true; + g_IsVs = false; + } + + case 1, 2: { + g_IsVs = true; + g_IsCoop = false; + } + + case 3: { + g_IsVs = false; + g_IsCoop = false; + } + } +} + +void SetVDOU(char[] val, any ...) { + Echo(2, "SetVDOU"); + + static const char tmp[128] = "\ + DominatorLimit=%s;\ + MaxSpecials=%s;\ + BoomerLimit=%s;\ + SmokerLimit=%s;\ + HunterLimit=%s;\ + ChargerLimit=%s;\ + SpitterLimit=%s;\ + JockeyLimit=%s;"; + + VFormat(val, sizeof(tmp), tmp, 2); +} + +void VDOUnlocker() { + Echo(2, "VDOUnlocker"); + + if (g_cvVDOUHandle != null) { + static bool restore = false; + g_MaxMates = CountTeamMates(2); + + if (g_UnlockSI == 2 && g_MaxMates > 4) { + static char m[3]; static char l[3]; + Format(m, sizeof(m), "%d", g_MaxMates); + Format(l, sizeof(l), "%d", g_SILimits); + SetVDOU(g_VDOUCurVal, m, m, l, l, l, l, l, l); + SetConVarString(g_cvVDOUHandle, g_VDOUCurVal); + restore = true; + } + + else if (restore) { + RestoreVDOU(); + restore = false; + } + } +} + +void RestoreVDOU() { + Echo(2, "RestoreVDOU"); + + if (!g_ADFreeze && g_cvVDOUHandle != null) { + static char origin[2048]; + origin = g_VDOUOrigin; + + SetVDOU(g_VDOUCurVal, "","","","","","","",""); + SetConVarString(g_cvVDOUHandle, g_VDOUCurVal); + SetConVarString(g_cvVDOUHandle, origin); + } +} + +void AutoSetTankHp() { + Echo(2, "AutoSetTankHp"); + + static int tankHp; + GetConVarDefault(g_cvTankHealth, g_sB, sizeof(g_sB)); + tankHp = StringToInt(g_sB); + + if (g_TankChunkHp != 0 && (g_IsCoop || g_IsVs)) { + if (g_AutoHard == 2 || g_MaxMates > 4 && g_AutoHard == 1) { + tankHp = g_MaxMates * g_TankChunkHp; + } + } + + SetConVarInt(g_cvTankHealth, tankHp); +} + +public void OnConfigsExecuted() { + Echo(2, "OnConfigsExecuted"); + + // extend the base cfg with a map specific cfg + GetCurrentMap(g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "cfg/sourcemod/abm/%s.cfg", g_sB); + + if (FileExists(g_sB, true)) { + strcopy(g_sB, sizeof(g_sB), g_sB[4]); + ServerCommand("exec \"%s\"", g_sB); + Echo(1, "Extending ABM: %s", g_sB); + } + + // some servers don't pick up on this automatically + else if (FileExists("cfg/sourcemod/abm.cfg", true)) { + ServerCommand("exec \"sourcemod/abm.cfg\""); + } +} + +public void OnClientPostAdminCheck(int client) { + Echo(2, "OnClientPostAdminCheck: %d", client); + + if (!IsFakeClient(client)) { + if (GetQRecord(client) && !g_update) { + return; + } + + if (IsAdmin(client) || !GetQRecord(client)) { + SetQRecord(client, true); + } + + else { + int status = g_status; + int onteam = g_onteam; + + if (SetQRecord(client, true) >= 0) { + g_QRecord.SetValue("status", status, true); + g_QRecord.SetValue("onteam", onteam, true); + } + } + + if (g_JoinMenu == 2 || g_JoinMenu == 1 && IsAdmin(client)) { + GoIdle(client, 1); + menuArg0 = client; + SwitchTeamHandler(client, 1, ""); + } + + else if (CountTeamMates(2) >= 1) { + CreateTimer(0.1, TakeoverTimer, client); + CreateTimer(0.5, AutoIdleTimer, client, TIMER_REPEAT); + } + } +} + +public Action AutoIdleTimer(Handle timer, int client) { + Echo(2, "AutoIdleTimer: %d", client); + + if (g_IsVs || !IsClientValid(client)) { + return Plugin_Stop; + } + + static int onteam; + onteam = GetClientTeam(client); + + if (onteam >= 2) { + if (onteam == 2) { + GoIdle(client, 0); + } + + return Plugin_Stop; + } + + return Plugin_Continue; +} + +public void GoIdleHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "GoIdleHook: %s", name); + int player = GetEventInt(event, "player"); + int client = GetClientOfUserId(player); + + if (GetQRecord(client)) { + switch (g_onteam) { + case 2: GoIdle(client); + case 3: SwitchTeam(client, 3); + } + } +} + +void GoIdle(int client, int onteam=0) { + Echo(2, "GoIdle: %d %d", client, onteam); + + if (GetQRecord(client)) { + int spec_target; + + // going from idle survivor to infected, leaves an icon behind + if (IsClientValid(g_target, 2, 0)) { + SwitchToBot(client, g_target); + } + + if (g_onteam == 2) { + SwitchToSpec(client); + + if (onteam == 0) { + SetHumanSpecSig(g_target, client); + } + + if (onteam == 1) { + SwitchToSpec(client); + Unqueue(client); + } + + AssignModel(g_target, g_model, g_IdentityFix); + } + + else { + SwitchToSpec(client); + } + + if (g_onteam == 3 && onteam <= 1) { + g_QRecord.SetString("model", "", true); + } + + spec_target = IsClientValid(g_target, 0, 0) ? g_target : GetSafeSurvivor(client); + + if (IsClientValid(spec_target)) { + SetEntPropEnt(client, Prop_Send, "m_hObserverTarget", spec_target); + SetEntProp(client, Prop_Send, "m_iObserverMode", 5); + } + } +} + +public void CleanQDBHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "CleanQDBHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int client = GetClientOfUserId(userid); + RemoveQDBKey(client); +} + +void RemoveQDBKey(int client) { + Echo(2, "RemoveQDBKey: %d", client); + + if (GetQRecord(client)) { + SetClientName(client, g_name); + g_QRecord.SetValue("update", true, true); + g_QRecord.SetString("model", "", true); + + if (CountTeamMates(2) > g_MinPlayers) { + CreateTimer(1.0, RmBotsTimer, 1); + } + } +} + +Action RmBotsTimer(Handle timer, any asmany) { + Echo(4, "RmBotsTimer: %d", asmany); + + if (!g_IsVs) { + RmBots(asmany, 2); + } + return Plugin_Handled; +} + +bool IsAdmin(int client) { + Echo(2, "IsAdmin: %d", client); + return CheckCommandAccess( + client, "generic_admin", ADMFLAG_GENERIC, false + ); +} + +bool IsEntityValid(int ent) { + Echo(2, "IsEntityValid: %d", ent); + return (ent > MaxClients && ent <= 2048 && IsValidEntity(ent)); +} + +bool IsClientValid(int client, int onteam=0, int mtype=2) { + Echo(6, "IsClientValid: %d, %d, %d", client, onteam, mtype); + + if (client >= 1 && client <= MaxClients) { + if (IsClientConnected(client)) { + if (IsClientInGame(client)) { + + if (onteam != 0 && GetClientTeam(client) != onteam) { + return false; + } + + switch (mtype) { + case 0: return IsFakeClient(client); + case 1: return !IsFakeClient(client); + } + + return true; + } + } + } + + return false; +} + +bool CanClientTarget(int client, int target) { + Echo(2, "CanClientTarget: %d %d", client, target); + + if (client == target) { + return true; + } + + else if (!IsClientValid(client) || !IsClientValid(target)) { + return false; + } + + else if (IsFakeClient(target)) { + int manager = GetClientManager(target); + + if (manager != -1) { + if (manager == 0) { + return true; + } + + else { + return CanClientTarget(client, manager); + } + } + } + + return CanUserTarget(client, target); +} + +int GetPlayClient(int client) { + Echo(3, "GetPlayClient: %d", client); + + if (GetQRecord(client)) { + return g_target; + } + + else if (IsClientValid(client)) { + return client; + } + + return -1; +} + +int ClientHomeTeam(int client) { + Echo(2, "ClientHomeTeam: %d", client); + + if (GetQRecord(client)) { + return g_onteam; + } + + else if (IsClientValid(client)) { + return GetClientTeam(client); + } + + return -1; +} + +// ================================================================== // +// g_QDB MANAGEMENT +// ================================================================== // + +bool SetQKey(int client) { + Echo(3, "SetQKey: %d", client); + + if (IsClientValid(client, 0, 1)) { + if (GetClientAuthId(client, AuthId_Steam2, g_QKey, sizeof(g_QKey), true)) { + return true; + } + } + + return false; +} + +bool GetQRtmp(int client) { + Echo(3, "GetQRtmp: %d", client); + + bool result; + static char QKey[64]; + QKey = g_QKey; + + if (SetQKey(client)) { + if (g_QDB.GetValue(g_QKey, g_QRtmp)) { + + if (IsClientValid(client) && IsPlayerAlive(client)) { + GetClientAbsOrigin(client, g_tmpOrigin); + g_QRtmp.SetArray("origin", g_tmpOrigin, sizeof(g_tmpOrigin), true); + } + + g_QRtmp.GetValue("client", g_tmpClient); + g_QRtmp.GetValue("target", g_tmpTarget); + g_QRtmp.GetValue("lastid", g_tmpLastid); + g_QRtmp.GetValue("onteam", g_tmpOnteam); + g_QRtmp.GetValue("queued", g_tmpQueued); + g_QRtmp.GetValue("inspec", g_tmpInspec); + g_QRtmp.GetValue("status", g_tmpStatus); + g_QRtmp.GetValue("update", g_tmpUpdate); + g_QRtmp.GetValue("rdelay", g_tmpRdelay); + g_QRtmp.GetString("ghost", g_tmpGhost, sizeof(g_tmpGhost)); + g_QRtmp.GetString("model", g_tmpModel, sizeof(g_tmpModel)); + g_QRtmp.GetString("name", g_tmpName, sizeof(g_tmpName)); + + if (g_tmpModel[0] == EOS || g_tmpOnteam == 3) { + GetBotCharacter(g_tmpTarget, g_tmpModel); + g_QRtmp.SetString("model", g_tmpModel, true); + + if (!g_IsVs && g_tmpOnteam == 3 && IsPlayerAlive(client)) { + SetClientName(client, g_tmpModel); + } + } + + result = true; + } + } + + g_QKey = QKey; + return result; +} + +bool GetQRecord(int client) { + Echo(3, "GetQRecord: %d", client); + + if (SetQKey(client)) { + if (g_QDB.GetValue(g_QKey, g_QRecord)) { + + if (IsClientValid(client) && IsPlayerAlive(client)) { + GetClientAbsOrigin(client, g_origin); + g_QRecord.SetArray("origin", g_origin, sizeof(g_origin), true); + } + + g_QRecord.GetValue("client", g_client); + g_QRecord.GetValue("target", g_target); + g_QRecord.GetValue("lastid", g_lastid); + g_QRecord.GetValue("onteam", g_onteam); + g_QRecord.GetValue("queued", g_queued); + g_QRecord.GetValue("inspec", g_inspec); + g_QRecord.GetValue("status", g_status); + g_QRecord.GetValue("update", g_update); + g_QRecord.GetValue("rdelay", g_rdelay); + g_QRecord.GetString("ghost", g_ghost, sizeof(g_ghost)); + g_QRecord.GetString("model", g_model, sizeof(g_model)); + g_QRecord.GetString("name", g_name, sizeof(g_name)); + + if (g_model[0] == EOS || g_onteam == 3) { + GetBotCharacter(g_target, g_model); + g_QRecord.SetString("model", g_model, true); + + if (!g_IsVs && g_onteam == 3 && IsPlayerAlive(client)) { + SetClientName(client, g_model); + } + } + + return true; + } + } + + return false; +} + +bool NewQRecord(int client) { + Echo(3, "NewQRecord: %d", client); + + g_QRecord = new StringMap(); + + GetClientAbsOrigin(client, g_origin); + g_QRecord.SetArray("origin", g_origin, sizeof(g_origin), true); + g_QRecord.SetValue("client", client, true); + g_QRecord.SetValue("target", client, true); + g_QRecord.SetValue("lastid", client, true); + g_QRecord.SetValue("onteam", GetClientTeam(client), true); + g_QRecord.SetValue("queued", false, true); + g_QRecord.SetValue("inspec", false, true); + g_QRecord.SetValue("status", true, true); + g_QRecord.SetValue("update", false, true); + g_QRecord.SetValue("rdelay", g_RespawnDelay, true); + g_QRecord.SetString("ghost", "", true); + g_QRecord.SetString("model", "", true); + + GetClientName(client, g_name, sizeof(g_name)); + g_QRecord.SetString("name", g_name, true); + return true; +} + +int SetQRecord(int client, bool update=false) { + Echo(3, "SetQRecord: %d %d", client, update); + + int result = -1; + + if (SetQKey(client)) { + if (g_QDB.GetValue(g_QKey, g_QRecord) && !update) { + result = 0; + } + + else if (NewQRecord(client)) { + GetClientName(client, g_pN, sizeof(g_pN)); + Echo(0, "AUTH ID: %s, (%s) ADDED TO QDB.", g_QKey, g_pN); + g_QDB.SetValue(g_QKey, g_QRecord, true); + result = 1; + } + + GetQRecord(client); + } + + return result; +} + +void QueueUp(int client, int onteam) { + Echo(2, "QueueUp: %d %d", client, onteam); + + if (onteam >= 2 && onteam <= 3 && GetQRecord(client)) { + Unqueue(client); + + switch (onteam) { + case 2: g_sQueue.Push(client); + case 3: g_iQueue.Push(client); + } + + g_QRecord.SetValue("target", client, true); + g_QRecord.SetValue("inspec", false, true); + g_QRecord.SetValue("onteam", onteam, true); + g_QRecord.SetValue("queued", true, true); + } +} + +void Unqueue(int client) { + Echo(2, "Unqueue: %d", client); + + if (GetQRecord(client)) { + g_QRecord.SetValue("queued", false, true); + + int iLength = g_iQueue.Length; + int sLength = g_sQueue.Length; + + if (iLength > 0) { + for (int i = iLength - 1; i > -1; i--) { + if (g_iQueue.Get(i) == client) { + g_iQueue.Erase(i); + } + } + } + + if (sLength > 0) { + for (int i = sLength - 1; i > -1; i--) { + if (g_sQueue.Get(i) == client) { + g_sQueue.Erase(i); + } + } + } + } +} + +public Action OnSpawnHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "OnSpawnHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int target = GetClientOfUserId(userid); + + GetClientName(target, g_pN, sizeof(g_pN)); + if (g_pN[0] == 'A' && StrContains(g_pN, "ABMclient") >= 0) { + return Plugin_Handled; + } + + int onteam = GetClientTeam(target); + int client; + + if (onteam == 3) { + int zClass = GetEntProp(target, Prop_Send, "m_zombieClass"); + + if (g_iQueue.Length == 0 && g_UnlockSI != 0) { + if (CountTeamMates(3) > g_MaxMates && zClass != 8) { + if (IsFakeClient(target)) { + KickClient(target); + return Plugin_Handled; + } + } + } + + if (!g_IsVs) { + if (g_AssistedSpawning) { + if (zClass == 8) { + + int j = 1; + static int i = 1; + + for (; i <= MaxClients + 1; i++) { + if (j++ == MaxClients + 1) { // join 3 Tank requires +1 + return Plugin_Handled; + } + + if (i > MaxClients) { + i = 1; + } + + if (GetQRecord(i) && g_onteam == 3 && !g_inspec) { + if (GetEntProp(i, Prop_Send, "m_zombieClass") != 8) { + client = i; + i++; + break; + } + } + } + + if(IsClientValid(client)) { + SwitchToBot(client, target); + } else { + CreateTimer(1.0, TankAssistTimer, target, TIMER_REPEAT); + } + } + } + + if (g_iQueue.Length > 0) { + client = g_iQueue.Get(0); + if (IsClientValid(client) && !IsPlayerAlive(client)) { + SwitchToBot(client, target); + } + + return Plugin_Handled; + } + } + } + + if (onteam == 2) { + // AutoModeling now takes place in OnEntityCreated + CreateTimer(0.4, OnSpawnHookTimer, target); + return Plugin_Handled; + } + + return Plugin_Continue; +} + +public Action TankAssistTimer(Handle timer, any client) { + Echo(4, "TankAssistTimer: %d", client); + + /* + * Human players on the infected team in modes that do not officially + * support them, can get Tanks stuck in "stasis" until they die. This + * function works around the issue by watching Tanks for movement. If + * a Tank does not move in 11 seconds, it is replaced with another. + */ + + float origin[3]; + static const float nullOrigin[3]; + static int times[MAXPLAYERS + 1] = {11, ...}; + static float origins[MAXPLAYERS + 1][3]; + static int i; + + if (IsClientValid(client)) { + i = times[client]--; + + if (i == 11) { + GetClientAbsOrigin(client, origins[client]); + return Plugin_Continue; + } + + else if (i >= 0) { + GetClientAbsOrigin(client, origin); + + if (origin[0] == origins[client][0]) { + if (i == 0) { + TeleportEntity(client, nullOrigin, NULL_VECTOR, NULL_VECTOR); + ForcePlayerSuicide(client); + AddInfected("tank"); + } + + return Plugin_Continue; + } + } + } + + i = times[client] = 11; + return Plugin_Stop; +} + +public Action ForceSpawnTimer(Handle timer, any client) { + Echo(4, "ForceSpawnTimer: %d", client); + + static int times[MAXPLAYERS + 1] = {20, ...}; + static int i; + + if (IsClientValid(client)) { + i = times[client]--; + + if (GetEntProp(client, Prop_Send, "m_zombieClass") != 8) { + i = times[client] = 20; + return Plugin_Stop; + } + + if (GetEntProp(client, Prop_Send, "m_isGhost") == 1) { + if (i >= 1) { + PrintHintText(client, "FORCING SPAWN IN: %d", i); + return Plugin_Continue; + } + + if (GetEntProp(client, Prop_Send, "m_ghostSpawnState") <= 2) { + SetEntProp(client, Prop_Send, "m_isGhost", 0); + } + + return Plugin_Continue; + } + } + + if (!IsEntityValid(GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"))) { + i = CreateEntityByName("weapon_tank_claw"); + if (IsEntityValid(i) && DispatchSpawn(i)) { + EquipPlayerWeapon(client, i); + } + } + + i = times[client] = 20; + PrintHintText(client, "KILL ALL HUMANS"); + return Plugin_Stop; +} + +Action OnSpawnHookTimer(Handle timer, any target) { + Echo(2, "OnSpawnHookTimer: %d", target); + + if (g_sQueue.Length > 0) { + SwitchToBot(g_sQueue.Get(0), target); + } + return Plugin_Handled; +} + +public void OnDeathHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(4, "OnDeathHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int client = GetClientOfUserId(userid); + + if (GetQRecord(client)) { + GetClientAbsOrigin(client, g_origin); + g_QRecord.SetValue("target", client, true); + g_QRecord.SetArray("origin", g_origin, sizeof(g_origin), true); + g_QRecord.SetValue("status", false, true); + bool offerTakeover; + + switch (g_onteam) { + case 3: { + g_QRecord.SetString("model", "", true); + + if (!g_IsVs) { + QueueSI(client, g_rdelay); + + switch (g_OfferTakeover) { + case 2, 3: { + GoIdle(client, 1); + offerTakeover = true; + } + + default: SwitchTeam(client, 3); + } + } + } + + case 2: { + switch (g_OfferTakeover) { + case 1, 3: offerTakeover = true; + } + } + } + + if (offerTakeover) { + GenericMenuCleaner(client); + menuArg0 = client; + SwitchToBotHandler(client, 1); + } + } + + else if (GetQRecord(GetRealClient(client))) { + g_QRecord.SetValue("status", false, true); + } +} + +public void QTeamHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "QTeamHook: %s", name); + + int userid = GetEventInt(event, "userid"); + int client = GetClientOfUserId(userid); + int onteam = GetEventInt(event, "team"); + + if (GetQRecord(client)) { + + if (!g_IsVs && g_onteam == 3) { + SetClientName(client, g_name); + } + + if (onteam >= 2) { + g_QRecord.SetValue("inspec", false, true); + g_QRecord.SetValue("target", client, true); + g_QRecord.SetValue("onteam", onteam, true); + + // attempt to apply a model asap + if (g_ADFreeze && onteam == 2 && g_model[0] != EOS) { + AssignModel(client, g_model, g_IdentityFix); + } + } + + if (onteam <= 1) { // cycling requires 0.2 or higher? + CreateTimer(0.2, QTeamHookTimer, client); + } + } +} + +Action QTeamHookTimer(Handle timer, any client) { + Echo(2, "QTeamHookTimer: %d", client); + + if (GetQRecord(client) && !g_inspec) { + if (g_onteam == 2) { + if (IsClientValid(g_target) && g_target != client) { + SetHumanSpecSig(g_target, client); + } + } + } + return Plugin_Handled; +} + +public void QAfkHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "QAfkHook: %s", name); + + int client = GetClientOfUserId(GetEventInt(event, "player")); + int target = GetClientOfUserId(GetEventInt(event, "bot")); + int clientTeam = GetClientTeam(client); + int targetTeam = GetClientTeam(target); + + if (GetQRecord(client)) { + int onteam = GetClientTeam(client); + + if (onteam == 2) { + g_QRecord.SetValue("target", target, true); + AssignModel(target, g_model, g_IdentityFix); + } + } + + if (targetTeam == 2 && IsClientValid(client)) { + if (IsClientInKickQueue(client)) { + if (client && target && clientTeam == targetTeam) { + int safeClient = GetSafeSurvivor(target); + RespawnClient(target, safeClient); + } + } + } +} + +public void QBakHook(Handle event, const char[] name, bool dontBroadcast) { + Echo(2, "QBakHook: %s", name); + + int client = GetClientOfUserId(GetEventInt(event, "player")); + int target = GetClientOfUserId(GetEventInt(event, "bot")); + + if (GetQRecord(client)) { + if (g_target != target) { + g_QRecord.SetValue("lastid", target); + g_QRecord.SetValue("target", client); + } + + if (GetClientTeam(client) == 2) { + AssignModel(client, g_model, g_IdentityFix); + } + } +} + +// ================================================================== // +// UNORGANIZED AS OF YET +// ================================================================== // + +void StripClient(int client) { + Echo(2, "StripClient: %d", client); + + if (IsClientValid(client)) { + if (GetClientTeam(client) == 2) { + for (int i = 4; i >= 0; i--) { + StripClientSlot(client, i); + } + } + } +} + +void StripClientSlot(int client, int slot) { + Echo(2, "StripClientSlot: %d %d", client, slot); + + client = GetPlayClient(client); + + if (IsClientValid(client)) { + if (GetClientTeam(client) == 2) { + int ent = GetPlayerWeaponSlot(client, slot); + if (IsEntityValid(ent)) { + RemovePlayerItem(client, ent); + AcceptEntityInput(ent,"kill"); + } + } + } +} + +void RespawnClient(int client, int target=0) { + Echo(2, "RespawnClient: %d %d", client, target); + + if (!IsClientValid(client)) { + return; + } + + else if (GetQRecord(client)) { + if (g_onteam == 3) { + Takeover(client, 3); + return; + } + } + + client = GetPlayClient(client); + target = GetPlayClient(target); + bool weaponizePlayer = true; + static const float pos0[3]; + static float pos1[3]; + pos1 = pos0; + + if (client != GetRealClient(target) && IsClientValid(target)) { + GetClientAbsOrigin(target, pos1); + } + + else if (GetQRtmp(client)) { + pos1 = g_origin; + if (pos1[0] != 0 && pos1[1] != 0 && pos1[2] != 0) { + weaponizePlayer = false; + } + } + + if (pos1[0] != 0 && pos1[1] != 0 && pos1[2] != 0) { + RoundRespawnSig(client); + + if (!g_ADFreeze && weaponizePlayer) { + QuickCheat(client, "give", g_PrimaryWeapon); + QuickCheat(client, "give", g_SecondaryWeapon); + QuickCheat(client, "give", g_Throwable); + QuickCheat(client, "give", g_HealItem); + QuickCheat(client, "give", g_Consumable); + } + + TeleportEntity(client, pos1, NULL_VECTOR, NULL_VECTOR); + } +} + +void TeleportClient(int client, int target) { + Echo(2, "TeleportClient: %d %d", client, target); + + float origin[3]; + client = GetPlayClient(client); + target = GetPlayClient(target); + + if (IsClientValid(client) && IsClientValid(target)) { + GetClientAbsOrigin(target, origin); + TeleportEntity(client, origin, NULL_VECTOR, NULL_VECTOR); + } +} + +int GetSafeSurvivor(int client) { + Echo(2, "GetSafeSurvivor: %d", client); + + + float lowestIntensity; + int lowestClient = -1; + + for (int i = 1; i <= MaxClients; i++) { + if (IsClientValid(i) && i != client && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + + // Skip if incapped or on a ledge + if (GetEntProp(i, Prop_Send, "m_isHangingFromLedge") || GetEntProp(i, Prop_Send, "m_isIncapacitated")) { + continue; + } + + float intensity = L4D_GetPlayerIntensity(i); + if(intensity < lowestIntensity || lowestClient == -1) { + lowestIntensity = intensity; + lowestClient = i; + } + } + } + + return lowestClient; +} + +bool AddSurvivor() { + Echo(2, "AddSurvivor"); + + if (GetClientCount(false) >= MaxClients - 1) { + return false; + } + + bool result = false; + if(GetFeatureStatus(FeatureType_Native, "NextBotCreatePlayerBotSurvivorBot") != FeatureStatus_Available) { + // Fallback to manual kick trick if no CreateSurvivorBot API + int i = CreateFakeClient("ABMclient2"); + if (IsClientValid(i)) { + if (DispatchKeyValue(i, "classname", "SurvivorBot")) { + ChangeClientTeam(i, 2); + + if (DispatchSpawn(i)) { + result = true; + } + } + KickClient(i); + } + } else { + result = CreateSurvivorBot() > 0; + } + return result; +} + +bool AddInfected(char model[32]="", int version=0) { + Echo(2, "AddInfected: '%s' %d", model, version); + + if (GetClientCount(false) >= MaxClients - 1) { + return false; + } + + CleanSIName(model); + int i = CreateFakeClient("ABMclient3"); + + if (IsClientValid(i)) { + ChangeClientTeam(i, 3); + Format(g_sB, sizeof(g_sB), "%s auto area", model); + + switch (version) { + case 0: QuickCheat(i, "z_spawn_old", g_sB); + case 1: QuickCheat(i, "z_spawn", g_sB); + } + + KickClient(i); + return true; + } + + return false; +} + +void GhostsModeProtector(int state=0) { + Echo(2, "GhostsModeProtector: %d", state); + // CAREFUL: 0 starts this function and you must close it with 1 or + // risk breaking things. Close this with 1 immediately when done. + + // e.g., + // GhostsModeProtector(0); + // z_spawn_old tank auto; + // GhostsModeProtector(1); + + static int ghosts[MAXPLAYERS + 1]; + static int lifeState[MAXPLAYERS + 1]; // prevent early rise from the dead + + switch (state) { + case 0: { + for (int i = 1; i <= MaxClients; i++) { + if (GetQRtmp(i) && g_tmpOnteam == 3) { + if (GetEntProp(i, Prop_Send, "m_isGhost") == 1 || g_tmpQueued) { + SetEntProp(i, Prop_Send, "m_isGhost", 0); + ghosts[i] = 1; + } + + if (GetEntProp(i, Prop_Send, "m_lifeState") == 1) { + SetEntProp(i, Prop_Send, "m_lifeState", 0); + g_QRtmp.SetValue("status", 1, true); + lifeState[i] = 1; + } + } + } + } + + case 1: { + for (int i = 1; i <= MaxClients; i++) { + if (ghosts[i] == 1) { + SetEntProp(i, Prop_Send, "m_isGhost", 1); + } + + if (lifeState[i] == 1) { + SetEntProp(i, Prop_Send, "m_lifeState", 1); + } + + ghosts[i] = 0; + lifeState[i] = 0; + } + } + } + + if (state == 0) { + RequestFrame(GhostsModeProtector, 1); + } +} + +void CleanSIName(char model[32]) { + Echo(2, "CleanSIName: %s", model); + + int i; + static char tmpModel[32]; + + if (model[0] != EOS) { + for (i = 0; i < sizeof(g_InfectedNames); i++) { + strcopy(tmpModel, sizeof(tmpModel), g_InfectedNames[i]); + if (StrContains(tmpModel, model, false) == 0) { + model = tmpModel; + return; + } + } + + if (StrContains("Tank", model, false) == 0) { + model = "Tank"; + return; + } + } + + i = GetRandomInt(0, sizeof(g_InfectedNames) - 1); + strcopy(model, sizeof(model), g_InfectedNames[i]); +} + +void SwitchToSpec(int client, int onteam=1) { + Echo(2, "SwitchToSpec: %d %d", client, onteam); + + if (GetQRecord(client)) { + // clearparent jockey bug switching teams (thanks to Lux) + AcceptEntityInput(client, "clearparent"); + g_QRecord.SetValue("inspec", true, true); + ChangeClientTeam(client, onteam); + + if (GetRealClient(g_target) == client) { + if (g_onteam == 2) { + AssignModel(g_target, g_model, g_IdentityFix); + } + + if (HasEntProp(g_target, Prop_Send, "m_humanSpectatorUserID")) { + SetEntProp(g_target, Prop_Send, "m_humanSpectatorUserID", 0); + } + } + } +} + +void QuickCheat(int client, char [] cmd, char [] arg) { + Echo(2, "QuickCheat: %d %s %s", client, cmd, arg); + + int flags = GetCommandFlags(cmd); + SetCommandFlags(cmd, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", cmd, arg); + SetCommandFlags(cmd, flags); +} + +void SwitchToBot(int client, int target, bool si_ghost=true) { + Echo(2, "SwitchToBot: %d %d %d", client, target, si_ghost); + + if (IsClientValid(target, 0, 0)) { + Unqueue(client); + + switch (GetClientTeam(target)) { + case 2: TakeoverBotSig(client, target); + case 3: TakeoverZombieBotSig(client, target, si_ghost); + } + } +} + +void Takeover(int client, int onteam) { + Echo(2, "Takeover: %d %d", client, onteam); + + if (GetQRecord(client)) { + if (IsClientValid(g_target, 0, 0)) { + if (client != g_target && GetClientTeam(g_target) == onteam) { + SwitchToBot(client, g_target); + return; + } + } + + int nextBot; + nextBot = GetNextBot(onteam, 0, true); + + if (IsClientValid(nextBot)) { + SwitchToBot(client, nextBot); + return; + } + + switch (onteam) { + case 2: { + if (g_KeepDead == 1 && !g_status) { + if (g_onteam == 2 && CountTeamMates(2, 0) == 0) { + ChangeClientTeam(client, 2); + ForcePlayerSuicide(client); // without this player may spawn if survivors are close to start + } + + return; + } + + QueueUp(client, 2); + AddSurvivor(); + } + + case 3: { + QueueUp(client, 3); + AddInfected(); + } + } + } +} + +public Action TakeoverTimer(Handle timer, any client) { + Echo(4, "TakeoverTimer: %d", client); + + if (CountTeamMates(2) <= 0) { + return Plugin_Handled; + } + + static int team2; + static int team3; + static int teamX; + + if (GetQRecord(client)) { + if (GetClientTeam(client) >= 2) { + return Plugin_Handled; + } + + teamX = 2; + if (g_onteam == 3) { + teamX = 3; + } + + if (g_IsVs && g_onteam <= 1) { + team2 = CountTeamMates(2, 1); + team3 = CountTeamMates(3, 1); + + if (team3 < team2) { + teamX = 3; + } + } + + if (CountTeamMates(teamX, 1) < g_TeamLimit) { + Takeover(client, teamX); + } + } + + return Plugin_Handled; +} + +int CountTeamMates(int onteam, int mtype=2) { + Echo(2, "CountTeamMates: %d %d", onteam, mtype); + + // mtype 0: counts only bots + // mtype 1: counts only humans + // mtype 2: counts all players on team + + static int clients, bots, humans; + clients = bots = humans = 0; + + for (int i = 1; i <= MaxClients; i++) { + if (IsClientValid(i, onteam)) { + clients++; + + if(IsFakeClient(GetRealClient(i))) { + bots++; + } else { + humans++; + } + } + } + + switch (mtype) { + case 0: clients = bots; + case 1: clients = humans; + } + + return clients; +} + +int GetClientManager(int target) { + Echo(4, "GetClientManager: %d", target); + + int result = -1; + target = GetRealClient(target); + + if (IsClientValid(target)) { + result = IsFakeClient(target) ? 0 : target; + } + + return result; +} + +int GetNextBot(int onteam, int start=1, bool alive=false) { + Echo(2, "GetNextBot: %d %d %d", onteam, start, alive); + + static int bot, j; + bot = 0; + j = start; + + if (onteam == 3) { + alive = true; + } + + for (int i = 1; i <= MaxClients; i++) { + if (j > 32) { + j = 1; + } + + if (IsClientValid(j, onteam, 0)) { + if (GetClientManager(j) == 0) { + if (onteam == 2) { + bot = j; + } + + if (alive && IsPlayerAlive(j)) { + return j; + } + + else if (!alive) { + return j; + } + } + } + + j++; + } + + return bot; +} + +void CycleBots(int client, int onteam) { + Echo(2, "CycleBots: %d %d", client, onteam); + + if (onteam <= 1) { + return; + } + + if (GetQRecord(client)) { + int bot = GetNextBot(onteam, g_lastid, true); + if (IsClientValid(bot, onteam, 0)) { + SwitchToBot(client, bot, false); + } + } +} + +void SwitchTeam(int client, int onteam, char model[32]="") { + Echo(2, "SwitchTeam: %d %d", client, onteam); + + if (GetQRecord(client)) { + if (GetClientTeam(client) >= 2) { + if (onteam == 2 && onteam == g_onteam) { + return; // keep survivors from rejoining survivors + } + } + + if (g_onteam == 2 && onteam <= 1) { + if (IsClientValid(g_target, 0, 0)) { + SwitchToBot(client, g_target); + } + } + + switch (onteam) { + case 0: GoIdle(client, 0); + case 1: GoIdle(client, 1); + //case 4: ChangeClientTeam(client, 4); + default: { + if (onteam <= 3 && onteam >= 2) { + if (g_onteam != onteam) { + GoIdle(client, 1); + } + + g_QRecord.SetString("model", model, true); + + if (onteam == 3) { + if (g_IsVs) { // see if a proper way to get on team 2 exist + static int switches; // A Lux idea + switches = GetConVarInt(g_cvMaxSwitches); + SetConVarInt(g_cvMaxSwitches, 9999); + ChangeClientTeam(client, onteam); + SetConVarInt(g_cvMaxSwitches, switches); + return; + } + + g_QRecord.SetValue("onteam", onteam,true); + g_QRecord.SetString("ghost", model, true); + QueueSI(client, g_rdelay); + return; + } + + Takeover(client, onteam); + } + } + } + } +} + +void QueueSI(int client, float delay=1.0) { + Echo(2, "QueueSI: %d %f", client, delay); + + if (g_rDelays[client] != null) { + KillTimer(g_rDelays[client]); + g_rDelays[client] = null; + } + + g_rDelays[client] = CreateTimer( + delay, QueueSITimer, client, TIMER_REPEAT + ); +} + +Action QueueSITimer(Handle Timer, int client) { + Echo(2, "QueueSITimer: %d", client); + + if (GetQRecord(client) && g_onteam == 3) { + QueueUp(client, 3); + + if (AddInfected(g_ghost, 1)) { + g_QRecord.SetValue("rdelay", g_RespawnDelay, true); + g_QRecord.SetString("ghost", "", true); + } + } + + g_rDelays[client] = null; + return Plugin_Stop; +} + +Action MkBotsCmd(int client, int args) { + Echo(2, "MkBotsCmd: %d", client); + + switch(args) { + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + int asmany = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + int onteam = StringToInt(g_sB); + + if (onteam >= 2 || onteam <= 3) { + MkBots(asmany, onteam); + } + } + } + return Plugin_Handled; +} + +void MkBots(int asmany, int onteam) { + Echo(2, "MkBots: %d %d", asmany, onteam); + + if (asmany < 0) { + asmany = asmany * -1 - CountTeamMates(onteam); + } + + float rate; + DataPack pack = new DataPack(); + + switch (onteam) { + case 2: rate = 0.2; + case 3: rate = 0.4; + } + + g_MkBotsTimer = CreateDataTimer(rate, MkBotsTimer, pack, TIMER_REPEAT); + pack.WriteCell(asmany); + pack.WriteCell(onteam); +} + +public Action MkBotsTimer(Handle timer, Handle pack) { + Echo(2, "MkBotsTimer"); + + static int i; + + ResetPack(pack); + int asmany = ReadPackCell(pack); + int onteam = ReadPackCell(pack); + + if (i++ < asmany) { + switch (onteam) { + case 2: AddSurvivor(); + case 3: AddInfected(); + } + + return Plugin_Continue; + } + + i = 0; + g_MkBotsTimer = null; + return Plugin_Stop; +} + +Action RmBotsCmd(int client, int args) { + Echo(2, "RmBotsCmd: %d", client); + + int asmany; + int onteam; + + switch(args) { + case 1: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + onteam = StringToInt(g_sB); + asmany = MaxClients; + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + asmany = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + onteam = StringToInt(g_sB); + } + } + + if (onteam >= 2 || onteam <= 3) { + RmBots(asmany, onteam); + } + return Plugin_Handled; +} + +void RmBots(int asmany, int onteam) { + Echo(2, "RmBots: %d %d", asmany, onteam); + + int j; + + if (onteam == 0) { + onteam = asmany; + asmany = MaxClients; + } + + else if (asmany == -0) { + return; + } + + else if (asmany < 0) { + asmany += CountTeamMates(onteam); + if (asmany <= 0) { + return; + } + } + + for (int i = MaxClients; i >= 1; i--) { + if (GetClientManager(i) == 0 && GetClientTeam(i) == onteam) { + + j++; + if (g_StripKick == 1) { + StripClient(i); + } + + KickClient(i); + + if (j >= asmany) { + break; + } + } + } +} + +// ================================================================== // +// MODEL FEATURES +// ================================================================== // + + +void AutoModel(int client) { + Echo(5, "AutoModel: %d", client); + RequestFrame(_AutoModel, client); +} + +public void _AutoModel(int client) { + Echo(5, "_AutoModel: %d", client); + + if (IsClientValid(client, 2)) { + SDKUnhook(client, SDKHook_SpawnPost, AutoModel); + } + + if (g_AutoModel && IsClientValid(client, 2)) { + static int realClient; + realClient = GetRealClient(client); + if (GetQRecord(realClient) && g_model[0] != EOS) { + return; + } + + static int set, survivors, character; + set = GetSurvivorSet(client); + GetAllSurvivorModels(client); + + survivors = CountTeamMates(2); + character = g_models[GetClientModelIndex(client)]; + if (character == 0 || character < survivors / 8) { + return; + } + + for (int i = 0; i < 4; i++) { + for (int index = set; index < sizeof(g_models); index++) { + if (g_models[index] <= i) { + g_models[index]++; + AssignModel(client, g_SurvivorNames[index], g_IdentityFix); + i = 4; // we want to fall through + break; + } + + if (set != 0 && index + 1 == sizeof(g_models)) { + index=-1; set=0; + } + } + } + } +} + +int GetSurvivorSet(int client) { + Echo(6, "GetSurvivorSet: %d", client); + + if (g_survivorSetScan && IsClientValid(client, 2)) { + g_survivorSetScan = false; + g_survivorSet = GetClientModelIndex(client); + + if (g_survivorSet >= 0 && g_survivorSet <= 3) { + g_survivorSet = 0; + } else { + g_survivorSet = 4; + } + } + + return g_survivorSet; +} + +void GetAllSurvivorModels(int client=-1) { + Echo(2, "GetAllSurvivorModels"); + + static int index; + static const int models[8]; + g_models = models; + + for (int i = 1; i <= MaxClients; i++) { + if (client == i) { + continue; + } + + index = -1; + + if (GetQRecord(i) && g_onteam == 2 && g_model[0] != EOS) { + index = GetModelIndexByName(g_model, 2); + } + + else if (IsClientValid(i, 2, 0) && GetRealClient(i) == i) { + index = GetClientModelIndex(i); + } + + if (index >= 0) { + g_models[index]++; + } + } +} + +void PrecacheModels() { + Echo(2, "PrecacheModels"); + + for (int i = 0; i < sizeof(g_SurvivorPaths); i++) { + PrecacheModel(g_SurvivorPaths[i]); + } +} + +void AssignModel(int client, char [] model, int identityFix) { + Echo(2, "AssignModel: %d %s %d", client, model, identityFix); + + if (identityFix == 1 && IsClientValid(client, 2)) { + if (IsClientsModel(client, model)) { + return; + } + + int i = GetModelIndexByName(model); + int realClient = GetRealClient(client); + + if (i >= 0 && i < sizeof(g_SurvivorPaths)) { + if(i == 5) { + SetEntProp(client, Prop_Send, "m_survivorCharacter", g_Zoey); + } else { + SetEntProp(client, Prop_Send, "m_survivorCharacter", i); + } + + SetEntityModel(client, g_SurvivorPaths[i]); + Format(g_pN, sizeof(g_pN), "%s", g_SurvivorNames[i]); + + if (IsFakeClient(client)) { + SetClientInfo(client, "name", g_pN); + } + + if (GetQRecord(realClient)) { + g_QRecord.SetString("model", g_pN, true); + } + } + } +} + +int GetClientModelIndex(int client) { + Echo(3, "GetClientModelIndex: %d", client); + + if (!IsClientValid(client)) { + return -2; + } + + char modelName[64]; + + GetEntPropString(client, Prop_Data, "m_ModelName", modelName, sizeof(modelName)); + for (int i = 0; i < sizeof(g_SurvivorPaths); i++) { + if (StrEqual(modelName, g_SurvivorPaths[i], false)) { + return i; + } + } + + return -1; +} + +int GetModelIndexByName(char [] name, int onteam=2) { + Echo(2, "GetModelIndexByName: %s %d", name, onteam); + + if (onteam == 2) { + for (int i; i < sizeof(g_SurvivorNames); i++) { + if (StrContains(name, g_SurvivorNames[i], false) != -1) { + return i; + } + } + } + + else if (onteam == 3) { + for (int i; i < sizeof(g_InfectedNames); i++) { + if (StrContains(g_InfectedNames[i], name, false) != -1) { + return i; + } + } + } + + return -1; +} + +bool IsClientsModel(int client, char [] name) { + Echo(2, "IsClientsModel: %d %s", client, name); + + int modelIndex = GetClientModelIndex(client); + Format(g_sB, sizeof(g_sB), "%s", g_SurvivorNames[modelIndex]); + return StrEqual(name, g_sB); +} + +void GetBotCharacter(int client, char strBuffer[32]) { + Echo(2, "GetBotCharacter: %d", client); + + if (IsClientValid(client)) { + strBuffer = ""; + + switch (GetClientTeam(client)) { + case 2: GetSurvivorCharacter(client, strBuffer); + case 3: GetInfectedCharacter(client, strBuffer); + } + } +} + +void GetSurvivorCharacter(int client, char strBuffer[32]) { + Echo(2, "GetSurvivorCharacter: %d %s", client, strBuffer); + + GetEntPropString(client, Prop_Data, "m_ModelName", g_sB, sizeof(g_sB)); + for (int i = 0; i < sizeof(g_SurvivorPaths); i++) { + if (StrEqual(g_SurvivorPaths[i], g_sB)) { + Format(strBuffer, sizeof(strBuffer), g_SurvivorNames[i]); + break; + } + } +} + +void GetInfectedCharacter(int client, char strBuffer[32]) { + Echo(2, "GetInfectedCharacter: %d %s", client, strBuffer); + + switch (GetEntProp(client, Prop_Send, "m_zombieClass")) { + case 1: strBuffer = "Smoker"; + case 2: strBuffer = "Boomer"; + case 3: strBuffer = "Hunter"; + case 4: strBuffer = "Spitter"; + case 5: strBuffer = "Jockey"; + case 6: strBuffer = "Charger"; + case 8: strBuffer = "Tank"; + } +} + +// ================================================================== // +// BLACK MAGIC SIGNATURES. SOME SPOOKY SHIT. +// ================================================================== // + +int GetOS() { + Echo(2, "GetOS"); + return GameConfGetOffset(g_GameData, "OS"); +} + +void RoundRespawnSig(int client) { + Echo(2, "RoundRespawnSig: %d", client); + + static Handle hRoundRespawn; + if (hRoundRespawn == null) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(g_GameData, SDKConf_Signature, "RoundRespawn"); + hRoundRespawn = EndPrepSDKCall(); + } + + if (hRoundRespawn != null) { + SDKCall(hRoundRespawn, client); + } + + else { + PrintToChat(client, "[ABM] RoundRespawnSig Signature broken."); + SetFailState("[ABM] RoundRespawnSig Signature broken."); + } +} + +void SetHumanSpecSig(int bot, int client) { + Echo(2, "SetHumanSpecSig: %d %d", bot, client); + + static Handle hSpec; + if (hSpec == null) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(g_GameData, SDKConf_Signature, "SetHumanSpec"); + PrepSDKCall_AddParameter(SDKType_CBasePlayer, SDKPass_Pointer); + hSpec = EndPrepSDKCall(); + } + + if (IsClientValid(client) && IsClientValid(bot)) { + if(hSpec != null) { + SDKCall(hSpec, bot, client); + ResetClientSpecUserId(client, bot); + } + + else { + PrintToChat(client, "[ABM] SetHumanSpecSig Signature broken."); + SetFailState("[ABM] SetHumanSpecSig Signature broken."); + } + } +} + +void ResetClientSpecUserId(int client, int target) { + Echo(2, "ResetClientSpecUserId: %d %d", client, target); + + if (!IsClientValid(client) || !IsClientValid(target)) { + return; + } + + static int spec, userid; + userid = GetClientUserId(client); + + for (int i = 1; i <= MaxClients; i++) { + if (IsClientValid(i, 2, 0)) { + if (HasEntProp(i, Prop_Send, "m_humanSpectatorUserID")) { + spec = GetEntProp(i, Prop_Send, "m_humanSpectatorUserID"); + if (userid == spec && i != target) { + SetEntProp(i, Prop_Send, "m_humanSpectatorUserID", 0); + } + } + } + } +} + +void State_TransitionSig(int client, int mode) { + Echo(2, "State_TransitionSig: %d %d", client, mode); + + static Handle hSpec; + if (hSpec == null) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(g_GameData, SDKConf_Signature, "State_Transition"); + PrepSDKCall_AddParameter(SDKType_PlainOldData , SDKPass_Plain); + hSpec = EndPrepSDKCall(); + } + + if(hSpec != null) { + SDKCall(hSpec, client, mode); // mode 8, press 8 to get closer + } + + else { + PrintToChat(client, "[ABM] State_TransitionSig Signature broken."); + SetFailState("[ABM] State_TransitionSig Signature broken."); + } +} + +bool TakeoverBotSig(int client, int target) { + Echo(2, "TakeoverBotSig: %d %d", client, target); + + if (!GetQRecord(client)) { + return false; + } + + static Handle hSwitch; + + if (hSwitch == null) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(g_GameData, SDKConf_Signature, "TakeOverBot"); + PrepSDKCall_AddParameter(SDKType_Bool, SDKPass_Plain); + hSwitch = EndPrepSDKCall(); + } + + if (hSwitch != null) { + if (IsClientInKickQueue(target)) { + KickClient(target); + } + + else if (IsClientValid(target, 2, 0)) { + SwitchToSpec(client); + + if (GetRealClient(target) != client) { + GetBotCharacter(target, g_model); + g_QRecord.SetString("model", g_model, true); + } + + SetHumanSpecSig(target, client); + SDKCall(hSwitch, client, true); + + GetConVarString(g_cvGameMode, g_sB, sizeof(g_sB)); + SendConVarValue(client, g_cvGameMode, g_sB); + return true; + } + } + + else { + PrintToChat(client, "[ABM] TakeoverBotSig Signature broken."); + SetFailState("[ABM] TakeoverBotSig Signature broken."); + } + + g_QRecord.SetValue("lastid", target, true); + if (GetClientTeam(client) == 1) { + QueueUp(client, 2); + } + + return false; +} + +bool TakeoverZombieBotSig(int client, int target, bool si_ghost) { + Echo(2, "TakeoverZombieBotSig: %d %d %d", client, target, si_ghost); + + if (!GetQRecord(client)) { + return false; + } + + static Handle hSwitch; + + if (hSwitch == null) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(g_GameData, SDKConf_Signature, "TakeOverZombieBot"); + PrepSDKCall_AddParameter(SDKType_CBasePlayer, SDKPass_Pointer); + hSwitch = EndPrepSDKCall(); + } + + if (hSwitch != null) { + if (IsClientInKickQueue(target)) { + KickClient(target); + } + + else if (IsClientValid(target, 3, 0) && IsPlayerAlive(target)) { + SwitchToSpec(client); + SDKCall(hSwitch, client, target); + + if (si_ghost) { + State_TransitionSig(client, 8); + if (GetEntProp(client, Prop_Send, "m_zombieClass") == 8) { + CreateTimer(1.0, ForceSpawnTimer, client, TIMER_REPEAT); + } + } + + // trade off, see ladders, not survivors + SendConVarValue(client, g_cvGameMode, "versus"); + SendConVarValue(client, g_cvConsistency, g_consistency); + return true; + } + } + + else { + PrintToChat(client, "[ABM] TakeoverZombieBotSig Signature broken."); + SetFailState("[ABM] TakeoverZombieBotSig Signature broken."); + } + + g_QRecord.SetValue("lastid", target, true); + if (GetClientTeam(client) == 1) { + QueueUp(client, 3); + } + + return false; +} + +// ================================================================== // +// PUBLIC INTERFACE AND MENU HANDLERS +// ================================================================== // + +public Action TeleportClientCmd(int client, int args) { + Echo(2, "TeleportClientCmd: %d", client); + + int level; + + switch(args) { + case 1: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + } + + if (args) { + level = 2; + } + + TeleportClientHandler(client, level); + return Plugin_Handled; +} + +public void TeleportClientHandler(int client, int level) { + Echo(2, "TeleportClientHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "TeleportClientHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Teleport Client", 2, 1); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Teleporting", g_sB); + TeamMatesMenu(client, g_sB, 2, 1); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (GetClientTeam(menuArg0) <= 1) { + menuArg0 = GetPlayClient(menuArg0); + } + + TeleportClient(menuArg0, menuArg1); + } + + GenericMenuCleaner(client); + } + } +} + +public Action SwitchTeamCmd(int client, int args) { + Echo(2, "SwitchTeamCmd: %d", client); + + int level; + + char model[32]; + GetCmdArg(args, model, sizeof(model)); + int result = StringToInt(model); + CleanSIName(model); + + if (args == 1 || args == 2 && result == 0) { + menuArg0 = client; + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + + else if (args >= 2) { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + + if (args) { + level = 2; + } + + else if (!IsAdmin(client)) { + menuArg0 = client; + level = 1; + } + + if (menuArg1 != 3) { + model = ""; + } + + SwitchTeamHandler(client, level, model); + return Plugin_Handled; +} + +public void SwitchTeamHandler(int client, int level, char model[32]) { + Echo(2, "SwitchTeamHandler: %d %d %s", client, level, model); + + if (!RegMenuHandler(client, "SwitchTeamHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Switch Client's Team", 1); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Switching", g_sB); + TeamsMenu(client, g_sB); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (!g_IsVs && !IsAdmin(client) && menuArg1 == 3) { + GenericMenuCleaner(client); + return; + } + + if (GetQRecord(menuArg0)) { + g_QRecord.SetValue("rdelay", 0.1, true); + SwitchToSpec(menuArg0); + } + + SwitchTeam(menuArg0, menuArg1, model); + } + + GenericMenuCleaner(client); + } + } +} + +public Action AssignModelCmd(int client, int args) { + Echo(2, "AssignModelCmd: %d", client); + + int level; + + switch(args) { + case 1: { + menuArg0 = client; + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = GetModelIndexByName(g_sB); + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = GetModelIndexByName(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + } + } + + if (args) { + level = 2; + } + + AssignModelHandler(client, level); + return Plugin_Handled; +} + +public void AssignModelHandler(int client, int level) { + Echo(2, "AssignModelHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "AssignModelHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Change Client's Model", 2, 0, false); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Modeling", g_sB); + ModelsMenu(client, g_sB); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (GetClientTeam(menuArg0) <= 1) { + menuArg0 = GetPlayClient(menuArg0); + } + + AssignModel(menuArg0, g_SurvivorNames[menuArg1], 1); + } + + GenericMenuCleaner(client); + } + } +} + +public Action SwitchToBotCmd(int client, int args) { + Echo(2, "SwitchToBotCmd: %d", client); + + int level; + + switch(args) { + case 1: { + menuArg0 = client; + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + } + + if (args) { + level = 2; + } + + else if (!IsAdmin(client)) { + menuArg0 = client; + level = 1; + } + + SwitchToBotHandler(client, level); + return Plugin_Handled; +} + +public void SwitchToBotHandler(int client, int level) { + Echo(2, "SwitchToBotHandler: %d %d", client, level); + + int homeTeam = ClientHomeTeam(client); + if (!RegMenuHandler(client, "SwitchToBotHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Takeover Bot", 1); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Takeover", g_sB); + TeamMatesMenu(client, g_sB, 0, 0, true, false, homeTeam); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (IsClientValid(menuArg1)) { + if (homeTeam != 3 && GetClientTeam(menuArg1) == 3) { + if (!IsAdmin(client)) { + GenericMenuCleaner(client); + return; + } + } + + if (GetClientManager(menuArg1) == 0) { + SwitchToBot(menuArg0, menuArg1, false); + } + } + } + + GenericMenuCleaner(client); + } + } +} + +public Action RespawnClientCmd(int client, int args) { + Echo(2, "RespawnClientCmd: %d", client); + + int level; + + switch(args) { + case 1: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + menuArg1 = menuArg0; + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + } + + if (args) { + level = 2; + } + + RespawnClientHandler(client, level); + return Plugin_Handled; +} + +public void RespawnClientHandler(int client, int level) { + Echo(2, "RespawnClientHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "RespawnClientHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Respawn Client"); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Respawning", g_sB); + TeamMatesMenu(client, g_sB); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (GetClientTeam(menuArg0) <= 1) { + menuArg0 = GetPlayClient(menuArg0); + } + + RespawnClient(menuArg0, menuArg1); + } + + GenericMenuCleaner(client); + } + } +} + +public Action CycleBotsCmd(int client, int args) { + Echo(2, "CycleBotsCmd: %d", client); + + int level; + + switch(args) { + case 1: { + menuArg0 = client; + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + } + + if (args) { + if (menuArg1 > 3 || menuArg1 < 2) { + return Plugin_Handled; + } + + level = 2; + } + + CycleBotsHandler(client, level); + return Plugin_Handled; +} + +public void CycleBotsHandler(int client, int level) { + Echo(2, "CycleBotsHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "CycleBotsHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Cycle Client", 1); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Cycling", g_sB); + TeamsMenu(client, g_sB, false); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (!IsAdmin(client) && menuArg1 == 3) { + GenericMenuCleaner(client); + return; + } + + CycleBots(menuArg0, menuArg1); + menuArg1 = 0; + } + + CycleBotsHandler(client, 1); + } + } +} + +public Action StripClientCmd(int client, int args) { + Echo(2, "StripClientCmd: %d", client); + + int target; + int level; + + switch(args) { + case 1: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + target = StringToInt(g_sB); + target = GetPlayClient(target); + + if (CanClientTarget(client, target)) { + StripClient(target); + } + + return Plugin_Handled; + } + + case 2: { + GetCmdArg(1, g_sB, sizeof(g_sB)); + menuArg0 = StringToInt(g_sB); + GetCmdArg(2, g_sB, sizeof(g_sB)); + menuArg1 = StringToInt(g_sB); + } + } + + if (args) { + level = 2; + } + + StripClientHandler(client, level); + return Plugin_Handled; +} + +public void StripClientHandler(int client, int level) { + Echo(2, "StripClientHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "StripClientHandler", level, 0)) { + return; + } + + switch(level) { + case 0: TeamMatesMenu(client, "Strip Client", 2, 1); + case 1: { + GetClientName(menuArg0, g_sB, sizeof(g_sB)); + Format(g_sB, sizeof(g_sB), "%s: Stripping", g_sB); + InvSlotsMenu(client, menuArg0, g_sB); + } + + case 2: { + if (CanClientTarget(client, menuArg0)) { + if (GetClientTeam(menuArg0) <= 1) { + menuArg0 = GetPlayClient(menuArg0); + } + + StripClientSlot(menuArg0, menuArg1); + menuArg1 = 0; + StripClientHandler(client, 1); + } + } + } +} + +public Action ResetCmd(int client, int args) { + Echo(2, "ResetCmd: %d", client); + + for (int i = 1; i <= MaxClients; i++) { + GenericMenuCleaner(i); + if (GetQRecord(i)) { + CancelClientMenu(i, true, null); + } + } + return Plugin_Handled; +} + +bool RegMenuHandler(int client, char [] handler, int level, int clearance=0) { + Echo(2, "RegMenuHandler: %d %s %d %d", client, handler, level, clearance); + + g_callBacks.PushString(handler); + if (!IsAdmin(client) && level <= clearance) { + GenericMenuCleaner(client); + return false; + } + + return true; +} + +public Action MainMenuCmd(int client, int args) { + Echo(2, "MainMenuCmd: %d", client); + + GenericMenuCleaner(client); + MainMenuHandler(client, 0); + return Plugin_Handled; +} + +public void MainMenuHandler(int client, int level) { + Echo(2, "MainMenuHandler: %d %d", client, level); + + if (!RegMenuHandler(client, "MainMenuHandler", level, 0)) { + return; + } + + int cmd = menuArg0; + menuArg0 = 0; + + char title[32]; + Format(title, sizeof(title), "ABM Menu %s", PLUGIN_VERSION); + + switch(level) { + case 0: MainMenu(client, title); + case 1: { + switch(cmd) { + case 0: TeleportClientCmd(client, 0); + case 1: SwitchTeamCmd(client, 0); + case 2: AssignModelCmd(client, 0); + case 3: SwitchToBotCmd(client, 0); + case 4: RespawnClientCmd(client, 0); + case 5: CycleBotsCmd(client, 0); + case 6: StripClientCmd(client, 0); + } + } + } +} + +// ================================================================== // +// MENUS BACKBONE +// ================================================================== // + +void GenericMenuCleaner(int client, bool clearStack=true) { + Echo(2, "GenericMenuCleaner: %d %d", client, clearStack); + + for (int i = 0; i < sizeof(g_menuItems[]); i++) { + g_menuItems[client][i] = 0; + } + + if (clearStack == true) { + if (g_callBacks != null) { + delete g_callBacks; + } + + g_callBacks = new ArrayStack(128); + } +} + +public int GenericMenuHandler(Menu menu, MenuAction action, int param1, int param2) { + Echo(2, "GenericMenuHandler: %d %d", param1, param2); + + int client = param1; + int i; // -1; + char sB[128]; + + if (IsClientValid(param1)) { + for (i = 0; i < sizeof(g_menuItems[]); i++) { + if (menuArgs[i] == 0) { + break; + } + } + } + + switch(action) { + case MenuAction_Select: { + menu.GetItem(param2, g_sB, sizeof(g_sB)); + menuArgs[i] = StringToInt(g_sB); + i = i + 1; + } + + case MenuAction_Cancel: { + if (param2 == MenuCancel_ExitBack) { + if (i > 0) { + i = i - 1; + menuArgs[i] = 0; + } + + else if (i == 0) { + + if (g_callBacks.Empty) { + GenericMenuCleaner(param1); + return 0; + } + + g_callBacks.PopString(g_sB, sizeof(g_sB)); + GenericMenuCleaner(param1, false); + + while (!g_callBacks.Empty) { + g_callBacks.PopString(sB, sizeof(sB)); + + if (!StrEqual(g_sB, sB)) { + g_callBacks.PushString(sB); + break; + } + } + + if (g_callBacks.Empty) { + GenericMenuCleaner(param1); + return 0; + } + } + } + + else { + return 0; + } + } + + case MenuAction_End: { + delete menu; + return 0; + } + } + + if (g_callBacks == null || g_callBacks.Empty) { + GenericMenuCleaner(param1); + return 0; + } + + g_callBacks.PopString(g_sB, sizeof(g_sB)); + callBack = GetFunctionByName(null, g_sB); + + Call_StartFunction(null, callBack); + Call_PushCell(param1); + Call_PushCell(i); + Call_Finish(); + return 0; +} + +// ================================================================== // +// MENUS +// ================================================================== // + +void MainMenu(int client, char [] title) { + Echo(2, "MainMenu: %d %s", client, title); + + Menu menu = new Menu(GenericMenuHandler); + menu.SetTitle(title); + menu.AddItem("0", "Teleport Client"); // "Telespiznat"); // teleport + menu.AddItem("1", "Switch Client Team"); //"Swintootle"); // switch team + menu.AddItem("2", "Change Client Model"); //"Changdangle"); // makeover + menu.AddItem("3", "Switch Client Bot"); //"Inbosnachup"); // takeover + menu.AddItem("4", "Respawn Client"); //"Respiggle"); // respawn + menu.AddItem("5", "Cycle Client"); //"Cycolicoo"); // cycle + menu.AddItem("6", "Strip Client"); //"Upsticky"); // strip + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, 120); +} + +void InvSlotsMenu(int client, int target, char [] title) { + Echo(2, "InvSlotsMenu: %d %d %s", client, target, title); + + int ent; + char weapon[64]; + Menu menu = new Menu(GenericMenuHandler); + menu.SetTitle(title); + + for (int i; i < 5; i++) { + IntToString(i, g_sB, sizeof(g_sB)); + ent = GetPlayerWeaponSlot(target, i); + + if (IsEntityValid(ent)) { + GetEntityClassname(ent, weapon, sizeof(weapon)); + menu.AddItem(g_sB, weapon); + } + } + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, 120); +} + +void ModelsMenu(int client, char [] title) { + Echo(2, "ModelsMenu: %d %s", client, title); + + Menu menu = new Menu(GenericMenuHandler); + menu.SetTitle(title); + + for (int i; i < sizeof(g_SurvivorNames); i++) { + IntToString(i, g_sB, sizeof(g_sB)); + menu.AddItem(g_sB, g_SurvivorNames[i]); + } + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, 120); +} + +void TeamsMenu(int client, char [] title, bool all=true) { + Echo(2, "TeamsMenu: %d %s %d", client, title, all); + + Menu menu = new Menu(GenericMenuHandler); + menu.SetTitle(title); + + if (all) { + menu.AddItem("0", "Idler"); + menu.AddItem("1", "Spectator"); + } + + menu.AddItem("2", "Survivor"); + if (g_IsVs || IsAdmin(client)) { + menu.AddItem("3", "Infected"); + } + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, 120); +} + +void TeamMatesMenu(int client, char [] title, int mtype=2, int target=0, bool incDead=true, + bool repeat=false, int homeTeam=0) { + Echo(2, "TeamMatesMenu: %d %s %d %d %d %d %d", client, title, mtype, target, incDead, repeat, homeTeam); + + Menu menu = new Menu(GenericMenuHandler); + menu.SetTitle(title); + int isAdmin = IsAdmin(client); + char health[32]; + bool mflag = false; + int isAlive; + int playClient; + int bossClient; + int targetClient; + int manager; + + for (int i = 1; i <= MaxClients; i++) { + bossClient = i; + playClient = i; + + if (GetQRecord(i)) { + + if (mtype == 0) { + continue; + } + + if (mtype == 1 || mtype == 2) { + mflag = true; + } + + if (IsClientValid(g_target) && g_target != i) { + isAlive = IsPlayerAlive(g_target); + playClient = g_target; + } + + else { + isAlive = IsPlayerAlive(i); + } + } + + else if (IsClientValid(i)) { + isAlive = IsPlayerAlive(i); + + if (mtype == 0 || mtype == 2) { + mflag = true; + } + + manager = GetClientManager(i); + + if (manager != 0) { + if (target == 0 || !repeat) { + mflag = false; + continue; + } + + bossClient = manager; + } + } + + else { + continue; + } + + // at this point the client is valid. + // bossClient is the human (if there is one) + // playClient is the bot (or human if not idle) + + if (!isAlive && !incDead) { + continue; + } + + if (GetClientTeam(playClient) != homeTeam && !isAdmin) { + continue; + } + + switch(target) { + case 0: targetClient = bossClient; + case 1: targetClient = playClient; + } + + if (mflag) { + mflag = false; + + Format(health, sizeof(health), "%d", GetClientHealth(playClient)); + if (!IsPlayerAlive(playClient)) { + Format(health, sizeof(health), "DEAD"); + } + + else if (GetEntProp(playClient, Prop_Send, "m_isIncapacitated")) { + Format(health, sizeof(health), "DOWN"); + } + + GetClientName(bossClient, g_pN, sizeof(g_pN)); + Format(g_pN, sizeof(g_pN), "%s (%s)", g_pN, health); + IntToString(targetClient, g_sB, sizeof(g_sB)); + + if(bossClient == client && menu.ItemCount > 0) { + menu.InsertItem(0, g_sB, g_pN); + } else { + menu.AddItem(g_sB, g_pN); + } + } + } + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, 120); +} + +// ================================================================== // +// MISC STUFF USEFUL FOR TROUBLESHOOTING +// ================================================================== // + +void Echo(int level, char [] format, any ...) { + static char g_dB[512]; + + if (g_LogLevel >= level) { + VFormat(g_dB, sizeof(g_dB), format, 3); + LogToFile(LOGFILE, g_dB); + PrintToServer("%s", g_dB); + } +} + +void QDBCheckCmd(int client) { + Echo(2, "QDBCheckCmd"); + + PrintToConsole(client, "-- STAT: QDB Size is %d", g_QDB.Size); + PrintToConsole(client, "-- MinPlayers is %d", g_MinPlayers); + + for (int i = 1; i <= MaxClients; i++) { + if (GetQRtmp(i)) { + PrintToConsole(client, "\n -"); + GetClientName(i, g_pN, sizeof(g_pN)); + + float x = g_origin[0]; + float y = g_origin[1]; + float z = g_origin[2]; + + PrintToConsole(client, " - Name: %s", g_pN); + PrintToConsole(client, " - Origin: {%d.0, %d.0, %d.0}", x, y, z); + PrintToConsole(client, " - Status: %d", g_tmpStatus); + PrintToConsole(client, " - Client: %d", g_tmpClient); + PrintToConsole(client, " - Target: %d", g_tmpTarget); + PrintToConsole(client, " - LastId: %d", g_tmpLastid); + PrintToConsole(client, " - OnTeam: %d", g_tmpOnteam); + PrintToConsole(client, " - Queued: %d", g_tmpQueued); + PrintToConsole(client, " - InSpec: %d", g_tmpInspec); + PrintToConsole(client, " - Model: %s", g_tmpModel); + PrintToConsole(client, " -\n"); + } + } +} + +Action QuickClientPrintCmd(int client, int args) { + Echo(2, "QuickClientPrintCmd: %d", client); + + int onteam; + int state; + int manager; + + PrintToConsole(client, "\nTeam\tState\tId\tManager\tName"); + + for (int i = 1; i <= MaxClients; i++) { + if (IsClientValid(i)) { + manager = i; + GetClientName(i, g_pN, sizeof(g_pN)); + onteam = GetClientTeam(i); + state = IsPlayerAlive(i); + + + if (IsFakeClient(i)) { + manager = GetClientManager(i); + } + + PrintToConsole(client, + "%d, \t%d, \t%d, \t%d, \t%s", onteam, state, i, manager, g_pN + ); + } + } + + QDBCheckCmd(client); + return Plugin_Handled; +} +Action DebugCmd(int client, int args) { + ReplyToCommand(client, "CreateSurvivorBot: %b", GetFeatureStatus(FeatureType_Native, "NextBotCreatePlayerBotSurvivorBot") == FeatureStatus_Available); + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/activitymonitor.sp b/scripting/activitymonitor.sp new file mode 100644 index 0000000..e63f560 --- /dev/null +++ b/scripting/activitymonitor.sp @@ -0,0 +1,305 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG +#define PUSH_TIMER 60.0 + +#define PLUGIN_VERSION "1.0" + +#include +#include +//#include + +public Plugin myinfo = +{ + name = "Admin Activity Log", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +enum struct Log { + char name[32]; + char clientSteamID[32]; + char targetSteamID[32]; + char message[256]; + int timestamp; +} +// Plugin data +static ArrayList logs; +static Database g_db; +static char serverID[64]; +static Handle pushTimer; +static ConVar hLogCvarChanges; +static char lastMap[64]; + +//Plugin related +static bool lateLoaded; +static EngineVersion g_Game; + +//L4d2 Specific +static char L4D2_ZDifficulty[16]; +//Generic +static char currentGamemode[32]; + +char playerLastName[MAXPLAYERS+1][32]; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + CreateNative("ActivityMonitor_AddLog", Native_AddLog); + lateLoaded = late; + return APLRes_Success; +} + +public void OnPluginStart() { + g_Game = GetEngineVersion(); + logs = new ArrayList(sizeof(Log)); + + if(!SQL_CheckConfig("activitymonitor")) { + SetFailState("No database entry for 'activitymonitor'; no database to connect to."); + } else if(!ConnectDB()) { + SetFailState("Failed to connect to database."); + } + + hLogCvarChanges = CreateConVar("sm_activitymonitor_log_cvar", "0", "Should this plugin log cvar changes (when using sm_cvar from console)"); + ConVar hServerID = CreateConVar("sm_activitymonitor_id", "", "The name to use for the 'server' column", FCVAR_DONTRECORD); + hServerID.GetString(serverID, sizeof(serverID)); + hServerID.AddChangeHook(CVAR_ServerIDChanged); + + HookEvent("player_first_spawn", Event_Connection); + HookEvent("player_disconnect", Event_Connection); + if(g_Game == Engine_Left4Dead2 || g_Game == Engine_Left4Dead) { + HookEvent("player_incapacitated", Event_L4D2_Incapped); + HookEvent("player_death", Event_L4D2_Death); + ConVar zDifficulty = FindConVar("z_difficulty"); + zDifficulty.GetString(L4D2_ZDifficulty, sizeof(L4D2_ZDifficulty)); + CVAR_DifficultyChanged(zDifficulty, "", L4D2_ZDifficulty); + zDifficulty.AddChangeHook(CVAR_DifficultyChanged); + + zDifficulty.GetString(L4D2_ZDifficulty, sizeof(L4D2_ZDifficulty)); + CVAR_DifficultyChanged(zDifficulty, "", L4D2_ZDifficulty); + zDifficulty.AddChangeHook(CVAR_DifficultyChanged); + } + + ConVar mpGamemode = FindConVar("mp_gamemode"); + if(mpGamemode != null) { + mpGamemode.GetString(currentGamemode, sizeof(currentGamemode)); + mpGamemode.AddChangeHook(CVAR_GamemodeChanged); + } + + + if(!lateLoaded) { + AddLog("INFO", "", "", "Server has started up"); + } + + pushTimer = CreateTimer(PUSH_TIMER, Timer_PushLogs, _, TIMER_REPEAT); + // AutoExecConfig(true, "activitymonitor"); +} + +public void OnPluginEnd() { + TriggerTimer(pushTimer, true); +} + +public void OnMapEnd() { + TriggerTimer(pushTimer, true); +} + +public void OnMapStart() { + static char curMap[64]; + GetCurrentMap(curMap, sizeof(curMap)); + if(!StrEqual(lastMap, curMap)) { + strcopy(lastMap, sizeof(lastMap), curMap); + if(g_Game == Engine_Left4Dead2 || g_Game == Engine_Left4Dead) + Format(curMap, sizeof(curMap), "Map changed to %s (%s %s)", curMap, L4D2_ZDifficulty, currentGamemode); + else + Format(curMap, sizeof(curMap), "Map changed to %s (%s)", curMap, currentGamemode); + AddLog("INFO", "", "", curMap); + } + TriggerTimer(pushTimer, true); +} + +public void CVAR_GamemodeChanged(ConVar convar, const char[] oldValue, const char[] newValue) { + strcopy(currentGamemode, sizeof(currentGamemode), newValue); +} + +public void CVAR_ServerIDChanged(ConVar convar, const char[] oldValue, const char[] newValue) { + strcopy(serverID, sizeof(serverID), newValue); +} + +public void CVAR_DifficultyChanged(ConVar convar, const char[] oldValue, const char[] newValue) { + if(StrEqual(newValue, "Hard", false)) strcopy(L4D2_ZDifficulty, sizeof(L4D2_ZDifficulty), "Advanced"); + else if(StrEqual(newValue, "Impossible", false)) strcopy(L4D2_ZDifficulty, sizeof(L4D2_ZDifficulty), "Expert"); + else { + strcopy(L4D2_ZDifficulty, sizeof(L4D2_ZDifficulty), newValue); + // CVAR value could be lowercase 'normal', convert to 'Normal' + L4D2_ZDifficulty[0] = CharToUpper(L4D2_ZDifficulty[0]); + } +} + +bool ConnectDB() { + char error[255]; + g_db = SQL_Connect("activitymonitor", true, error, sizeof(error)); + if (g_db == null) { + LogError("Database error %s", error); + delete g_db; + return false; + } else { + PrintToServer("[ACTM] Connected to database \"activitymonitor\""); + SQL_LockDatabase(g_db); + SQL_FastQuery(g_db, "SET NAMES \"UTF8mb4\""); + SQL_UnlockDatabase(g_db); + g_db.SetCharset("utf8mb4"); + return true; + } +} + +public Action Timer_PushLogs(Handle h) { + static char query[1024]; + static Log log; + int length = logs.Length; + + if(length > 0) { + Transaction transaction = new Transaction(); + for(int i = 0; i < length; i++) { + logs.GetArray(i, log, sizeof(log)); + g_db.Format(query, sizeof(query), "INSERT INTO `activity_log` (`timestamp`, `server`, `type`, `client`, `target`, `message`) VALUES (%d, NULLIF('%s', ''), '%s', NULLIF('%s', ''), NULLIF('%s', ''), NULLIF('%s', ''))", + log.timestamp, + serverID, + log.name, + log.clientSteamID, + log.targetSteamID, + log.message + ); + transaction.AddQuery(query); + } + logs.Resize(logs.Length - length); + g_db.Execute(transaction, _, SQL_TransactionFailed, length, DBPrio_Low); + } + return Plugin_Continue; +} +void SQL_TransactionFailed(Database db, any data, int numQueries, const char[] error, int failIndex, any[] queryData) { + LogError("Push transaction failed: %s at query %d/%d", error, failIndex, numQueries); +} + +public void Event_Connection(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && !IsFakeClient(client)) { + static char clientName[32]; + if(GetClientAuthId(client, AuthId_Steam2, clientName, sizeof(clientName))) { + if(name[7] == 'f') { + AddLog("JOIN", clientName, "", ""); + GetClientName(client, playerLastName[client], 32); + } else { + static char reason[64]; + event.GetString("reason", reason, sizeof(reason)); + Format(reason, sizeof(reason), " left: \"%s\"", reason); + AddLog("QUIT", clientName, "", reason); + } + } + } +} + +public void Event_PlayerInfo(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && !IsFakeClient(client) && GetUserAdmin(client) == INVALID_ADMIN_ID) { + char clientName[32]; + if(GetClientAuthId(client, AuthId_Steam2, clientName, sizeof(clientName))) { + AddLogCustom("INFO", clientName, "", "\"%s\" changed their name to \"%L\"", playerLastName[client], client); + GetClientName(client, playerLastName[client], 32); + } + } +} + +public Action OnLogAction(Handle source, Identity identity, int client, int target, const char[] message) { + // Ignore cvar changed msgs (from server.cfg) + if(client == 0 && !hLogCvarChanges.BoolValue && strcmp(message[31], "changed cvar") >= 0) return Plugin_Continue; + + static char clientName[32], targetName[32]; + if(client == 0) clientName = "Server"; + else if(client > 0) GetClientAuthId(client, AuthId_Steam2, clientName, sizeof(clientName)); + else clientName[0] = '\0'; + + if(target > 0 && !IsFakeClient(target)) GetClientAuthId(target, AuthId_Steam2, targetName, sizeof(targetName)); + else targetName[0] = '\0'; + + AddLog("ACTION", clientName, targetName, message); + return Plugin_Continue; +} + +public void OnClientSayCommand_Post(int client, const char[] command, const char[] sArgs) { + if(client > 0 && !IsFakeClient(client)) { + static char clientName[32]; + GetClientAuthId(client, AuthId_Steam2, clientName, sizeof(clientName)); + AddLog("CHAT", clientName, "", sArgs); + } +} + +public void Event_L4D2_Death(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + if(victim > 0 && GetClientTeam(victim) == 2) { //victim is a survivor + static char victimName[32], attackerName[32]; + + if(IsFakeClient(victim)) GetClientName(victim, victimName, sizeof(victimName)); + else GetClientAuthId(victim, AuthId_Steam2, victimName, sizeof(victimName)); + + if(attacker > 0 && attacker != victim) { + if(IsFakeClient(attacker)) GetClientName(attacker, attackerName, sizeof(attackerName)); + else GetClientAuthId(attacker, AuthId_Steam2, attackerName, sizeof(attackerName)); + + AddLogCustom("STATE", attackerName, victimName, "\"%L\" killed \"%L\"", attacker, victim); + } else { + AddLogCustom("STATE", "", victimName, "\"%L\" died", victim); + } + } +} +//Player was incapped by Jockey +//Player was incapped (by world/zombie, no msg) +public void Event_L4D2_Incapped(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + if(victim > 0 && GetClientTeam(victim) == 2) { + static char victimName[32], attackerName[32]; + if(IsFakeClient(victim)) GetClientName(victim, victimName, sizeof(victimName)); + else GetClientAuthId(victim, AuthId_Steam2, victimName, sizeof(victimName)); + + if(attacker > 0 && attacker != victim) { + if(IsFakeClient(attacker)) GetClientName(attacker, attackerName, sizeof(attackerName)); + else GetClientAuthId(attacker, AuthId_Steam2, attackerName, sizeof(attackerName)); + + AddLogCustom("STATE", attackerName, victimName, "\"%L\" incapped \"%L\"", attacker, victim); + } else { + AddLogCustom("STATE", "", victimName, "\"%L\" was incapped", victim); + } + } +} + +void AddLog(const char[] type, const char[] clientName, const char[] targetName, const char[] message) { + if(StrEqual(clientName, "Bot")) return; + Log log; + strcopy(log.name, sizeof(log.name), type); + strcopy(log.clientSteamID, sizeof(log.clientSteamID), clientName); + strcopy(log.targetSteamID, sizeof(log.targetSteamID), targetName); + strcopy(log.message, sizeof(log.message), message); + log.timestamp = GetTime(); + logs.PushArray(log); +} + +void AddLogCustom(const char[] type, const char[] clientName, const char[] targetName, const char[] format, any ...) { + static char message[254]; + if(StrEqual(clientName, "Bot")) return; + + VFormat(message, sizeof(message), format, 5); + AddLog(type, clientName, targetName, message); +} + +public any Native_AddLog(Handle plugin, int numParams) { + char type[32], clientName[32], targetName[32], message[256]; + if(GetNativeString(1, type, sizeof(type)) != SP_ERROR_NONE) return false; + if(GetNativeString(2, clientName, sizeof(clientName)) != SP_ERROR_NONE) return false; + if(GetNativeString(3, targetName, sizeof(targetName)) != SP_ERROR_NONE) return false; + if(GetNativeString(4, message, sizeof(message)) != SP_ERROR_NONE) return false; + AddLog(type, clientName, targetName, message); + return true; +} diff --git a/scripting/adminpanel.sp b/scripting/adminpanel.sp new file mode 100644 index 0000000..f42e3d9 --- /dev/null +++ b/scripting/adminpanel.sp @@ -0,0 +1,423 @@ +#pragma semicolon 1 + +#define DEBUG + +// Update intervals (only sends when > 0 players) +// The update interval when there are active viewers +#define UPDATE_INTERVAL 5.0 +// The update interval when there are no viewers on. +// We still need to poll to know how many viewers are watching +#define UPDATE_INTERVAL_SLOW 20.0 + +#include +#include +#include +#include +#include +#include + +#pragma newdecls required + +public Plugin myinfo = +{ + name = "Admin Panel", + author = "Jackz", + description = "Plugin to integrate with admin panel", + version = "1.0.0", + url = "https://github.com/jackzmc/l4d2-admin-dash" +}; + +ConVar cvar_debug; +ConVar cvar_postAddress; char postAddress[128]; +ConVar cvar_authKey; char authKey[512]; +ConVar cvar_gamemode; char gamemode[32]; + +char currentMap[64]; +int numberOfPlayers = 0; +int lastSuccessTime; +int campaignStartTime; +int lastErrorCode; +int uptime; +bool fastUpdateMode = false; + +Handle updateTimer = null; + +char steamidCache[MAXPLAYERS+1][32]; +char nameCache[MAXPLAYERS+1][MAX_NAME_LENGTH]; +int g_icBeingHealed[MAXPLAYERS+1]; +int playerJoinTime[MAXPLAYERS+1]; + + +public void OnPluginStart() +{ + uptime = GetTime(); + cvar_debug = CreateConVar("sm_adminpanel_debug", "0", "Turn on debug mode", FCVAR_DONTRECORD, true, 0.0, true, 1.0); + + cvar_postAddress = CreateConVar("sm_adminpanel_url", "", "The base address to post updates to", FCVAR_NONE); + cvar_postAddress.AddChangeHook(OnCvarChanged); + cvar_postAddress.GetString(postAddress, sizeof(postAddress)); + cvar_authKey = CreateConVar("sm_adminpanel_key", "", "The authentication key", FCVAR_NONE); + cvar_authKey.AddChangeHook(OnCvarChanged); + cvar_authKey.GetString(authKey, sizeof(authKey)); + + cvar_gamemode = FindConVar("mp_gamemode"); + cvar_gamemode.AddChangeHook(OnCvarChanged); + cvar_gamemode.GetString(gamemode, sizeof(gamemode)); + + HookEvent("game_init", Event_GameStart); + HookEvent("heal_success", Event_HealStop); + HookEvent("heal_interrupted", Event_HealStop); + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + OnClientPutInServer(i); + } + } + + TryStartTimer(true); + + AutoExecConfig(true, "adminpanel"); + + RegAdminCmd("sm_panel_status", Command_PanelStatus, ADMFLAG_GENERIC); + +} + +#define DATE_FORMAT "%F at %I:%M %p" +Action Command_PanelStatus(int client, int args) { + ReplyToCommand(client, "Active: %b", updateTimer != null); + ReplyToCommand(client, "#Players: %d", numberOfPlayers); + ReplyToCommand(client, "Update Interval: %0f s", fastUpdateMode ? UPDATE_INTERVAL : UPDATE_INTERVAL_SLOW); + char buffer[32]; + ReplyToCommand(client, "Last Error Code: %d", lastErrorCode); + if(lastSuccessTime > 0) + FormatTime(buffer, sizeof(buffer), DATE_FORMAT, lastSuccessTime); + else + Format(buffer, sizeof(buffer), "(none)"); + ReplyToCommand(client, "Last Success: %s", buffer); + return Plugin_Handled; +} + +void TryStartTimer(bool fast = true) { + if(numberOfPlayers > 0 && updateTimer == null && postAddress[0] != '\0' && authKey[0] != 0) { + fastUpdateMode = fast; + float interval = fast ? UPDATE_INTERVAL : UPDATE_INTERVAL_SLOW; + updateTimer = CreateTimer(interval, Timer_PostStatus, _, TIMER_REPEAT); + PrintToServer("[AdminPanel] Updating every %.1f seconds", interval); + } +} + + +void Event_GameStart(Event event, const char[] name, bool dontBroadcast) { + campaignStartTime = GetTime(); +} + +void Event_HealStart(Event event, const char[] name, bool dontBroadcast) { + int healing = GetClientOfUserId(event.GetInt("subject")); + g_icBeingHealed[healing] = true; +} +void Event_HealStop(Event event, const char[] name, bool dontBroadcast) { + int healing = GetClientOfUserId(event.GetInt("subject")); + g_icBeingHealed[healing] = false; +} + +void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + playerJoinTime[client] = GetTime(); + RecalculatePlayerCount(); +} + +void RecalculatePlayerCount() { + int players = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i)) { + players++; + } + } + numberOfPlayers = players; +} + +public void OnMapStart() { + GetCurrentMap(currentMap, sizeof(currentMap)); + numberOfPlayers = 0; +} + +// Player counts +public void OnClientPutInServer(int client) { + GetClientName(client, nameCache[client], MAX_NAME_LENGTH); + if(!IsFakeClient(client)) { + GetClientAuthId(client, AuthId_SteamID64, steamidCache[client], 32); + numberOfPlayers++; + TryStartTimer(true); + } else { + strcopy(steamidCache[client], 32, "BOT"); + } +} + +public void OnClientDisconnect(int client) { + steamidCache[client][0] = '\0'; + nameCache[client][0] = '\0'; + if(!IsFakeClient(client)) { + numberOfPlayers--; + // Incase somehow we lost track + if(numberOfPlayers < 0) { + numberOfPlayers = 0; + } + if(numberOfPlayers == 0 && updateTimer != null) { + delete updateTimer; + } + } +} + +// Cvar updates +void OnCvarChanged(ConVar convar, const char[] oldValue, const char[] newValue) { + if(cvar_postAddress == convar) { + strcopy(postAddress, sizeof(postAddress), newValue); + PrintToServer("[AdminPanel] Update Url has updated"); + } else if(cvar_authKey == convar) { + strcopy(authKey, sizeof(authKey), newValue); + PrintToServer("[AdminPanel] Auth key has been updated"); + } else if(cvar_gamemode == convar) { + strcopy(gamemode, sizeof(gamemode), newValue); + } + TryStartTimer(true); +} + +bool isSubmitting; +Action Timer_PostStatus(Handle h) { + if(isSubmitting) return Plugin_Continue; + isSubmitting = true; + // TODO: optimize only if someone is requesting live + HTTPRequest req = new HTTPRequest(postAddress); + JSONObject obj = GetObject(); + req.SetHeader("x-authtoken", authKey); + // req.AppendFormParam("playerCount", "%d", numberOfPlayers); + // req.AppendFormParam("map", currentMap); + if(cvar_debug.BoolValue) PrintToServer("[AdminPanel] Submitting"); + req.Post(obj, Callback_PostStatus); + delete obj; + // req.PostForm(Callback_PostStatus); + return Plugin_Continue; +} + +void Callback_PostStatus(HTTPResponse response, any value, const char[] error) { + isSubmitting = false; + if(response.Status == HTTPStatus_NoContent || response.Status == HTTPStatus_OK) { + lastErrorCode = 0; + lastSuccessTime = GetTime(); + if(cvar_debug.BoolValue) + PrintToServer("[AdminPanel] Response: OK/204"); + // We have subscribers, kill timer and recreate it in fast mode (if not already): + if(!fastUpdateMode) { + PrintToServer("[AdminPanel] Switching to fast update interval for active viewers."); + if(updateTimer != null) + delete updateTimer; + TryStartTimer(true); + } + + } else if(response.Status == HTTPStatus_Gone) { + lastErrorCode = 0; + // We have no subscribers, kill timer and recreate it in slow mode (if not already): + if(fastUpdateMode) { + PrintToServer("[AdminPanel] Switching to slow update interval, no viewers"); + if(updateTimer != null) + delete updateTimer; + TryStartTimer(false); + } + } else { + lastErrorCode = view_as(response.Status); + lastSuccessTime = 0; + // TODO: backoff + PrintToServer("[AdminPanel] Getting response: %d", response.Status); + if(cvar_debug.BoolValue) { + char buffer[64]; + JSONObject json = view_as(response.Data); + if(false && json.GetString("error", buffer, sizeof(buffer))) { + PrintToServer("[AdminPanel] Got %d response from server: \"%s\"", view_as(response.Status), buffer); + json.GetString("message", buffer, sizeof(buffer)); + PrintToServer("[AdminPanel] Error message: \"%s\"", buffer); + } else { + PrintToServer("[AdminPanel] Got %d response from server: \n%s", view_as(response.Status), error); + } + } + if(response.Status == HTTPStatus_Unauthorized || response.Status == HTTPStatus_Forbidden) { + PrintToServer("[AdminPanel] API Key seems to be invalid, killing timer."); + if(updateTimer != null) + delete updateTimer; + } + } +} + +JSONObject GetObject() { + JSONObject obj = new JSONObject(); + obj.SetInt("playerCount", numberOfPlayers); + obj.SetString("map", currentMap); + obj.SetString("gamemode", gamemode); + obj.SetInt("startTime", uptime); + obj.SetInt("commonsCount", L4D_GetCommonsCount()); + obj.SetFloat("fps", 1.0 / GetGameFrameTime()); + AddFinaleInfo(obj); + JSONArray players = GetPlayers(); + obj.Set("players", players); + delete players; + obj.SetFloat("refreshInterval", UPDATE_INTERVAL); + obj.SetInt("lastUpdateTime", GetTime()); + obj.SetInt("campaignStartTime", campaignStartTime); + return obj; +} + +void AddFinaleInfo(JSONObject parentObj) { + if(L4D_IsMissionFinalMap()) { + JSONObject obj = new JSONObject(); + obj.SetBool("escapeLeaving", L4D_IsFinaleEscapeInProgress()); + obj.SetInt("finaleStage", L4D2_GetCurrentFinaleStage()); + parentObj.Set("finaleInfo", obj); + delete obj; + } +} + +JSONArray GetPlayers() { + JSONArray players = new JSONArray(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + int team = GetClientTeam(i); + if( team == 2 || team == 3) { + JSONObject player = GetPlayer(i); + players.Push(player); + delete player; + } + } + } + return players; +} + + +enum { + Action_BeingHealed = -1, + Action_None = 0, // No use action active + Action_Healing = 1, // Includes healing yourself or a teammate. + Action_AmmoPack = 2, // When deploying the ammo pack that was never added into the game + Action_Defibing = 4, // When defib'ing a dead body. + Action_GettingDefibed = 5, // When comming back to life from a dead body. + Action_DeployIncendiary = 6, // When deploying Incendiary ammo + Action_DeployExplosive = 7, // When deploying Explosive ammo + Action_PouringGas = 8, // Pouring gas into a generator + Action_Cola = 9, // For Dead Center map 2 cola event, when handing over the cola to whitalker. + Action_Button = 10, // Such as buttons, timed buttons, generators, etc. + Action_UsePointScript = 11 // When using a "point_script_use_target" entity +} + +int GetAction(int client) { + if(g_icBeingHealed[client]) return Action_BeingHealed; + return view_as(L4D2_GetPlayerUseAction(client)); +} + +enum { + Move_UnderAttack = -3, + Move_Hanging = -2, + Move_Incapped = -1, + Move_Idle = 0, + Move_Walk = 1, + Move_Run = 2, + Move_Crouched = 3, + Move_Ladder = 4 +} + +stock float GetPlayerSpeed(int client) { + int iVelocity = FindSendPropInfo("CTerrorPlayer", "m_vecVelocity[0]"); + float velocity[3]; + GetEntDataVector(client, iVelocity, velocity); + return GetVectorLength(velocity, false); +} + +int GetPlayerMovement(int client) { + MoveType moveType = GetEntityMoveType(client); + if(moveType == MOVETYPE_LADDER) return Move_Ladder; + else if(GetEntProp(client, Prop_Send, "m_bDucked", 1)) return Move_Crouched; + else if(GetEntProp(client, Prop_Send, "m_isIncapacitated", 1)) return Move_Incapped; + else if(GetEntProp(client, Prop_Send, "m_isHangingFromLedge", 1)) return Move_Hanging; + else if(L4D_GetPinnedSurvivor(client)) return Move_UnderAttack; // TODO: optimize for events + float velocity = GetPlayerSpeed(client); + if(velocity > 85.0) return Move_Run; + else if(velocity > 1.0) return Move_Walk; + return Move_Idle; +} + +// TODO: pursued by witch +enum { + pState_BlackAndWhite = 1, + pState_InSaferoom = 2, + pState_IsCalm = 4, + pState_IsBoomed = 8 +} + +stock bool IsPlayerBoomed(int client) { + return (GetEntPropFloat(client, Prop_Send, "m_vomitStart") + 20.1) > GetGameTime(); +} + +int GetPlayerStates(int client) { + int state = 0; + if(L4D_IsInLastCheckpoint(client) || L4D_IsInFirstCheckpoint(client)) + state |= pState_InSaferoom; + if(GetEntProp(client, Prop_Send, "m_bIsOnThirdStrike", 1)) state |= pState_BlackAndWhite; + if(GetEntProp(client, Prop_Send, "m_isCalm")) state |= pState_IsCalm; + if(IsPlayerBoomed(client)) state |= pState_IsBoomed; + return state; +} + +JSONObject GetPlayer(int client) { + int team = GetClientTeam(client); + JSONObject player = new JSONObject(); + player.SetString("steamid", steamidCache[client]); + player.SetInt("userId", GetClientUserId(client)); + player.SetString("name", nameCache[client]); + player.SetInt("team", team); + player.SetBool("isAlive", IsPlayerAlive(client)); + player.SetInt("joinTime", playerJoinTime[client]); + player.SetInt("permHealth", GetEntProp(client, Prop_Send, "m_iHealth")); + if(team == 2) { + // Include idle players (player here is their idle bot) + if(IsFakeClient(client)) { + int idlePlayer = L4D_GetIdlePlayerOfBot(client); + if(idlePlayer > 0) { + player.SetString("idlePlayerId", steamidCache[idlePlayer]); + if(IsClientInGame(idlePlayer)) { + JSONObject idlePlayerObj = GetPlayer(idlePlayer); + player.Set("idlePlayer", idlePlayerObj); + delete idlePlayerObj; + } + } + } + player.SetInt("action", GetAction(client)); + player.SetInt("flowProgress", L4D2_GetVersusCompletionPlayer(client)); + player.SetFloat("flow", L4D2Direct_GetFlowDistance(client)); + player.SetBool("isPinned", L4D2_GetInfectedAttacker(client) > 0); + player.SetInt("tempHealth", L4D_GetPlayerTempHealth(client)); + player.SetInt("states", GetPlayerStates(client)); + player.SetInt("move", GetPlayerMovement(client)); + player.SetInt("survivor", GetEntProp(client, Prop_Send, "m_survivorCharacter")); + JSONArray weapons = GetPlayerWeapons(client); + player.Set("weapons", weapons); + delete weapons; + } else if(team == 3) { + player.SetInt("class", L4D2_GetPlayerZombieClass(client)); + player.SetInt("maxHealth", GetEntProp(client, Prop_Send, "m_iMaxHealth")); + int victim = L4D2_GetSurvivorVictim(client); + if(victim > 0) + player.SetString("pinnedSurvivorId", steamidCache[victim]); + } + return player; +} + +JSONArray GetPlayerWeapons(int client) { + JSONArray weapons = new JSONArray(); + static char buffer[64]; + for(int slot = 0; slot < 6; slot++) { + if(GetClientWeaponNameSmart(client, slot, buffer, sizeof(buffer))) { + weapons.PushString(buffer); + } else { + weapons.PushNull(); + } + } + return weapons; +} \ No newline at end of file diff --git a/scripting/basechat.sp b/scripting/basechat.sp new file mode 100644 index 0000000..d00c1db --- /dev/null +++ b/scripting/basechat.sp @@ -0,0 +1,441 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * SourceMod Basic Chat Plugin + * Implements basic communication commands. + * + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + * + * Version: $Id$ + */ + +#pragma semicolon 1 + +#include + +#pragma newdecls required + +public Plugin myinfo = +{ + name = "Basic Chat+", + author = "AlliedModders LLC", + description = "Basic Communication Commands", + version = SOURCEMOD_VERSION, + url = "http://www.sourcemod.net/" +}; + +#define CHAT_SYMBOL '@' + +char g_ColorNames[13][10] = {"White", "Red", "Green", "Blue", "Yellow", "Purple", "Cyan", "Orange", "Pink", "Olive", "Lime", "Violet", "Lightblue"}; +int g_Colors[13][3] = {{255,255,255},{255,0,0},{0,255,0},{0,0,255},{255,255,0},{255,0,255},{0,255,255},{255,128,0},{255,0,128},{128,255,0},{0,255,128},{128,0,255},{0,128,255}}; + +ConVar g_Cvar_Chatmode; + +EngineVersion g_GameEngine = Engine_Unknown; + +public void OnPluginStart() +{ + LoadTranslations("common.phrases"); + + g_GameEngine = GetEngineVersion(); + + g_Cvar_Chatmode = CreateConVar("sm_chat_mode", "1", "Allows player's to send messages to admin chat.", 0, true, 0.0, true, 1.0); + + RegAdminCmd("sm_say", Command_SmSay, ADMFLAG_CHAT, "sm_say - sends message to all players"); + RegAdminCmd("sm_csay", Command_SmCsay, ADMFLAG_CHAT, "sm_csay - sends centered message to all players"); + + /* HintText does not work on Dark Messiah */ + if (g_GameEngine != Engine_DarkMessiah) + { + RegAdminCmd("sm_hsay", Command_SmHsay, ADMFLAG_CHAT, "sm_hsay - sends hint message to all players"); + } + + RegAdminCmd("sm_tsay", Command_SmTsay, ADMFLAG_CHAT, "sm_tsay [color] - sends top-left message to all players"); + RegAdminCmd("sm_chat", Command_SmChat, ADMFLAG_CHAT, "sm_chat - sends message to admins"); + RegAdminCmd("sm_psay", Command_SmPsay, ADMFLAG_CHAT, "sm_psay - sends private message"); + RegAdminCmd("sm_msay", Command_SmMsay, ADMFLAG_CHAT, "sm_msay - sends message as a menu panel"); +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) +{ + int startidx; + if (sArgs[startidx] != CHAT_SYMBOL) + return Plugin_Continue; + + startidx++; + + if (strcmp(command, "say", false) == 0) + { + if (sArgs[startidx] != CHAT_SYMBOL) // sm_say alias + { + if (!CheckCommandAccess(client, "sm_chat", ADMFLAG_CHAT)) + { + return Plugin_Continue; + } + + SendChatToAdmins(client, sArgs[startidx]); + LogAction(client, -1, "\"%L\" triggered sm_say (text %s)", client, sArgs[startidx]); + + return Plugin_Stop; + } + + startidx++; + + if (sArgs[startidx] != CHAT_SYMBOL) // sm_psay alias + { + if (!CheckCommandAccess(client, "sm_psay", ADMFLAG_CHAT)) + { + return Plugin_Continue; + } + + char arg[64]; + + int len = BreakString(sArgs[startidx], arg, sizeof(arg)); + int target = FindTarget(client, arg, true, false); + + if (target == -1 || len == -1) { + PrintToChat(client, "Cannot send a private msg: Invalid user specified."); + } else { + SendPrivateChat(client, target, sArgs[startidx+len]); + } + + + return Plugin_Stop; + } + + startidx++; + + // sm_csay alias + if (!CheckCommandAccess(client, "sm_csay", ADMFLAG_CHAT)) + { + return Plugin_Continue; + } + + DisplayCenterTextToAll(client, sArgs[startidx]); + LogAction(client, -1, "\"%L\" triggered sm_csay (text %s)", client, sArgs[startidx]); + + return Plugin_Stop; + } + else if (strcmp(command, "say_team", false) == 0 || strcmp(command, "say_squad", false) == 0) + { + if (!CheckCommandAccess(client, "sm_chat", ADMFLAG_CHAT) && !g_Cvar_Chatmode.BoolValue) + { + return Plugin_Continue; + } + + SendChatToAdmins(client, sArgs[startidx]); + LogAction(client, -1, "\"%L\" triggered sm_chat (text %s)", client, sArgs[startidx]); + + return Plugin_Stop; + } + + return Plugin_Continue; +} + +public Action Command_SmSay(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_say "); + return Plugin_Handled; + } + + char text[192]; + GetCmdArgString(text, sizeof(text)); + + SendChatToAll(client, text); + LogAction(client, -1, "\"%L\" triggered sm_say (text %s)", client, text); + + return Plugin_Handled; +} + +public Action Command_SmCsay(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_csay "); + return Plugin_Handled; + } + + char text[192]; + GetCmdArgString(text, sizeof(text)); + + DisplayCenterTextToAll(client, text); + + LogAction(client, -1, "\"%L\" triggered sm_csay (text %s)", client, text); + + return Plugin_Handled; +} + +public Action Command_SmHsay(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_hsay "); + return Plugin_Handled; + } + + char text[192]; + GetCmdArgString(text, sizeof(text)); + + char nameBuf[MAX_NAME_LENGTH]; + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i) || IsFakeClient(i)) + { + continue; + } + FormatActivitySource(client, i, nameBuf, sizeof(nameBuf)); + PrintHintText(i, "%s: %s", nameBuf, text); + } + + LogAction(client, -1, "\"%L\" triggered sm_hsay (text %s)", client, text); + + return Plugin_Handled; +} + +public Action Command_SmTsay(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_tsay "); + return Plugin_Handled; + } + + char text[192], colorStr[16]; + GetCmdArgString(text, sizeof(text)); + + int len = BreakString(text, colorStr, 16); + + int color = FindColor(colorStr); + char nameBuf[MAX_NAME_LENGTH]; + + if (color == -1) + { + color = 0; + len = 0; + } + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i) || IsFakeClient(i)) + { + continue; + } + FormatActivitySource(client, i, nameBuf, sizeof(nameBuf)); + SendDialogToOne(i, color, "%s: %s", nameBuf, text[len]); + } + + LogAction(client, -1, "\"%L\" triggered sm_tsay (text %s)", client, text); + + return Plugin_Handled; +} + +public Action Command_SmChat(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_chat "); + return Plugin_Handled; + } + + char text[192]; + GetCmdArgString(text, sizeof(text)); + + SendChatToAdmins(client, text); + LogAction(client, -1, "\"%L\" triggered sm_chat (text %s)", client, text); + + return Plugin_Handled; +} + +public Action Command_SmPsay(int client, int args) +{ + if (args < 2) + { + ReplyToCommand(client, "[SM] Usage: sm_psay "); + return Plugin_Handled; + } + + char text[192], arg[64]; + GetCmdArgString(text, sizeof(text)); + + int len = BreakString(text, arg, sizeof(arg)); + + int target = FindTarget(client, arg, true, false); + + if (target == -1) + return Plugin_Handled; + + SendPrivateChat(client, target, text[len]); + + return Plugin_Handled; +} + +public Action Command_SmMsay(int client, int args) +{ + if (args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_msay "); + return Plugin_Handled; + } + + char text[192]; + GetCmdArgString(text, sizeof(text)); + + SendPanelToAll(client, text); + + LogAction(client, -1, "\"%L\" triggered sm_msay (text %s)", client, text); + + return Plugin_Handled; +} + +int FindColor(const char[] color) +{ + for (int i = 0; i < sizeof(g_ColorNames); i++) + { + if (strcmp(color, g_ColorNames[i], false) == 0) + return i; + } + + return -1; +} + +void SendChatToAll(int client, const char[] message) +{ + char nameBuf[MAX_NAME_LENGTH]; + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i) || IsFakeClient(i)) + { + continue; + } + FormatActivitySource(client, i, nameBuf, sizeof(nameBuf)); + + if (g_GameEngine == Engine_CSGO) + PrintToChat(i, " \x01\x0B\x04%t: \x01%s", "Say all", nameBuf, message); + else + PrintToChat(i, "\x04%t: \x01%s", "Say all", nameBuf, message); + } +} + +void DisplayCenterTextToAll(int client, const char[] message) +{ + char nameBuf[MAX_NAME_LENGTH]; + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i) || IsFakeClient(i)) + { + continue; + } + FormatActivitySource(client, i, nameBuf, sizeof(nameBuf)); + PrintCenterText(i, "%s: %s", nameBuf, message); + } +} + +void SendChatToAdmins(int from, const char[] message) +{ + int fromAdmin = CheckCommandAccess(from, "sm_chat", ADMFLAG_CHAT); + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && (from == i || CheckCommandAccess(i, "sm_chat", ADMFLAG_CHAT))) + { + if (g_GameEngine == Engine_CSGO) + PrintToChat(i, " \x01\x0B\x04%t: \x01%s", fromAdmin ? "Chat admins" : "Chat to admins", from, message); + else + PrintToChat(i, "\x04%t: \x01%s", fromAdmin ? "Chat admins" : "Chat to admins", from, message); + } + } +} + +void SendDialogToOne(int client, int color, const char[] text, any ...) +{ + char message[100]; + VFormat(message, sizeof(message), text, 4); + + KeyValues kv = new KeyValues("Stuff", "title", message); + kv.SetColor("color", g_Colors[color][0], g_Colors[color][1], g_Colors[color][2], 255); + kv.SetNum("level", 1); + kv.SetNum("time", 10); + + CreateDialog(client, kv, DialogType_Msg); + + delete kv; +} + +void SendPrivateChat(int client, int target, const char[] message) +{ + if (!client) + { + PrintToServer("(Private to %N) %N: %s", target, client, message); + } + else if (target != client) + { + if (g_GameEngine == Engine_CSGO) + PrintToChat(client, " \x01\x0B\x04%t: \x01%s", "Private say to", target, client, message); + else + PrintToChat(client, "\x04%t: \x01%s", "Private say to", target, client, message); + } + + if (g_GameEngine == Engine_CSGO) + PrintToChat(target, " \x01\x0B\x04%t: \x01%s", "Private say to", target, client, message); + else + PrintToChat(target, "\x04%t: \x01%s", "Private say to", target, client, message); + LogAction(client, target, "\"%L\" triggered sm_psay to \"%L\" (text %s)", client, target, message); +} + +void SendPanelToAll(int from, char[] message) +{ + char title[100]; + Format(title, 64, "%N:", from); + + ReplaceString(message, 192, "\\n", "\n"); + + Panel mSayPanel = new Panel(); + mSayPanel.SetTitle(title); + mSayPanel.DrawItem("", ITEMDRAW_SPACER); + mSayPanel.DrawText(message); + mSayPanel.DrawItem("", ITEMDRAW_SPACER); + mSayPanel.CurrentKey = GetMaxPageItems(mSayPanel.Style); + mSayPanel.DrawItem("Exit", ITEMDRAW_CONTROL); + + for(int i = 1; i <= MaxClients; i++) + { + if(IsClientInGame(i) && !IsFakeClient(i)) + { + mSayPanel.Send(i, Handler_DoNothing, 10); + } + } + + delete mSayPanel; +} + +public int Handler_DoNothing(Menu menu, MenuAction action, int param1, int param2) +{ + return 0; + /* Do nothing */ +} diff --git a/scripting/csgo-knifehp.sp b/scripting/csgo-knifehp.sp new file mode 100644 index 0000000..7f2ad7c --- /dev/null +++ b/scripting/csgo-knifehp.sp @@ -0,0 +1,68 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_NAME "CSGO Knife Regen" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.00" +#define PLUGIN_DESCRIPTION "" + +#include +#include +#include +//#include + +EngineVersion g_Game; + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = "" +}; + +ConVar g_bKnifeHPEnabled, g_iKnifeHPMax, g_iKnifeHPRegain; + +public OnPluginStart() +{ + g_Game = GetEngineVersion(); + if (g_Game != Engine_CSGO && g_Game != Engine_CSS) + { + SetFailState("This plugin is for CSGO/CSS only."); + } + + g_bKnifeHPEnabled = CreateConVar("knifehp_enable", "1", "Enable regaining health on knife kill", FCVAR_NONE, true, 0.0, true, 1.0); + g_iKnifeHPMax = CreateConVar("knifehp_max_health", "100", "Maximum health to set an attacker to", FCVAR_NONE, true, 0.0); + g_iKnifeHPRegain = CreateConVar("knifehp_amount", "100", "Amount of health to give attacker", FCVAR_NONE, true, 0.0); + HookEvent("player_death", Event_PlayerDeath); + + AutoExecConfig(true, "csgo_knifehp"); +} + +public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) +{ + if (g_bKnifeHPEnabled.BoolValue) { + char weapon_name[64]; + event.GetString("weapon", weapon_name, sizeof(weapon_name)); + if (StrContains(weapon_name, "knife", false) > -1) { + int attacker = event.GetInt("attacker"); + int client = GetClientOfUserId(attacker); + + //get the new health value (current client hp + the regen amount) + int new_health = GetClientHealth(client) + g_iKnifeHPRegain.IntValue; + //50 + 20 <= max + if (IsClientInGame(client) && IsPlayerAlive(client) && !IsFakeClient(client)) { + if(new_health <= g_iKnifeHPMax.IntValue) { //if the new health is less than max, set it to it + SetEntityHealth(client, new_health); + }else{ //if > max, set it to max + SetEntityHealth(client, g_iKnifeHPMax.IntValue); + } + } + + } + + + } +} \ No newline at end of file diff --git a/scripting/csgo-misc.sp b/scripting/csgo-misc.sp new file mode 100644 index 0000000..f039622 --- /dev/null +++ b/scripting/csgo-misc.sp @@ -0,0 +1,60 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_AUTHOR "" +#define PLUGIN_VERSION "0.00" + +#include +#include +#include +//#include + +#pragma newdecls required + +public Plugin myinfo = +{ + name = "", + author = PLUGIN_AUTHOR, + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_CSGO && g_Game != Engine_CSS) + { + SetFailState("This plugin is for CSGO/CSS only."); + } + RegConsoleCmd("sm_first", Command_FirstPov, "Go back to first person"); + RegConsoleCmd("sm_third", Command_ThirdPov, "Go to third person"); +} +public Action Command_FirstPov(int client, int args) { + if(client == 0) { + ReplyToCommand(client, "This command is for clients only"); + return Plugin_Handled; + } + CheatCommand(client, "firstperson", "", ""); + return Plugin_Handled; +} +public Action Command_ThirdPov(int client, int args) { + if(client == 0) { + ReplyToCommand(client, "This command is for clients only"); + return Plugin_Handled; + } + CheatCommand(client, "thirdperson", "", ""); + return Plugin_Handled; +} + +stock void CheatCommand(int client, char[] command, char[] argument1, char[] argument2) +{ + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s %s", command, argument1, argument2); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} \ No newline at end of file diff --git a/scripting/disable_cameras.sp b/scripting/disable_cameras.sp new file mode 100644 index 0000000..b7bc167 --- /dev/null +++ b/scripting/disable_cameras.sp @@ -0,0 +1,84 @@ +#include +#include +#include + +// Fixed issues: +// - Server crash when kicking a bot who have been an active target of camera (point_viewcontrol_survivor) +// - Multiple visual spectator bugs after team swap in finale + +public void Event_round_start_pre_entity(Event event, const char[] name, bool dontBroadcast) +{ + static char classes[][] = { + "point_viewcontrol", + "point_viewcontrol_survivor", + "point_viewcontrol_multiplayer", + }; + + for (int i = 0; i < sizeof(classes); i++) { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, classes[i])) != INVALID_ENT_REFERENCE) { + // Invoke a "Disable" input on camera entities to free all players + // Doing so on round_start_pre_entity should help to not let map logic kick in too early + AcceptEntityInput(entity, "Disable"); + } + } +} + +public void OnClientDisconnect(int client) +{ + if (!IsClientInGame(client)) { + return; + } + + int viewEntity = GetEntPropEnt(client, Prop_Send, "m_hViewEntity"); + if (!IsValidEdict(viewEntity)) { + return; + } + + char cls[64]; + GetEdictClassname(viewEntity, cls, sizeof(cls)); + if (strncmp(cls, "point_viewcontrol", 17) != 0) { + return; + } + + // Matches CSurvivorCamera, CTriggerCamera + if (strcmp(cls[17], "_survivor") == 0 || cls[17] == '\0') { + // Disable entity to prevent CMoveableCamera::FollowTarget to cause a crash + // m_hTargetEnt EHANDLE is not checked for existence and can be NULL + // CBaseEntity::GetAbsAngles being called on causing a crash + AcceptEntityInput(viewEntity, "Disable"); + } + + // Matches CTriggerCameraMultiplayer + if (strcmp(cls[17], "_multiplayer") == 0) { + AcceptEntityInput(viewEntity, "RemovePlayer", client); + } +} + +public void OnPluginStart() +{ + HookEvent("round_start_pre_entity", Event_round_start_pre_entity, EventHookMode_PostNoCopy); +} + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + switch (GetEngineVersion()) { + case Engine_Left4Dead2, Engine_Left4Dead: + { + return APLRes_Success; + } + } + + strcopy(error, err_max, "Plugin only supports Left 4 Dead and Left 4 Dead 2."); + + return APLRes_SilentFailure; +} + +public Plugin myinfo = +{ + name = "[L4D/2] Unlink Camera Entities", + author = "shqke", + description = "Frees cached players from camera entity", + version = "1.1", + url = "https://github.com/shqke/sp_public" +}; diff --git a/scripting/globalbans.sp b/scripting/globalbans.sp new file mode 100644 index 0000000..dd1cb8e --- /dev/null +++ b/scripting/globalbans.sp @@ -0,0 +1,323 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG 0 +#define PLUGIN_VERSION "1.0" +#define DB_NAME "globalbans" + +#define BANFLAG_NONE 0 +#define BANFLAG_IPBANNED 1 +#define BANFLAG_SUSPENDED 2 + +#include +#include + +public Plugin myinfo = +{ + name = "Global Bans", + author = "jackzmc", + description = "Manages bans via MySQL", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +static Database g_db; +static ConVar hKickType; +static StringMap pendingInsertQueries; + +static int iPendingCounter; + + +public void OnPluginStart() { + if(!SQL_CheckConfig(DB_NAME)) { + SetFailState("No database entry for " ... DB_NAME ... "; no database to connect to."); + } + if(!ConnectDB()) { + SetFailState("Failed to connect to database."); + } + + pendingInsertQueries = new StringMap(); + + hKickType = CreateConVar("sm_globalbans_kick_type", "1", "0 = Do not kick, just notify\n1 = Kick if banned\n 2 = Kick if cannot reach database", FCVAR_NONE, true, 0.0, true, 2.0); + +} + +/////////////////////////////////////////////////////////////////////////////// +// DB Connections +/////////////////////////////////////////////////////////////////////////////// + +bool ConnectDB() { + static char error[255]; + g_db = SQL_Connect(DB_NAME, true, error, sizeof(error)); + if (g_db == null) { + LogError("Database error %s", error); + delete g_db; + return false; + } else { + PrintToServer("Connected to sm database " ... DB_NAME); + SQL_LockDatabase(g_db); + SQL_FastQuery(g_db, "SET NAMES \"UTF8mb4\""); + SQL_UnlockDatabase(g_db); + g_db.SetCharset("utf8mb4"); + return true; + } +} + +/////////////////////////////////////////////////////////////////////////////// +// EVENTS +/////////////////////////////////////////////////////////////////////////////// + +public void OnClientAuthorized(int client, const char[] auth) { + if(!StrEqual(auth, "BOT", true)) { + static char query[256], ip[32]; + GetClientIP(client, ip, sizeof(ip)); + g_db.Format(query, sizeof(query), "SELECT `reason`, `steamid`, `expired`, `public_message`, `flags`, `id` FROM `bans` WHERE `expired` = 0 AND `steamid` LIKE 'STEAM_%%:%%:%s' OR ip = '%s'", auth[10], ip); + g_db.Query(DB_OnConnectCheck, query, GetClientUserId(client), DBPrio_High); + } +} + +public Action OnBanIdentity(const char[] identity, int time, int flags, const char[] reason, const char[] command, any source) { + if(flags == BANFLAG_AUTHID) { + char executor[32]; + if(source > 0 && source <= MaxClients) { + GetClientAuthId(source, AuthId_Steam2, executor, sizeof(executor)); + }else{ + executor = "CONSOLE"; + } + + char query[512]; + + + // Setup expiration date + char expiresDate[64]; + if(time > 0) { + Format(expiresDate, sizeof(expiresDate), "%d", GetTime() + (time * 60000)); + }else{ + Format(expiresDate, sizeof(expiresDate), "NULL"); + } + + g_db.Format(query, sizeof(query), "INSERT INTO bans" + ..."(steamid, reason, expires, executor, flags, timestamp)" + ..."VALUES ('%s', '%s', %s, '%s', %d, UNIX_TIMESTAMP())", + identity, + reason, + expiresDate, + executor, + BANFLAG_NONE + ); + + static char strKey[8]; + int key = ++iPendingCounter; + IntToString(key, strKey, sizeof(strKey)); + pendingInsertQueries.SetString(strKey, query); + + g_db.Format(query, sizeof(query), "SELECT `flags` FROM `bans` WHERE `expired` = 0 AND `steamid` LIKE 'STEAM_%%:%%:%s' OR ip = '%s'", identity[10], identity); + g_db.Query(DB_OnBanPreCheck, query, key); + PrintToServer("Adding %s to OnBanClient queue. Key: %d", identity, key); + + }else if(flags == BANFLAG_IP) { + LogMessage("Cannot save IP without steamid: %s [Source: %s]", identity, source); + } + return Plugin_Continue; +} + +public Action OnBanClient(int client, int time, int flags, const char[] reason, const char[] kick_message, const char[] command, any source) { + if(GetUserAdmin(client) != INVALID_ADMIN_ID) { + LogMessage("Ignoring OnBanClient with admin id as target"); + return Plugin_Stop; + } + + + char executor[32], identity[32], ip[32]; + GetClientAuthId(client, AuthId_Steam2, identity, sizeof(identity)); + + LogMessage("OnBanClient client=%d flags=%d source=%d, command=%s", client, flags, source, command); + + DataPack pack; + if(source > 0 && source <= MaxClients && IsClientConnected(source) && GetClientAuthId(source, AuthId_Steam2, executor, sizeof(executor))) { + pack = new DataPack(); + pack.WriteString(identity); + pack.WriteCell(source); + }else{ + executor = "CONSOLE"; + } + + GetClientIP(client, ip, sizeof(ip)); + char query[512]; + + char expiresDate[64]; + if(time > 0) { + Format(expiresDate, sizeof(expiresDate), "%d", GetTime() + (time * 60)); + } else { + Format(expiresDate, sizeof(expiresDate), "NULL"); + } + + g_db.Format(query, sizeof(query), "INSERT INTO bans" + ..."(steamid, ip, reason, public_message, expires, executor, flags, timestamp)" + ..."VALUES ('%s', '%s', '%s', '%s', %s, '%s', %d, UNIX_TIMESTAMP())", + identity, + ip, + reason, + kick_message, + expiresDate, + executor, + BANFLAG_NONE + ); + + static char strKey[8]; + int key = ++iPendingCounter; + IntToString(key, strKey, sizeof(strKey)); + pendingInsertQueries.SetString(strKey, query); + + g_db.Format(query, sizeof(query), "SELECT `flags` FROM `bans` WHERE `expired` = 0 AND `steamid` LIKE 'STEAM_%%:%%:%s' OR ip = '%s'", identity[10], identity); + g_db.Query(DB_OnBanPreCheck, query, key); + + PrintToServer("Adding %N to OnBanClient queue. Key: %d", client, key); + + // TODO: REMOVE : FOR DEBUG + return Plugin_Handled; + return Plugin_Continue; +} + + + +public Action OnRemoveBan(const char[] identity, int flags, const char[] command, any source) { + if(flags == BANFLAG_AUTHID) { + static char query[128]; + g_db.Format(query, sizeof(query), "DELETE FROM `bans` WHERE steamid = '%s'", identity); + g_db.Query(DB_GenericCallback, query, flags); + } + return Plugin_Continue; + +} + +/////////////////////////////////////////////////////////////////////////////// +// DB Callbacks +/////////////////////////////////////////////////////////////////////////////// +//] DB_OnBanQuery returned error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 +public void DB_OnBanPreCheck(Database db, DBResultSet results, const char[] error, int key) { + static char strKey[8]; + IntToString(key, strKey, sizeof(strKey)); + static char query[255]; + pendingInsertQueries.GetString(strKey, query, sizeof(query)); + + if(results == null || db == INVALID_HANDLE) { + LogError("Ban Pre-check: Cannot check for existing ban, ignoring ban attempt. [Query: %s]", query); + } else { + if(results.FetchRow()) { + int flags = results.FetchInt(0); + if(~flags & BANFLAG_SUSPENDED) { + LogMessage("Ban Pre-check: Found existing non-suspended ban, ignoring ban attempt. [Query: %s]", query); + return; + } + } + + g_db.Query(DB_OnBanQuery, query); + } +} + + +public void DB_OnConnectCheck(Database db, DBResultSet results, const char[] error, int user) { + int client = GetClientOfUserId(user); + if(db == INVALID_HANDLE || results == null) { + LogError("DB_OnConnectCheck returned error: %s", error); + if(client > 0 && hKickType.IntValue == 2) { + KickClient(client, "Could not authenticate at this time."); + LogMessage("Could not connect to database to authorize user '%N' (#%d)", client, user); + } + } else { + //No failure, check the data. + while(client > 0 && results.FetchRow()) { //Is there a ban found? + static char reason[255], steamid[64], public_message[255]; + DBResult colResult; + + results.FetchString(0, reason, sizeof(reason), colResult); + results.FetchString(1, steamid, sizeof(steamid)); + if(colResult == DBVal_Null) { + reason[0] = '\0'; + } + + bool expired = results.FetchInt(2) == 1; //Check if computed column 'expired' is true + if(results.IsFieldNull(2)) { //If expired null, delete i guess. lol + DeleteBan(steamid); + } else { + int flags = results.FetchInt(4); + if(!expired && (~flags & BANFLAG_SUSPENDED)) { + LogAction(-1, client, "\"%L\" (%s), is banned from server: \"%s\"", client, steamid, reason); + // Fetch public message + results.FetchString(3, public_message, sizeof(public_message), colResult); + if(colResult == DBVal_Null || strlen(public_message) == 0) { + public_message = reason; + } + + int id = results.FetchInt(5); + + if(hKickType.IntValue > 0) { + if(public_message[0] != '\0') + KickClient(client, "Banned:\n%s\nAppeal at jackz.me/apl/%d", public_message, id); + else + KickClient(client, "You have been banned from this server.\nAppeal at jackz.me/apl/%d", id); + static char query[128]; + g_db.Format(query, sizeof(query), "UPDATE bans SET times_tried=times_tried+1 WHERE steamid = '%s'", steamid); + g_db.Query(DB_GenericCallback, query); + } else { + PrintChatToAdmins("\"%L\" was banned from this server for: \"%s\"", client, reason); + } + static char query[128]; + g_db.Format(query, sizeof(query), "UPDATE bans SET times_tried=times_tried+1 WHERE steamid = '%s'", steamid); + g_db.Query(DB_GenericCallback, query); + } else { + LogAction(-1, client, "\"%L\" was previously banned from server: \"%s\"", client, reason); + // User was previously banned + PrintChatToAdmins("%N (%s) has a previous suspended/expired ban of reason \"%s\"", client, steamid, reason); + } + } + } + } +} + +void DeleteBan(const char[] steamid) { + static char query[128]; + g_db.Format(query, sizeof(query), "DELETE FROM `bans` WHERE steamid = '%s'", steamid); + g_db.Query(DB_GenericCallback, query); +} + + +public void DB_OnBanQuery(Database db, DBResultSet results, const char[] error, any data) { + if(db == INVALID_HANDLE || results == null) { + LogError("DB_OnBanQuery returned error: %s", error); + DataPack pack = data; + if(pack != null) { + pack.Reset(); + static char id[32]; + pack.ReadString(id, sizeof(id)); + int source = pack.ReadCell(); + + if(StrContains(error, "Duplicate entry") > 0) { + PrintToChat(source, "Could not ban \"%s\", as they were previously banned. Please edit the ban manually on the website (or yell at jackz).", id); + } else { + PrintToChat(source, "Could not ban \"%s\" due to an error: %s", id, error); + } + } + } +} + +public void DB_GenericCallback(Database db, DBResultSet results, const char[] error, any data) { + if(db == INVALID_HANDLE || results == null) { + LogError("DB_OnRemoveBanQuery returned error: %s", error); + } +} + +stock void PrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToChat(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} diff --git a/scripting/include/CreateSurvivorBot.inc b/scripting/include/CreateSurvivorBot.inc new file mode 100644 index 0000000..ef108d5 --- /dev/null +++ b/scripting/include/CreateSurvivorBot.inc @@ -0,0 +1,43 @@ +#if defined _CreateSurvivorBot_included + #endinput +#endif +#define _CreateSurvivorBot_included + +native int NextBotCreatePlayerBotSurvivorBot(const char[] _szName = NULL_STRING); + +native bool CTerrorPlayerRoundRespawn(int _iClientIndex); + +stock int CreateSurvivorBot() +{ + int bot = NextBotCreatePlayerBotSurvivorBot(NULL_STRING); + if( IsValidEntity(bot) ) + { + ChangeClientTeam(bot, 2); + + if( !IsPlayerAlive(bot) ) + { + CTerrorPlayerRoundRespawn(bot); + } + return bot; + } + return -1; +} + +public SharedPlugin __pl_shope = +{ + name = "CreateSurvivorBot", + file = "CreateSurvivorBot.smx", + #if defined REQUIRE_PLUGIN + required = 1 + #else + required = 0 + #endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_CreateSurvivorBot_SetNTVOptional() +{ + MarkNativeAsOptional("NextBotCreatePlayerBotSurvivorBot"); + MarkNativeAsOptional("CTerrorPlayerRoundRespawn"); +} +#endif \ No newline at end of file diff --git a/scripting/include/SteamWorks.inc b/scripting/include/SteamWorks.inc new file mode 100644 index 0000000..94b38f5 --- /dev/null +++ b/scripting/include/SteamWorks.inc @@ -0,0 +1,413 @@ +#if defined _SteamWorks_Included + #endinput +#endif +#define _SteamWorks_Included + +/* results from UserHasLicenseForApp */ +enum EUserHasLicenseForAppResult +{ + k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app + k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app + k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated +}; + +/* General result codes */ +enum EResult +{ + k_EResultOK = 1, // success + k_EResultFail = 2, // generic failure + k_EResultNoConnection = 3, // no/failed network connection +// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed + k_EResultInvalidPassword = 5, // password/ticket is invalid + k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere + k_EResultInvalidProtocolVer = 7, // protocol version is incorrect + k_EResultInvalidParam = 8, // a parameter is incorrect + k_EResultFileNotFound = 9, // file was not found + k_EResultBusy = 10, // called method busy - action not taken + k_EResultInvalidState = 11, // called object was in an invalid state + k_EResultInvalidName = 12, // name is invalid + k_EResultInvalidEmail = 13, // email is invalid + k_EResultDuplicateName = 14, // name is not unique + k_EResultAccessDenied = 15, // access is denied + k_EResultTimeout = 16, // operation timed out + k_EResultBanned = 17, // VAC2 banned + k_EResultAccountNotFound = 18, // account not found + k_EResultInvalidSteamID = 19, // steamID is invalid + k_EResultServiceUnavailable = 20, // The requested service is currently unavailable + k_EResultNotLoggedOn = 21, // The user is not logged on + k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party) + k_EResultEncryptionFailure = 23, // Encryption or Decryption failed + k_EResultInsufficientPrivilege = 24, // Insufficient privilege + k_EResultLimitExceeded = 25, // Too much of a good thing + k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes) + k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired + k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again + k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time + k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user + k_EResultIPNotFound = 31, // IP address not found + k_EResultPersistFailed = 32, // failed to write change to the data store + k_EResultLockingFailed = 33, // failed to acquire access lock for this operation + k_EResultLogonSessionReplaced = 34, + k_EResultConnectFailed = 35, + k_EResultHandshakeFailed = 36, + k_EResultIOFailure = 37, + k_EResultRemoteDisconnect = 38, + k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested + k_EResultBlocked = 40, // a user didn't allow it + k_EResultIgnored = 41, // target is ignoring sender + k_EResultNoMatch = 42, // nothing matching the request found + k_EResultAccountDisabled = 43, + k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now + k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available + k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin + k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol. + k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another. + k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed. + k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait + k_EResultSuspended = 51, // Long running operation (content download) suspended/paused + k_EResultCancelled = 52, // Operation canceled (typically by user: content download) + k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable + k_EResultDiskFull = 54, // Operation canceled - not enough disk space. + k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed + k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side + k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account + k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid + k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first + k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files + k_EResultIllegalPassword = 61, // The requested new password is not legal + k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer ) + k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure + k_EResultCannotUseOldPassword = 64, // The requested new password is not legal + k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid + k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent + k_EResultHardwareNotCapableOfIPT = 67, // + k_EResultIPTInitError = 68, // + k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user + k_EResultFacebookQueryError = 70, // Facebook query returned an error + k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired + k_EResultIPLoginRestrictionFailed = 72, + k_EResultAccountLockedDown = 73, + k_EResultAccountLogonDeniedVerifiedEmailRequired = 74, + k_EResultNoMatchingURL = 75, + k_EResultBadResponse = 76, // parse failure, missing field, etc. + k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password + k_EResultValueOutOfRange = 78, // the value entered is outside the acceptable range + k_EResultUnexpectedError = 79, // something happened that we didn't expect to ever happen + k_EResultDisabled = 80, // The requested service has been configured to be unavailable + k_EResultInvalidCEGSubmission = 81, // The set of files submitted to the CEG server are not valid ! + k_EResultRestrictedDevice = 82, // The device being used is not allowed to perform this action + k_EResultRegionLocked = 83, // The action could not be complete because it is region restricted + k_EResultRateLimitExceeded = 84, // Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent + k_EResultAccountLoginDeniedNeedTwoFactor = 85, // Need two-factor code to login + k_EResultItemDeleted = 86, // The thing we're trying to access has been deleted + k_EResultAccountLoginDeniedThrottle = 87, // login attempt failed, try to throttle response to possible attacker + k_EResultTwoFactorCodeMismatch = 88, // two factor code mismatch + k_EResultTwoFactorActivationCodeMismatch = 89, // activation code for two-factor didn't match + k_EResultAccountAssociatedToMultiplePartners = 90, // account has been associated with multiple partners + k_EResultNotModified = 91, // data not modified + k_EResultNoMobileDevice = 92, // the account does not have a mobile device associated with it + k_EResultTimeNotSynced = 93, // the time presented is out of range or tolerance + k_EResultSmsCodeFailed = 94, // SMS code failure (no match, none pending, etc.) + k_EResultAccountLimitExceeded = 95, // Too many accounts access this resource + k_EResultAccountActivityLimitExceeded = 96, // Too many changes to this account + k_EResultPhoneActivityLimitExceeded = 97, // Too many changes to this phone + k_EResultRefundToWallet = 98, // Cannot refund to payment method, must use wallet + k_EResultEmailSendFailure = 99, // Cannot send an email + k_EResultNotSettled = 100, // Can't perform operation till payment has settled + k_EResultNeedCaptcha = 101, // Needs to provide a valid captcha + k_EResultGSLTDenied = 102, // a game server login token owned by this token's owner has been banned + k_EResultGSOwnerDenied = 103, // game server owner is denied for other reason (account lock, community ban, vac ban, missing phone) + k_EResultInvalidItemType = 104 // the type of thing we were requested to act on is invalid +}; + +/* This enum is used in client API methods, do not re-number existing values. */ +enum EHTTPMethod +{ + k_EHTTPMethodInvalid = 0, + k_EHTTPMethodGET, + k_EHTTPMethodHEAD, + k_EHTTPMethodPOST, + k_EHTTPMethodPUT, + k_EHTTPMethodDELETE, + k_EHTTPMethodOPTIONS, + k_EHTTPMethodPATCH, + + // The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for + // a compliant general purpose server. We'll likely add more as we find uses for them. + + // k_EHTTPMethodTRACE, + // k_EHTTPMethodCONNECT +}; + + +/* HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions + of each of these. */ +enum EHTTPStatusCode +{ + // Invalid status code (this isn't defined in HTTP, used to indicate unset in our code) + k_EHTTPStatusCodeInvalid = 0, + + // Informational codes + k_EHTTPStatusCode100Continue = 100, + k_EHTTPStatusCode101SwitchingProtocols = 101, + + // Success codes + k_EHTTPStatusCode200OK = 200, + k_EHTTPStatusCode201Created = 201, + k_EHTTPStatusCode202Accepted = 202, + k_EHTTPStatusCode203NonAuthoritative = 203, + k_EHTTPStatusCode204NoContent = 204, + k_EHTTPStatusCode205ResetContent = 205, + k_EHTTPStatusCode206PartialContent = 206, + + // Redirection codes + k_EHTTPStatusCode300MultipleChoices = 300, + k_EHTTPStatusCode301MovedPermanently = 301, + k_EHTTPStatusCode302Found = 302, + k_EHTTPStatusCode303SeeOther = 303, + k_EHTTPStatusCode304NotModified = 304, + k_EHTTPStatusCode305UseProxy = 305, + //k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1) + k_EHTTPStatusCode307TemporaryRedirect = 307, + + // Error codes + k_EHTTPStatusCode400BadRequest = 400, + k_EHTTPStatusCode401Unauthorized = 401, // You probably want 403 or something else. 401 implies you're sending a WWW-Authenticate header and the client can sent an Authorization header in response. + k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients + k_EHTTPStatusCode403Forbidden = 403, + k_EHTTPStatusCode404NotFound = 404, + k_EHTTPStatusCode405MethodNotAllowed = 405, + k_EHTTPStatusCode406NotAcceptable = 406, + k_EHTTPStatusCode407ProxyAuthRequired = 407, + k_EHTTPStatusCode408RequestTimeout = 408, + k_EHTTPStatusCode409Conflict = 409, + k_EHTTPStatusCode410Gone = 410, + k_EHTTPStatusCode411LengthRequired = 411, + k_EHTTPStatusCode412PreconditionFailed = 412, + k_EHTTPStatusCode413RequestEntityTooLarge = 413, + k_EHTTPStatusCode414RequestURITooLong = 414, + k_EHTTPStatusCode415UnsupportedMediaType = 415, + k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416, + k_EHTTPStatusCode417ExpectationFailed = 417, + k_EHTTPStatusCode4xxUnknown = 418, // 418 is reserved, so we'll use it to mean unknown + k_EHTTPStatusCode429TooManyRequests = 429, + + // Server error codes + k_EHTTPStatusCode500InternalServerError = 500, + k_EHTTPStatusCode501NotImplemented = 501, + k_EHTTPStatusCode502BadGateway = 502, + k_EHTTPStatusCode503ServiceUnavailable = 503, + k_EHTTPStatusCode504GatewayTimeout = 504, + k_EHTTPStatusCode505HTTPVersionNotSupported = 505, + k_EHTTPStatusCode5xxUnknown = 599, +}; + +/* list of possible return values from the ISteamGameCoordinator API */ +enum EGCResults +{ + k_EGCResultOK = 0, + k_EGCResultNoMessage = 1, // There is no message in the queue + k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message + k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam + k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage +}; + +native bool SteamWorks_IsVACEnabled(); +native bool SteamWorks_GetPublicIP(int ipaddr[4]); +native void SteamWorks_GetPublicIPCell(); +native bool SteamWorks_IsLoaded(); +native bool SteamWorks_SetGameData(const char[] sData); +native bool SteamWorks_SetGameDescription(const char[] sDesc); +native bool SteamWorks_SetMapName(const char[] sMapName); +native bool SteamWorks_IsConnected(); +native bool SteamWorks_SetRule(const char[] sKey, const char[] sValue); +native bool SteamWorks_ClearRules(); +native bool SteamWorks_ForceHeartbeat(); +native bool SteamWorks_GetUserGroupStatus(int client, int groupid); +native bool SteamWorks_GetUserGroupStatusAuthID(int authid, int groupid); + +native EUserHasLicenseForAppResult SteamWorks_HasLicenseForApp(int client, int app); +native EUserHasLicenseForAppResult SteamWorks_HasLicenseForAppId(int authid, int app); +native void SteamWorks_GetClientSteamID(int client, char[] sSteamID, int length); + +native bool SteamWorks_RequestStatsAuthID(int authid, int appid); +native bool SteamWorks_RequestStats(int client, int appid); +native bool SteamWorks_GetStatCell(int client, const char[] sKey, int &value); +native bool SteamWorks_GetStatAuthIDCell(int authid, const char[] sKey, int &value); +native bool SteamWorks_GetStatFloat(int client, const char[] sKey, float &value); +native bool SteamWorks_GetStatAuthIDFloat(int authid, const char[] sKey, float &value); + +native Handle SteamWorks_CreateHTTPRequest(EHTTPMethod method, const char[] sURL); +native bool SteamWorks_SetHTTPRequestContextValue(Handle hHandle, any data1, any data2 = 0); +native bool SteamWorks_SetHTTPRequestNetworkActivityTimeout(Handle hHandle, int timeout); +native bool SteamWorks_SetHTTPRequestHeaderValue(Handle hHandle, const char[] sName, const char[] sValue); +native bool SteamWorks_SetHTTPRequestGetOrPostParameter(Handle hHandle, const char[] sName, const char[] sValue); +native bool SteamWorks_SetHTTPRequestUserAgentInfo(Handle hHandle, const char[] sUserAgentInfo); +native bool SteamWorks_SetHTTPRequestRequiresVerifiedCertificate(Handle hHandle, bool bRequireVerifiedCertificate); +native bool SteamWorks_SetHTTPRequestAbsoluteTimeoutMS(Handle hHandle, int unMilliseconds); + +#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 9 +typeset SteamWorksHTTPRequestCompleted +{ + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode); + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1); + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1, any data2); +}; + +typeset SteamWorksHTTPHeadersReceived +{ + function void (Handle hRequest, bool bFailure); + function void (Handle hRequest, bool bFailure, any data1); + function void (Handle hRequest, bool bFailure, any data1, any data2); +}; + +typeset SteamWorksHTTPDataReceived +{ + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived); + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1); + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1, any data2); +}; + +typeset SteamWorksHTTPBodyCallback +{ + function void (const char[] sData); + function void (const char[] sData, any value); + function void (const int[] data, any value, int datalen); +}; + +#else + +funcenum SteamWorksHTTPRequestCompleted +{ + public(Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode:eStatusCode), + public(Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1), + public(Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPHeadersReceived +{ + public(Handle hRequest, bool bFailure), + public(Handle hRequest, bool bFailure, any:data1), + public(Handle hRequest, bool bFailure, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPDataReceived +{ + public(Handle hRequest, bool bFailure, offset, bytesreceived), + public(Handle hRequest, bool bFailure, offset, bytesreceived, any:data1), + public(Handle hRequest, bool bFailure, offset, bytesreceived, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPBodyCallback +{ + public(const char sData[]), + public(const char sData[], any:value), + public(const data[], any:value, datalen) +}; + +#endif + +native bool SteamWorks_SetHTTPCallbacks(Handle hHandle, SteamWorksHTTPRequestCompleted fCompleted = INVALID_FUNCTION, SteamWorksHTTPHeadersReceived fHeaders = INVALID_FUNCTION, SteamWorksHTTPDataReceived fData = INVALID_FUNCTION, Handle hCalling = INVALID_HANDLE); +native bool SteamWorks_SendHTTPRequest(Handle hRequest); +native bool SteamWorks_SendHTTPRequestAndStreamResponse(Handle hRequest); +native bool SteamWorks_DeferHTTPRequest(Handle hRequest); +native bool SteamWorks_PrioritizeHTTPRequest(Handle hRequest); +native bool SteamWorks_GetHTTPResponseHeaderSize(Handle hRequest, const char[] sHeader, int &size); +native bool SteamWorks_GetHTTPResponseHeaderValue(Handle hRequest, const char[] sHeader, char[] sValue, int size); +native bool SteamWorks_GetHTTPResponseBodySize(Handle hRequest, int &size); +native bool SteamWorks_GetHTTPResponseBodyData(Handle hRequest, char[] sBody, int length); +native bool SteamWorks_GetHTTPStreamingResponseBodyData(Handle hRequest, int cOffset, char[] sBody, int length); +native bool SteamWorks_GetHTTPDownloadProgressPct(Handle hRequest, float &percent); +native bool SteamWorks_GetHTTPRequestWasTimedOut(Handle hRequest, bool & bWasTimedOut); +native bool SteamWorks_SetHTTPRequestRawPostBody(Handle hRequest, const char[] sContentType, const char[] sBody, int bodylen); +native bool SteamWorks_SetHTTPRequestRawPostBodyFromFile(Handle hRequest, const char[] sContentType, const char[] sFileName); + +native bool SteamWorks_GetHTTPResponseBodyCallback(Handle hRequest, SteamWorksHTTPBodyCallback fCallback, any data = 0, Handle hPlugin = INVALID_HANDLE); /* Look up, moved definition for 1.7+ compat. */ +native bool SteamWorks_WriteHTTPResponseBodyToFile(Handle hRequest, const char[] sFileName); + +forward void SW_OnValidateClient(int ownerauthid, int authid); +forward void SteamWorks_OnValidateClient(int ownerauthid, int authid); +forward void SteamWorks_SteamServersConnected(); +forward void SteamWorks_SteamServersConnectFailure(EResult result); +forward void SteamWorks_SteamServersDisconnected(EResult result); + +forward Action SteamWorks_RestartRequested(); +forward void SteamWorks_TokenRequested(char[] sToken, int maxlen); + +forward void SteamWorks_OnClientGroupStatus(int authid, int groupid, bool isMember, bool isOfficer); + +forward EGCResults SteamWorks_GCSendMessage(int unMsgType, const char[] pubData, int cubData); +forward void SteamWorks_GCMsgAvailable(int cubData); +forward EGCResults SteamWorks_GCRetrieveMessage(int punMsgType, const char[] pubDest, int cubDest, int pcubMsgSize); + +native EGCResults SteamWorks_SendMessageToGC(int unMsgType, const char[] pubData, int cubData); + +public Extension __ext_SteamWorks = +{ + name = "SteamWorks", + file = "SteamWorks.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_EXTENSIONS +public __ext_SteamWorks_SetNTVOptional() +{ + MarkNativeAsOptional("SteamWorks_IsVACEnabled"); + MarkNativeAsOptional("SteamWorks_GetPublicIP"); + MarkNativeAsOptional("SteamWorks_GetPublicIPCell"); + MarkNativeAsOptional("SteamWorks_IsLoaded"); + MarkNativeAsOptional("SteamWorks_SetGameData"); + MarkNativeAsOptional("SteamWorks_SetGameDescription"); + MarkNativeAsOptional("SteamWorks_IsConnected"); + MarkNativeAsOptional("SteamWorks_SetRule"); + MarkNativeAsOptional("SteamWorks_ClearRules"); + MarkNativeAsOptional("SteamWorks_ForceHeartbeat"); + MarkNativeAsOptional("SteamWorks_GetUserGroupStatus"); + MarkNativeAsOptional("SteamWorks_GetUserGroupStatusAuthID"); + + MarkNativeAsOptional("SteamWorks_HasLicenseForApp"); + MarkNativeAsOptional("SteamWorks_HasLicenseForAppId"); + MarkNativeAsOptional("SteamWorks_GetClientSteamID"); + + MarkNativeAsOptional("SteamWorks_RequestStatsAuthID"); + MarkNativeAsOptional("SteamWorks_RequestStats"); + MarkNativeAsOptional("SteamWorks_GetStatCell"); + MarkNativeAsOptional("SteamWorks_GetStatAuthIDCell"); + MarkNativeAsOptional("SteamWorks_GetStatFloat"); + MarkNativeAsOptional("SteamWorks_GetStatAuthIDFloat"); + + MarkNativeAsOptional("SteamWorks_SendMessageToGC"); + + MarkNativeAsOptional("SteamWorks_CreateHTTPRequest"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestContextValue"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestNetworkActivityTimeout"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestHeaderValue"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestGetOrPostParameter"); + + MarkNativeAsOptional("SteamWorks_SetHTTPCallbacks"); + MarkNativeAsOptional("SteamWorks_SendHTTPRequest"); + MarkNativeAsOptional("SteamWorks_SendHTTPRequestAndStreamResponse"); + MarkNativeAsOptional("SteamWorks_DeferHTTPRequest"); + MarkNativeAsOptional("SteamWorks_PrioritizeHTTPRequest"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderSize"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderValue"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodySize"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyData"); + MarkNativeAsOptional("SteamWorks_GetHTTPStreamingResponseBodyData"); + MarkNativeAsOptional("SteamWorks_GetHTTPDownloadProgressPct"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBody"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBodyFromFile"); + + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyCallback"); + MarkNativeAsOptional("SteamWorks_WriteHTTPResponseBodyToFile"); +} +#endif diff --git a/scripting/include/actions.inc b/scripting/include/actions.inc new file mode 100644 index 0000000..9273ce4 --- /dev/null +++ b/scripting/include/actions.inc @@ -0,0 +1,962 @@ +#if defined _actions_included + #endinput +#endif + +#define _actions_included + +#define ACTION_NAME_LENGTH 32 + +enum ActionResultType +{ + CONTINUE, // continue executing this action next frame - nothing has changed + CHANGE_TO, // change actions next frame + SUSPEND_FOR, // put the current action on hold for the new action + DONE, // this action has finished, resume suspended action + SUSTAIN, // for use with event handlers - a way to say "It's important to keep doing what I'm doing" +}; + +enum EventResultPriorityType +{ + RESULT_NONE, // no result + RESULT_TRY, // use this result, or toss it out, either is ok + RESULT_IMPORTANT, // try extra-hard to use this result + RESULT_CRITICAL // this result must be used - emit an error if it can't be +}; + +enum BehaviorAction +{ + INVALID_ACTION +}; + +/** + * @brief Callback called for every entity action. + * + * @param action Action address + * + * @noreturn + */ +typedef ActionsIteratorCallback = function void (BehaviorAction action); + +/** + * @brief Called whenever action is created + * + * @param action Created action address + * @param actor Actor of the action + * @param name Name of the action + * + * @noreturn + */ +forward void OnActionCreated( BehaviorAction action, int actor, const char[] name ); + +/** + * @brief Called whenever action is destroyed + * @note You are in action destructor! + * + * @param action Destroyed action address + * @param actor Actor of the action + * @param name Name of the action + * + * @noreturn + */ +forward void OnActionDestroyed( BehaviorAction action, int actor, const char[] name ); + +methodmap ActionResult +{ + /** + * @brief Gets action result reason + * + * @param destination Buffer to store reason + * @param maxlength Length of the buffer + * + * @noreturn + */ + public native void GetReason( char[] destination, int maxlength ); + + /** + * @brief Sets action result reason + * + * @param reason String with reason + * + * @noreturn + */ + public native void SetReason( const char[] reason ); + + /** + * @brief Property to get/set result type + * + * @return Result type (see ActionResultType) + */ + property ActionResultType type + { + public native get(); + public native set(ActionResultType type); + } + + /** + * @brief Property to get/set result action + * + * @return Result action + */ + property BehaviorAction action + { + public native get(); + public native set(BehaviorAction action); + } + + /** + * @brief Checks if result is requesting change + * + * @return true if it is requesting, false otherwise + */ + public bool IsRequestingChange() + { + ActionResultType type = this.type; + + return (type == CHANGE_TO || type == SUSPEND_FOR || type == DONE); + } +} + +methodmap ActionDesiredResult < ActionResult +{ + /** + * @brief Property to get/set result priority + * + * @return Result priority + */ + property EventResultPriorityType priority + { + public native get(); + public native set(EventResultPriorityType priority); + } +} + +typeset ActionHandler +{ + /* OnStart, OnSuspend, OnResume */ + function Action (BehaviorAction action, int actor, BehaviorAction priorAction, ActionResult result); + + /* OnUpdate */ + function Action (BehaviorAction action, int actor, float interval, ActionResult result); + + /* OnEnd */ + function void (BehaviorAction action, int actor, BehaviorAction priorAction, ActionResult result); + + /* InitialContainedAction */ + function Action (BehaviorAction action, int actor, BehaviorAction& action); + + /* OnLeaveGround, OnLandOnGround, OnDrop, OnShoved, OnBlinded, OnHitByVomitJar, OnCommandAttack */ + function Action (BehaviorAction action, int actor, int entity, ActionDesiredResult result); + + /* OnContact */ + function Action (BehaviorAction action, int actor, int entity, Address trace, ActionDesiredResult result); + + /* OnMoveToSuccess */ + function Action (BehaviorAction action, int actor, Address path, ActionDesiredResult result); + + /* OnMoveToFailure */ + function Action (BehaviorAction action, int actor, Address path, any type, ActionDesiredResult result); + + /* OnStuck, OnUnStuck, OnPostureChanged, OnIgnite, OnModelChanged, OnEnteredSpit, OnCommandAssault, OnCommandResume */ + function Action (BehaviorAction action, int actor, ActionDesiredResult result); + + /* OnAnimationActivityComplete, OnAnimationActivityInterrupted */ + function Action (BehaviorAction action, int actor, int activity, ActionDesiredResult result); + + /* OnAnimationEvent */ + function Action (BehaviorAction action, int actor, Address animevent, ActionDesiredResult result); + + /* OnInjured, OnKilled */ + function Action (BehaviorAction action, int actor, Address takedamageinfo, ActionDesiredResult result); + + /* OnOtherKilled */ + function Action (BehaviorAction action, int actor, int other, Address takedamageinfo, ActionDesiredResult result); + + /* OnSight, OnLostSight, OnThreatChanged */ + function Action (BehaviorAction action, int actor, int entity, ActionDesiredResult result); + + /* OnSound */ + function Action (BehaviorAction action, int actor, int entity, const float pos[3], Address keyvalues, ActionDesiredResult result); + + /* OnSpokeConcept */ + function Action (BehaviorAction action, int actor, int who, Address concept, Address response, Address unknown, ActionDesiredResult result); + + /* OnNavAreaChanged */ + function Action (BehaviorAction action, int actor, Address newArea, Address oldArea, ActionDesiredResult result); + + /* OnPickUp */ + function Action (BehaviorAction action, int actor, int entity, int giver, ActionDesiredResult result); + + /* OnCommandApproachVector */ + function Action (BehaviorAction action, int actor, const float pos[3], float range, ActionDesiredResult result); + + /* OnCommandApproachEntity */ + function Action (BehaviorAction action, int actor, int goal, ActionDesiredResult result); + + /* OnCommandRetreat */ + function Action (BehaviorAction action, int actor, int threat, float range, ActionDesiredResult result); + + /* OnCommandPause */ + function Action (BehaviorAction action, int actor, float duration, ActionDesiredResult result); + + /* OnCommandString */ + function Action (BehaviorAction action, int actor, const char[] command, ActionDesiredResult result); + + /* IsAbleToBlockMovementOf */ + function Action (BehaviorAction action, int actor, Address nextbot, ActionDesiredResult result); +} + +methodmap ActionsManager +{ + /** + * @brief Creates action template with given name + * @note Use this to create your own actions + * + * @param name New action name + * + * @return Action address + */ + public static native BehaviorAction Create( const char[] name ); + + /** + * @brief Allocates memory with given size + * @note Use this with game action constructor to create game actions + * + * @param size Size to allocate + * + * @return Allocated memory start address + */ + public static native BehaviorAction Allocate( int size ); + + /** + * @brief Deallocates memory + * @note Actually used only for deallocating actions + * + * @param action Action to deallocate + * + * @noreturn + */ + public static native void Deallocate( BehaviorAction action ); + + /** + * @brief Used to iterate over all entity actions + * + * @param entity Entity index + * @param callback Iterator callback + * + * @return Number of actions entity has + */ + public static native int Iterator( int entity, ActionsIteratorCallback callback = INVALID_FUNCTION ); + + /** + * @brief Returns entity action with given name + * + * @param entity Entity index + * @param name Action name to find + * + * @return Action address, INVALID_ACTION if not found + */ + public static native BehaviorAction GetAction( int entity, const char[] name ); +} + +methodmap BehaviorAction +{ + public BehaviorAction(any action) + { + return view_as(action); + } + + /** + * @brief Stores pending event result + * @note This is almost same as changing result via event handler but this one violates semantics + * + * @param type Result type (See ActionResultType) + * @param action Action + * @param priority Priority + * @param reason Reason + * + * @error Invalid action passed + * @noreturn + */ + public native void StorePendingEventResult( ActionResultType type = CONTINUE, BehaviorAction action = INVALID_ACTION, EventResultPriorityType priority = RESULT_TRY, const char[] reason = NULL_STRING ); + + /** + * @brief Gets action name + * + * @param destination Buffer to store name + * @param maxlength Buffer length + * + * @error Invalid action passed + * @return Number of bytes written? + */ + public native int GetName( char[] destination, int maxlength = ACTION_NAME_LENGTH ); + + /** + * @brief Simple wrapper to get action data + * + * @param int Offset to data + * @param type How many bytes read (See NumberType) + * + * @return Stored data + */ + public any Get( int offset, NumberType type = NumberType_Int32 ) + { + return view_as(LoadFromAddress(view_as
(this) + view_as
(offset), type)); + } + + /** + * @brief Simple wrapper to set action data + * + * @param int Offset to data + * @param data Data to set + * @param type How many bytes set (See NumberType) + * + * @noreturn + */ + #if SOURCEMOD_V_MINOR < 11 + public void Set( int offset, any data, NumberType type = NumberType_Int32 ) + { + StoreToAddress(view_as
(this) + view_as
(offset), data, type); + } + #else + public void Set( int offset, any data, NumberType type = NumberType_Int32, bool updateMemAccess = true ) + { + StoreToAddress(view_as
(this) + view_as
(offset), data, type, updateMemAccess); + } + #endif + // ==================================================================================================== + // ACTION PROPERTIES + // ==================================================================================================== + + /** + * @brief Property to get/set parent action + * + * @return Parent action + */ + property BehaviorAction Parent + { + public native get(); + } + + /** + * @brief Property to get/set child action + * + * @return Child action + */ + property BehaviorAction Child + { + public native get(); + } + + /** + * @brief Property to get/set "under" action + * @note if we are suspender then this will return a suspended action + * + * @return Under action + */ + property BehaviorAction Under + { + public native get(); + } + + /** + * @brief Property to get/set "above" action + * @note if we are suspended action then this will return a suspender + * + * @return Above action + */ + property BehaviorAction Above + { + public native get(); + } + + /** + * @brief Property to get actor of action + * @note returns 0 if action hasn't been started yet + * + * @return Action actor + */ + property int Actor + { + public native get(); + } + + /** + * @brief Property to get/set suspended state of action + * + * @return true if suspended, false otherwise + */ + property bool IsSuspended + { + public native get(); + public native set(bool suspended); + } + + /** + * @brief Property to get/set started state of action + * @note if this returns true then OnStart handled has already been called + * + * @return true if started, false otherwise + */ + property bool IsStarted + { + public native get(); + public native set(bool started); + } + + // ==================================================================================================== + // ACTION PRE EVENT HANDLERS + // ==================================================================================================== + + property ActionHandler OnStart + { + public native set(ActionHandler func); + } + + property ActionHandler OnUpdate + { + public native set(ActionHandler func); + } + + property ActionHandler OnEnd + { + public native set(ActionHandler func); + } + + property ActionHandler OnSuspend + { + public native set(ActionHandler func); + } + + property ActionHandler OnResume + { + public native set(ActionHandler func); + } + + property ActionHandler OnInitialContainedAction + { + public native set(ActionHandler func); + } + + property ActionHandler OnLeaveGround + { + public native set(ActionHandler func); + } + + property ActionHandler OnLandOnGround + { + public native set(ActionHandler func); + } + + property ActionHandler OnContact + { + public native set(ActionHandler func); + } + + property ActionHandler OnMoveToSuccess + { + public native set(ActionHandler func); + } + + property ActionHandler OnMoveToFailure + { + public native set(ActionHandler func); + } + + property ActionHandler OnStuck + { + public native set(ActionHandler func); + } + + property ActionHandler OnUnStuck + { + public native set(ActionHandler func); + } + + property ActionHandler OnPostureChanged + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationActivityComplete + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationActivityInterrupted + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationEvent + { + public native set(ActionHandler func); + } + + property ActionHandler OnIgnite + { + public native set(ActionHandler func); + } + + property ActionHandler OnInjured + { + public native set(ActionHandler func); + } + + property ActionHandler OnKilled + { + public native set(ActionHandler func); + } + + property ActionHandler OnOtherKilled + { + public native set(ActionHandler func); + } + + property ActionHandler OnSight + { + public native set(ActionHandler func); + } + + property ActionHandler OnLostSight + { + public native set(ActionHandler func); + } + + property ActionHandler OnThreatChanged + { + public native set(ActionHandler func); + } + + property ActionHandler OnSound + { + public native set(ActionHandler func); + } + + property ActionHandler OnSpokeConcept + { + public native set(ActionHandler func); + } + + property ActionHandler OnNavAreaChanged + { + public native set(ActionHandler func); + } + + property ActionHandler OnModelChanged + { + public native set(ActionHandler func); + } + + property ActionHandler OnPickUp + { + public native set(ActionHandler func); + } + + property ActionHandler OnShoved + { + public native set(ActionHandler func); + } + + property ActionHandler OnBlinded + { + public native set(ActionHandler func); + } + + property ActionHandler OnEnteredSpit + { + public native set(ActionHandler func); + } + + property ActionHandler OnHitByVomitJar + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandAttack + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandAssault + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandApproachV + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandApproachE + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandRetreat + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandPause + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandResume + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandString + { + public native set(ActionHandler func); + } + + property ActionHandler IsAbleToBlockMovementOf + { + public native set(ActionHandler func); + } + + // ==================================================================================================== + // ACTION POST EVENT HANDLERS + // ==================================================================================================== + + property ActionHandler OnStartPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnUpdatePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnEndPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnSuspendPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnResumePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnInitialContainedActionPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnLeaveGroundPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnLandOnGroundPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnContactPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnMoveToSuccessPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnMoveToFailurePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnStuckPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnUnStuckPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnPostureChangedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationActivityCompletePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationActivityInterruptedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnAnimationEventPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnIgnitePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnInjuredPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnKilledPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnOtherKilledPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnSightPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnLostSightPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnThreatChangedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnSoundPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnSpokeConceptPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnNavAreaChangedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnModelChangedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnPickUpPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnShovedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnBlindedPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnEnteredSpitPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnHitByVomitJarPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandAttackPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandAssaultPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandApproachVPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandApproachEPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandRetreatPost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandPausePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandResumePost + { + public native set(ActionHandler func); + } + + property ActionHandler OnCommandStringPost + { + public native set(ActionHandler func); + } + + property ActionHandler IsAbleToBlockMovementOfPost + { + public native set(ActionHandler func); + } +}; + +// ==================================================================================================== +// PL NTV +// ==================================================================================================== + +public Extension __ext_actions = +{ + name = "Actions", + file = "actions.ext", + autoload = 1, +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_EXTENSIONS +public void __ext_actions_SetNTVOptional() +{ + MarkNativeAsOptional("ActionResult.GetReason"); + MarkNativeAsOptional("ActionResult.SetReason"); + MarkNativeAsOptional("ActionResult.type.get"); + MarkNativeAsOptional("ActionResult.type.set"); + MarkNativeAsOptional("ActionResult.action.get"); + MarkNativeAsOptional("ActionResult.action.set"); + MarkNativeAsOptional("ActionDesiredResult.priority.get"); + MarkNativeAsOptional("ActionDesiredResult.priority.set"); + MarkNativeAsOptional("ActionsManager.Create"); + MarkNativeAsOptional("ActionsManager.Allocate"); + MarkNativeAsOptional("ActionsManager.Deallocate"); + MarkNativeAsOptional("ActionsManager.Iterator"); + MarkNativeAsOptional("ActionsManager.GetAction"); + MarkNativeAsOptional("BehaviorAction.StorePendingEventResult"); + MarkNativeAsOptional("BehaviorAction.GetName"); + MarkNativeAsOptional("BehaviorAction.Parent.get"); + MarkNativeAsOptional("BehaviorAction.Child.get"); + MarkNativeAsOptional("BehaviorAction.Under.get"); + MarkNativeAsOptional("BehaviorAction.Above.get"); + MarkNativeAsOptional("BehaviorAction.Actor.get"); + MarkNativeAsOptional("BehaviorAction.IsSuspended.get"); + MarkNativeAsOptional("BehaviorAction.IsSuspended.set"); + MarkNativeAsOptional("BehaviorAction.IsStarted.get"); + MarkNativeAsOptional("BehaviorAction.IsStarted.set"); + MarkNativeAsOptional("BehaviorAction.OnStart.set"); + MarkNativeAsOptional("BehaviorAction.OnUpdate.set"); + MarkNativeAsOptional("BehaviorAction.OnEnd.set"); + MarkNativeAsOptional("BehaviorAction.OnSuspend.set"); + MarkNativeAsOptional("BehaviorAction.OnResume.set"); + MarkNativeAsOptional("BehaviorAction.OnInitialContainedAction.set"); + MarkNativeAsOptional("BehaviorAction.OnLeaveGround.set"); + MarkNativeAsOptional("BehaviorAction.OnLandOnGround.set"); + MarkNativeAsOptional("BehaviorAction.OnContact.set"); + MarkNativeAsOptional("BehaviorAction.OnMoveToSuccess.set"); + MarkNativeAsOptional("BehaviorAction.OnMoveToFailure.set"); + MarkNativeAsOptional("BehaviorAction.OnStuck.set"); + MarkNativeAsOptional("BehaviorAction.OnUnStuck.set"); + MarkNativeAsOptional("BehaviorAction.OnPostureChanged.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationActivityComplete.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationActivityInterrupted.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationEvent.set"); + MarkNativeAsOptional("BehaviorAction.OnIgnite.set"); + MarkNativeAsOptional("BehaviorAction.OnInjured.set"); + MarkNativeAsOptional("BehaviorAction.OnKilled.set"); + MarkNativeAsOptional("BehaviorAction.OnOtherKilled.set"); + MarkNativeAsOptional("BehaviorAction.OnSight.set"); + MarkNativeAsOptional("BehaviorAction.OnLostSight.set"); + MarkNativeAsOptional("BehaviorAction.OnThreatChanged.set"); + MarkNativeAsOptional("BehaviorAction.OnSound.set"); + MarkNativeAsOptional("BehaviorAction.OnSpokeConcept.set"); + MarkNativeAsOptional("BehaviorAction.OnNavAreaChanged.set"); + MarkNativeAsOptional("BehaviorAction.OnModelChanged.set"); + MarkNativeAsOptional("BehaviorAction.OnPickUp.set"); + MarkNativeAsOptional("BehaviorAction.OnShoved.set"); + MarkNativeAsOptional("BehaviorAction.OnBlinded.set"); + MarkNativeAsOptional("BehaviorAction.OnEnteredSpit.set"); + MarkNativeAsOptional("BehaviorAction.OnHitByVomitJar.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandAttack.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandAssault.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandApproachV.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandApproachE.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandRetreat.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandPause.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandResume.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandString.set"); + MarkNativeAsOptional("BehaviorAction.IsAbleToBlockMovementOf.set"); + MarkNativeAsOptional("BehaviorAction.OnStartPost.set"); + MarkNativeAsOptional("BehaviorAction.OnUpdatePost.set"); + MarkNativeAsOptional("BehaviorAction.OnEndPost.set"); + MarkNativeAsOptional("BehaviorAction.OnSuspendPost.set"); + MarkNativeAsOptional("BehaviorAction.OnResumePost.set"); + MarkNativeAsOptional("BehaviorAction.OnInitialContainedActionPost.set"); + MarkNativeAsOptional("BehaviorAction.OnLeaveGroundPost.set"); + MarkNativeAsOptional("BehaviorAction.OnLandOnGroundPost.set"); + MarkNativeAsOptional("BehaviorAction.OnContactPost.set"); + MarkNativeAsOptional("BehaviorAction.OnMoveToSuccessPost.set"); + MarkNativeAsOptional("BehaviorAction.OnMoveToFailurePost.set"); + MarkNativeAsOptional("BehaviorAction.OnStuckPost.set"); + MarkNativeAsOptional("BehaviorAction.OnUnStuckPost.set"); + MarkNativeAsOptional("BehaviorAction.OnPostureChangedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationActivityCompletePost.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationActivityInterruptedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnAnimationEventPost.set"); + MarkNativeAsOptional("BehaviorAction.OnIgnitePost.set"); + MarkNativeAsOptional("BehaviorAction.OnInjuredPost.set"); + MarkNativeAsOptional("BehaviorAction.OnKilledPost.set"); + MarkNativeAsOptional("BehaviorAction.OnOtherKilledPost.set"); + MarkNativeAsOptional("BehaviorAction.OnSightPost.set"); + MarkNativeAsOptional("BehaviorAction.OnLostSightPost.set"); + MarkNativeAsOptional("BehaviorAction.OnThreatChangedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnSoundPost.set"); + MarkNativeAsOptional("BehaviorAction.OnSpokeConceptPost.set"); + MarkNativeAsOptional("BehaviorAction.OnNavAreaChangedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnModelChangedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnPickUpPost.set"); + MarkNativeAsOptional("BehaviorAction.OnShovedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnBlindedPost.set"); + MarkNativeAsOptional("BehaviorAction.OnEnteredSpitPost.set"); + MarkNativeAsOptional("BehaviorAction.OnHitByVomitJarPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandAttackPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandAssaultPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandApproachVPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandApproachEPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandRetreatPost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandPausePost.set"); + MarkNativeAsOptional("BehaviorAction.OnCommandResumePost.set"); + MarkNativeAsOptional("BehaviorAction.IsAbleToBlockMovementOfPost.set"); +} +#endif \ No newline at end of file diff --git a/scripting/include/activitymonitor.inc b/scripting/include/activitymonitor.inc new file mode 100644 index 0000000..c58c76d --- /dev/null +++ b/scripting/include/activitymonitor.inc @@ -0,0 +1,6 @@ +#if defined _activitymonitor_included_ + #endinput +#endif +#define _activitymonitor_included_ + +native bool AddLog(const char[] type, const char[] clientName, const char[] targetName, const char[] message); \ No newline at end of file diff --git a/scripting/include/colors.inc b/scripting/include/colors.inc new file mode 100644 index 0000000..45fd1ef --- /dev/null +++ b/scripting/include/colors.inc @@ -0,0 +1,446 @@ +/************************************************************************** + * * + * Colored Chat Functions * + * Author: exvel * + * Version: 1.0.5 * + * * + **************************************************************************/ + +#if defined _colors_included + #endinput +#endif +#define _colors_included + +#define MAX_MESSAGE_LENGTH 250 +#define MAX_COLORS 6 + +#define SERVER_INDEX 0 +#define NO_INDEX -1 +#define NO_PLAYER -2 + +enum Colors +{ + Color_Default = 0, + Color_Green, + Color_Lightgreen, + Color_Red, + Color_Blue, + Color_Olive +} + +/* Colors' properties */ +new String:CTag[][] = {"{default}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}"}; +new String:CTagCode[][] = {"\x01", "\x04", "\x03", "\x03", "\x03", "\x05"}; +new bool:CTagReqSayText2[] = {false, false, true, true, true, false}; +new bool:CEventIsHooked = false; +new bool:CSkipList[MAXPLAYERS+1] = {false,...}; + +/* Game default profile */ +new bool:CProfile_Colors[] = {true, true, false, false, false, false}; +new CProfile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX}; +new bool:CProfile_SayText2 = false; + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client is not connected an error will be thrown. + */ +stock CPrintToChat(client, const String:szMessage[], any:...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + decl String:szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3); + + new index = CFormat(szCMessage, sizeof(szCMessage)); + if (index == NO_INDEX) + { + PrintToChat(client, szCMessage); + } + else + { + CSayText2(client, index, szCMessage); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules) + * @return No return + */ +stock CPrintToChatAll(const String:szMessage[], any:...) +{ + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 2); + CPrintToChat(i, szBuffer); + } + + CSkipList[i] = false; + } +} + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags and teamcolor tag. + * + * @param client Client index. + * @param author Author index whose color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client or author are not connected an error will be thrown. + */ +stock CPrintToChatEx(client, author, const String:szMessage[], any:...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + decl String:szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4); + + new index = CFormat(szCMessage, sizeof(szCMessage), author); + if (index == NO_INDEX) + { + PrintToChat(client, szCMessage); + } + else + { + CSayText2(client, author, szCMessage); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags and teamcolor tag. + * + * @param author Author index whos color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the author is not connected an error will be thrown. + */ +stock CPrintToChatAllEx(author, const String:szMessage[], any:...) +{ + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + if (!IsClientInGame(author)) + ThrowError("Client %d is not in game", author); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 3); + CPrintToChatEx(i, author, szBuffer); + } + + CSkipList[i] = false; + } +} + +/** + * Removes color tags from the string. + * + * @param szMessage String. + * @return No return + */ +stock CRemoveTags(String:szMessage[], maxlength) +{ + for (new i = 0; i < MAX_COLORS; i++) + { + ReplaceString(szMessage, maxlength, CTag[i], ""); + } + + ReplaceString(szMessage, maxlength, "{teamcolor}", ""); +} + +/** + * This function should only be used right in front of + * CPrintToChatAll or CPrintToChatAllEx and it tells + * to those funcions to skip specified client when printing + * message to all clients. After message is printed client will + * no more be skipped. + * + * @param client Client index + * @return No return + */ +stock CSkipNextClient(client) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + CSkipList[client] = true; +} + +/** + * Replaces color tags in a string with color codes + * + * @param szMessage String. + * @param maxlength Maximum length of the string buffer. + * @return Client index that can be used for SayText2 author index + * + * On error/Errors: If there is more then one team color is used an error will be thrown. + */ +stock CFormat(String:szMessage[], maxlength, author=NO_INDEX) +{ + /* Hook event for auto profile setup on map start */ + if (!CEventIsHooked) + { + CSetupProfile(); + HookEvent("server_spawn", CEvent_MapStart, EventHookMode_PostNoCopy); + CEventIsHooked = true; + } + + new iRandomPlayer = NO_INDEX; + + /* If author was specified replace {teamcolor} tag */ + if (author != NO_INDEX) + { + if (CProfile_SayText2) + { + ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03"); + iRandomPlayer = author; + } + /* If saytext2 is not supported by game replace {teamcolor} with green tag */ + else + { + ReplaceString(szMessage, maxlength, "{teamcolor}", CTagCode[Color_Green]); + } + } + else + { + ReplaceString(szMessage, maxlength, "{teamcolor}", ""); + } + + /* For other color tags we need a loop */ + for (new i = 0; i < MAX_COLORS; i++) + { + /* If tag not found - skip */ + if (StrContains(szMessage, CTag[i]) == -1) + { + continue; + } + /* If tag is not supported by game replace it with green tag */ + else if (!CProfile_Colors[i]) + { + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green]); + } + /* If tag doesn't need saytext2 simply replace */ + else if (!CTagReqSayText2[i]) + { + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i]); + } + /* Tag needs saytext2 */ + else + { + /* If saytext2 is not supported by game replace tag with green tag */ + if (!CProfile_SayText2) + { + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green]); + } + /* Game supports saytext2 */ + else + { + /* If random player for tag wasn't specified replace tag and find player */ + if (iRandomPlayer == NO_INDEX) + { + /* Searching for valid client for tag */ + iRandomPlayer = CFindRandomPlayerByTeam(CProfile_TeamIndex[i]); + + /* If player not found replace tag with green color tag */ + if (iRandomPlayer == NO_PLAYER) + { + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green]); + } + /* If player was found simply replace */ + else + { + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i]); + } + + } + /* If found another team color tag throw error */ + else + { + //ReplaceString(szMessage, maxlength, CTag[i], ""); + ThrowError("Using two team colors in one message is not allowed"); + } + } + + } + } + + return iRandomPlayer; +} + +/** + * Founds a random player with specified team + * + * @param color_team Client team. + * @return Client index or NO_PLAYER if no player found + */ +stock CFindRandomPlayerByTeam(color_team) +{ + if (color_team == SERVER_INDEX) + { + return 0; + } + else + { + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && GetClientTeam(i) == color_team) + { + return i; + } + } + } + + return NO_PLAYER; +} + +/** + * Sends a SayText2 usermessage to a client + * + * @param szMessage Client index + * @param maxlength Author index + * @param szMessage Message + * @return No return. + */ +stock CSayText2(client, author, const String:szMessage[]) +{ + new Handle:hBuffer = StartMessageOne("SayText2", client); + BfWriteByte(hBuffer, author); + BfWriteByte(hBuffer, true); + BfWriteString(hBuffer, szMessage); + EndMessage(); +} + +/** + * Creates game color profile + * This function must be edited if you want to add more games support + * + * @return No return. + */ +stock CSetupProfile() +{ + decl String:szGameName[30]; + GetGameFolderName(szGameName, sizeof(szGameName)); + + if (StrEqual(szGameName, "cstrike", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "tf", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "left4dead", false) || StrEqual(szGameName, "left4dead2", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 3; + CProfile_TeamIndex[Color_Blue] = 2; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "hl2mp", false)) + { + /* hl2mp profile is based on mp_teamplay convar */ + if (GetConVarBool(FindConVar("mp_teamplay"))) + { + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Red] = 3; + CProfile_TeamIndex[Color_Blue] = 2; + CProfile_SayText2 = true; + } + else + { + CProfile_SayText2 = false; + CProfile_Colors[Color_Olive] = true; + } + } + else if (StrEqual(szGameName, "dod", false)) + { + CProfile_Colors[Color_Olive] = true; + CProfile_SayText2 = false; + } + /* Profile for other games */ + else + { + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) + { + CProfile_SayText2 = false; + } + else + { + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + } +} + +public Action:CEvent_MapStart(Handle:event, const String:name[], bool:dontBroadcast) +{ + CSetupProfile(); + + for (new i = 1; i <= MaxClients; i++) + { + CSkipList[i] = false; + } +} \ No newline at end of file diff --git a/scripting/include/dhooks.inc b/scripting/include/dhooks.inc new file mode 100644 index 0000000..448be8c --- /dev/null +++ b/scripting/include/dhooks.inc @@ -0,0 +1,1015 @@ +#if defined _dhooks_included +#endinput +#endif +#define _dhooks_included + +// Needed for the SDKFuncConfSource enum. +#include + +#define INVALID_HOOK_ID -1 + +enum ObjectValueType +{ + ObjectValueType_Int = 0, + ObjectValueType_Bool, + ObjectValueType_Ehandle, + ObjectValueType_Float, + ObjectValueType_CBaseEntityPtr, + ObjectValueType_IntPtr, + ObjectValueType_BoolPtr, + ObjectValueType_EhandlePtr, + ObjectValueType_FloatPtr, + ObjectValueType_Vector, + ObjectValueType_VectorPtr, + ObjectValueType_CharPtr, + ObjectValueType_String +}; + +enum ListenType +{ + ListenType_Created, + ListenType_Deleted +}; + +enum ReturnType +{ + ReturnType_Unknown, + ReturnType_Void, + ReturnType_Int, + ReturnType_Bool, + ReturnType_Float, + ReturnType_String, //Note this is a string_t + ReturnType_StringPtr, //Note this is a string_t * + ReturnType_CharPtr, + ReturnType_Vector, + ReturnType_VectorPtr, + ReturnType_CBaseEntity, + ReturnType_Edict +}; + +enum HookParamType +{ + HookParamType_Unknown, + HookParamType_Int, + HookParamType_Bool, + HookParamType_Float, + HookParamType_String, //Note this is a string_t + HookParamType_StringPtr, //Note this is a string_t * + HookParamType_CharPtr, + HookParamType_VectorPtr, + HookParamType_CBaseEntity, + HookParamType_ObjectPtr, + HookParamType_Edict, + HookParamType_Object +}; + +enum ThisPointerType +{ + ThisPointer_Ignore, + ThisPointer_CBaseEntity, + ThisPointer_Address +}; + +enum HookType +{ + HookType_Entity, + HookType_GameRules, + HookType_Raw +}; + +enum CallingConvention +{ + CallConv_CDECL, + CallConv_THISCALL, + CallConv_STDCALL, + CallConv_FASTCALL, +}; + +enum HookMode +{ + Hook_Pre, // Callback will be executed BEFORE the original function. + Hook_Post // Callback will be executed AFTER the original function. +}; + +enum MRESReturn +{ + MRES_ChangedHandled = -2, // Use changed values and return MRES_Handled + MRES_ChangedOverride, // Use changed values and return MRES_Override + MRES_Ignored, // plugin didn't take any action + MRES_Handled, // plugin did something, but real function should still be called + MRES_Override, // call real function, but use my return value + MRES_Supercede // skip real function; use my return value +}; + +enum DHookPassFlag +{ + DHookPass_ByVal = (1<<0), /**< Passing by value */ + DHookPass_ByRef = (1<<1), /**< Passing by reference */ + DHookPass_ODTOR = (1<<2), /**< Object has a destructor */ + DHookPass_OCTOR = (1<<3), /**< Object has a constructor */ + DHookPass_OASSIGNOP = (1<<4), /**< Object has an assignment operator */ +}; + +enum DHookRegister +{ + // Don't change the register and use the default for the calling convention. + DHookRegister_Default, + + // 8-bit general purpose registers + DHookRegister_AL, + DHookRegister_CL, + DHookRegister_DL, + DHookRegister_BL, + DHookRegister_AH, + DHookRegister_CH, + DHookRegister_DH, + DHookRegister_BH, + + // 32-bit general purpose registers + DHookRegister_EAX, + DHookRegister_ECX, + DHookRegister_EDX, + DHookRegister_EBX, + DHookRegister_ESP, + DHookRegister_EBP, + DHookRegister_ESI, + DHookRegister_EDI, + + // 128-bit XMM registers + DHookRegister_XMM0, + DHookRegister_XMM1, + DHookRegister_XMM2, + DHookRegister_XMM3, + DHookRegister_XMM4, + DHookRegister_XMM5, + DHookRegister_XMM6, + DHookRegister_XMM7, + + // 80-bit FPU registers + DHookRegister_ST0 +}; + +typeset ListenCB +{ + //Deleted + function void (int entity); + + //Created + function void (int entity, const char[] classname); +}; + +typeset DHookRemovalCB +{ + function void (int hookid); +}; +typeset DHookCallback +{ + //Function Example: void Ham::Test() with this pointer ignore + function MRESReturn (); + + //Function Example: void Ham::Test() with this pointer passed + function MRESReturn (int pThis); + + //Function Example: void Ham::Test(int cake) with this pointer ignore + function MRESReturn (DHookParam hParams); + + //Function Example: void Ham::Test(int cake) with this pointer passed + function MRESReturn (int pThis, DHookParam hParams); + + //Function Example: int Ham::Test() with this pointer ignore + function MRESReturn (DHookReturn hReturn); + + //Function Example: int Ham::Test() with this pointer passed + function MRESReturn (int pThis, DHookReturn hReturn); + + //Function Example: int Ham::Test(int cake) with this pointer ignore + function MRESReturn (DHookReturn hReturn, DHookParam hParams); + + //Function Example: int Ham::Test(int cake) with this pointer passed + function MRESReturn (int pThis, DHookReturn hReturn, DHookParam hParams); + + //Address NOW + + //Function Example: void Ham::Test() with this pointer passed + function MRESReturn (Address pThis); + + //Function Example: void Ham::Test(int cake) with this pointer passed + function MRESReturn (Address pThis, DHookParam hParams); + + //Function Example: int Ham::Test() with this pointer passed + function MRESReturn (Address pThis, DHookReturn hReturn); + + //Function Example: int Ham::Test(int cake) with this pointer passed + function MRESReturn (Address pThis, DHookReturn hReturn, DHookParam hParams); + +}; + +// Represents the parameters of the hooked function. +methodmap DHookParam < Handle +{ + // Get the value of a parameter. + // Use only for: int, entity, edict, bool or float parameter types. + // + // @param num Parameter number to get, starting at 1. Parameter number 0 returns + // the number of parameters. + // + // @return Value if num greater than 0. If 0 returns parameter count. + // If CBaseEntity returns entity index. + // @error Invalid handle, invalid param number or invalid param type. + public native any Get(int num); + + // Get the value of a vector parameter. + // Use only for: vector or vectorptr parameter types. + // + // @param num Parameter number to get, starting at 1. + // @param vec Vector buffer to store result. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void GetVector(int num, float vec[3]); + + // Get the value of a string parameter. + // Use only for: string, stringptr or charptr parameter types. + // + // @param num Parameter number to get, starting at 1. + // @param buffer String buffer to store result. + // @param size Buffer size. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void GetString(int num, char[] buffer, int size); + + // Set the value of a parameter. + // Use only for: int, entity, edict, bool or float parameter types. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set starting at 1. + // @param value Value to set it as (only pass int, bool, float or entity index). + // + // @error Invalid handle, invalid param number or invalid param type. + public native void Set(int num, any value); + + // Set the value of a vector parameter. + // Use only for: vector or vectorptr parameter types. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param vec Value to set vector as. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void SetVector(int num, const float vec[3]); + + // Set the value of a string parameter. + // Use only for: string, stringptr or charptr parameter types. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param value Value to set string as. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void SetString(int num, const char[] value); + + // Gets an object's variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // + // @return Value of the objects var. If EHANDLE type or entity returns entity index. + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native any GetObjectVar(int num, int offset, ObjectValueType type); + + // Gets an object's vector variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // @param vec Buffer to store the result vector. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void GetObjectVarVector(int num, int offset, ObjectValueType type, float vec[3]); + + // Gets an object's string variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // @param buffer Buffer to store the result string. + // @param size Size of the buffer. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void GetObjectVarString(int num, int offset, ObjectValueType type, char[] buffer, int size); + + // Sets an object's variable value. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param offset Byte offset within the object to the var to set. + // @param type Type of var it is. + // @param value The value to set the var to. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void SetObjectVar(int num, int offset, ObjectValueType type, any value); + + // Sets an object's vector variable value. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param offset Byte offset within the object to the var to set. + // @param type Type of var it is. + // @param vec The value to set the vector var to. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void SetObjectVarVector(int num, int offset, ObjectValueType type, const float vec[3]); + + // No setter for object strings yet. Open an issue if you really need it. + + // Checks if a pointer parameter is null. + // + // @param num Parameter number to check, starting at 1. + // + // @return True if null, false otherwise. + // @error Non-pointer parameter. + public native bool IsNull(int num); +}; + + +// Represents the return value of the hooked function. +methodmap DHookReturn < Handle +{ + // Retrieves or sets the return value. + // Use only for: int, entity, edict, bool or float return types. + // + // The return value is only readable in a post hook. + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + property any Value { + public native get(); + public native set(any value); + } + + // Get return vector value. + // Use only for: vector or vectorptr return types. + // + // Only useful in post hooks. + // + // @param vec Vector buffer to store result in. + // + // @error Invalid Handle or invalid type. + public native void GetVector(float vec[3]); + + // Get return string value. + // Use only for: string, stringptr or charptr return types. + // + // Only useful in post hooks. + // + // @param buffer String buffer to store result in. + // @param size String buffer size. + // + // @error Invalid Handle or invalid type. + public native void GetString(char[] buffer, int size); + + // Set return vector value. + // Use only for: vector or vectorptr return types. + // + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + // + // @param vec Value to set return vector to. + // + // @error Invalid Handle or invalid type. + public native void SetVector(const float vec[3]); + + // Set return string value. + // Use only for: string, stringptr or charptr return types. + // + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + // + // @param buffer Value to set return string to. + // + // @error Invalid Handle or invalid type. + public native void SetString(const char[] buffer); +}; + +// Base method map for common functions between virtual hooks and detours. +methodmap DHookSetup < Handle +{ + // Load address or offset for a vtable hook or detour from a gamedata file. + // + // @param gameconf GameData handle. + // @param source Whether to look in Offsets, Signatures, or Addresses. + // @param name Name of the property to find. + // + // @return True on success, false if nothing was found. + // @error Invalid setup or gamedata handle. + public native bool SetFromConf(GameData gameconf, SDKFuncConfSource source, const char[] name); + + // Adds a parameter to a hook setup. + // + // @param type Parameter type. + // @param size Used for Objects (not Object ptr) to define the size of the object. + // @param flag Used to change the pass type (ignored by detours). + // @param custom_register The register this argument is passed in instead of the stack (ignored by vhooks). + // + // @error Invalid setup handle or too many params added (request upping the max in thread). + public native void AddParam(HookParamType type, int size=-1, DHookPassFlag flag=DHookPass_ByVal, DHookRegister custom_register=DHookRegister_Default); +}; + +// A DynamicHook allows to hook a virtual function on any C++ object. +// Currently CBaseEntity and CGameRules have a convenience API for easy entity hooking, +// but it's possible to provide a raw this-pointer to hook any object in memory too. +// +// Internally this intercepts function calls by replacing the function pointer +// in the virtual table of the object with our own function. +methodmap DynamicHook < DHookSetup +{ + // Creates a vtable hook. + // + // @param offset Virtual table offset of function to hook. + // @param hooktype Type of hook. + // @param returntype Type of return value. + // @param thistype Type of this pointer or ignore (ignore can be used if not needed). + // + // @error Failed to create hook setup handle or invalid callback function. + public native DynamicHook(int offset, HookType hooktype, ReturnType returntype, ThisPointerType thistype); + + // Setup a vtable hook for a function as described in a "Functions" section in gamedata. + // The "Functions" section is parsed once the gamedata file is loaded and cached globally. + // + // @param gameconf GameData handle to use for address lookup. + // Doesn't have to be the same as the one with the "Functions" section. + // @param name Name of the function in a "Functions" section to load. + // + // @return Setup handle for the detour or null if offset wasn't found. + // @error Failed to create detour setup handle, invalid gamedata handle, + // invalid callback function or failed to find function in cached "Functions" sections. + public static native DynamicHook FromConf(GameData gameconf, const char[] name); + + // Hook an entity. + // + // Entity hooks are auto-removed when the entity is destroyed. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param entity Entity index to hook on. + // @param callback Callback function. + // @param removalcb Optional callback for when the hook is removed. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookEntity(HookMode mode, int entity, DHookCallback callback, DHookRemovalCB removalcb=INVALID_FUNCTION); + + // Hook gamerules object. + // + // Game rules hooks are auto-removed on map end. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param callback Callback function. + // @param removalcb Optional callback for when the hook is removed. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookGamerules(HookMode mode, DHookCallback callback, DHookRemovalCB removalcb=INVALID_FUNCTION); + + // Hook a raw this-pointer. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param addr This pointer address. + // @param callback Callback function. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookRaw(HookMode mode, Address addr, DHookCallback callback); + + // Remove hook by hook id: + // This will NOT fire the removal callback! + // + // @param hookid Hook id to remove. + // + // @return True on success, false otherwise + public static native bool RemoveHook(int hookid); +}; + +// A DynamicDetour is a way to hook and block any function in memory. +// Given the address of a function, it can call a callback in your script whenever +// the function gets called. The callback has access to all parameters of the function +// as well as the return value. +// +// Internally this works by replacing the first instructions of the function +// with a jump to our own code. This means that the signature used to find +// the function address in the first place might not match anymore after a detour. +// If you need to detour the same function in different plugins make sure to +// wildcard \x2a the first 6 bytes of the signature to accommodate for the patched +// jump introduced by the detour. +methodmap DynamicDetour < DHookSetup +{ + // Creates a detour. + // + // @param funcaddr The address of the function to detour. + // Can be Address_Null if you want to load the address from gamedata using DHookSetFromConf. + // @param callConv Calling convention of the function. + // @param returnType Type of the return value. + // @param thisType Type of this pointer or ignore (ignore can be used if not needed). + // Only used for thiscall detours. + // + // @error Failed to create detour setup handle. + public native DynamicDetour(Address funcaddr, CallingConvention callConv, ReturnType returntype, ThisPointerType thisType=ThisPointer_Ignore); + + // Setup a detour for a function as described in a "Functions" section in gamedata. + // The "Functions" section is parsed once the gamedata file is loaded and cached globally. + // + // @param gameconf GameData handle to use for address lookup. + // Doesn't have to be the same as the one with the "Functions" section. + // @param name Name of the function in a "Functions" section to load. + // + // @return Setup handle for the detour or null if offset wasn't found. + // @error Failed to create detour setup handle, invalid gamedata handle, + // invalid callback function or failed to find function in cached "Functions" sections. + public static native DynamicDetour FromConf(GameData gameconf, const char[] name); + + // Enable the detour of the function described in this detour setup. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param callback Callback function. + // + // @return True if detour was enabled, false otherwise. + // @error Hook handle is not setup for a detour. + public native bool Enable(HookMode mode, DHookCallback callback); + + // Disable the detour of the function described in this detour setup. + // + // @param mode The hook mode to disable - pre or post. + // @param callback Callback function. + // + // @return True if detour was disabled, false otherwise. + // @error Hook handle is not setup for a detour or function is not detoured. + public native bool Disable(HookMode mode, DHookCallback callback); +}; + +/* Adds an entity listener hook + * + * @param type Type of listener to add + * @param callback Callback to use + * + * @noreturn +*/ +native void DHookAddEntityListener(ListenType type, ListenCB callback); + +/* Removes an entity listener hook + * + * @param type Type of listener to remove + * @param callback Callback this listener was using + * + * @return True if one was removed false otherwise. +*/ +native bool DHookRemoveEntityListener(ListenType type, ListenCB callback); + +/* Creates a hook + * + * @param offset vtable offset of function to hook + * @param hooktype Type of hook + * @param returntype Type of return value + * @param thistype Type of this pointer or ignore (ignore can be used if not needed) + * @param callback Optional callback function, if not set here must be set when hooking. + * + * @return Returns setup handle for the hook. + * @error Failed to create hook setup handle or invalid callback function. +*/ +native DynamicHook DHookCreate(int offset, HookType hooktype, ReturnType returntype, ThisPointerType thistype, DHookCallback callback=INVALID_FUNCTION); + +/** + * Creates a detour + * + * @param funcaddr The address of the function to detour. + * Can be Address_Null if you want to load the address from gamedata using DHookSetFromConf. + * @param callConv Calling convention of the function. + * @param returnType Type of the return value. + * @param thisType Type of this pointer or ignore (ignore can be used if not needed) + * + * @return Setup handle for the detour. + * @error Failed to create detour setup handle. + */ +native DynamicDetour DHookCreateDetour(Address funcaddr, CallingConvention callConv, ReturnType returntype, ThisPointerType thisType); + +/** + * Setup a detour or hook for a function as described in a "Functions" section in gamedata. + * + * @param gameconf GameConfig handle + * @param name Name of the function in the gamedata to load. + * + * @return Setup handle for the detour or INVALID_HANDLE if offset/signature/address wasn't found. + * @error Failed to create detour setup handle, invalid gamedata handle, invalid callback function or failed to find function in gamedata. + */ +native DHookSetup DHookCreateFromConf(Handle gameconf, const char[] name); + +/** + * Load details for a vhook or detour from a gamedata file. + * + * @param setup Hook setup handle to set the offset or address on. + * @param gameconf GameConfig handle + * @param source Whether to look in Offsets or Signatures. + * @param name Name of the property to find. + * + * @return True on success, false if nothing was found. + * @error Invalid setup or gamedata handle. + */ +native bool DHookSetFromConf(Handle setup, Handle gameconf, SDKFuncConfSource source, const char[] name); + +/** + * Enable the detour of the function described in the hook setup handle. + * + * @param setup Hook setup handle + * @param post True to make the hook a post hook. (If you need to change the retunr value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param callback Callback function + * + * @return True if detour was enabled, false otherwise. + * @error Hook handle is not setup for a detour. + */ +native bool DHookEnableDetour(Handle setup, bool post, DHookCallback callback); + +/** + * Disable the detour of the function described in the hook setup handle. + * + * @param setup Hook setup handle + * @param post True to disable a post hook. + * @param callback Callback function + * + * @return True if detour was disabled, false otherwise. + * @error Hook handle is not setup for a detour or function is not detoured. + */ +native bool DHookDisableDetour(Handle setup, bool post, DHookCallback callback); + +/* Adds param to a hook setup + * + * @param setup Setup handle to add the param to. + * @param type Param type + * @param size Used for Objects (not Object ptr) to define the size of the object. + * @param flag Used to change the pass type. + * @param custom_register The register this argument is passed in instead of the stack. + * + * @error Invalid setup handle or too many params added (request upping the max in thread) + * @noreturn +*/ +native void DHookAddParam(Handle setup, HookParamType type, int size=-1, DHookPassFlag flag=DHookPass_ByVal, DHookRegister custom_register=DHookRegister_Default); + +/* Hook entity + * + * @param setup Setup handle to use to add the hook. + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param entity Entity index to hook on. + * @param removalcb Callback for when the hook is removed (Entity hooks are auto-removed on entity destroyed and will call this callback) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + * @return INVALID_HOOK_ID on fail a hookid on success +*/ +native int DHookEntity(Handle setup, bool post, int entity, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); + +/* Hook gamerules + * + * @param setup Setup handle to use to add the hook. + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param removalcb Callback for when the hook is removed (Game rules hooks are auto-removed on map end and will call this callback) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + * @return INVALID_HOOK_ID on fail a hookid on success +*/ +native int DHookGamerules(Handle setup, bool post, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); + +/* Hook a raw pointer + * + * @param setup Setup handle to use to add the hook. + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param addr This pointer address. + * @param removalcb Callback for when the hook is removed (Entity hooks are auto-removed on entity destroyed and will call this callback) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + * @return INVALID_HOOK_ID on fail a hookid on success +*/ +native int DHookRaw(Handle setup, bool post, Address addr, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); + +/* Remove hook by hook id + * + * @param hookid Hook id to remove + * + * @return true on success false otherwise + * @note This will not fire the removal callback! +*/ +native bool DHookRemoveHookID(int hookid); + +/* Get param value (Use only for: int, entity, bool or float param types) + * + * @param hParams Handle to params structure + * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1. 0 Will return the number of params stored) + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @return value if num greater than 0. If 0 returns paramcount. +*/ +native any DHookGetParam(Handle hParams, int num); + +/* Get vector param value + * + * @param hParams Handle to params structure + * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1.) + * @param vec Vector buffer to store result. + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @noreturn +*/ +native void DHookGetParamVector(Handle hParams, int num, float vec[3]); + +/* Get string param value + * + * @param hParams Handle to params structure + * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1.) + * @param buffer String buffer to store result + * @param size Buffer size + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @noreturn +*/ +native void DHookGetParamString(Handle hParams, int num, char[] buffer, int size); + +/* Set param value (Use only for: int, entity, bool or float param types) + * + * @param hParams Handle to params structure + * @param num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) + * @param value Value to set it as (only pass int, bool, float or entity index) + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @noreturn +*/ +native void DHookSetParam(Handle hParams, int num, any value); + +/* Set vector param value + * + * @param hParams Handle to params structure + * @param num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) + * @param vec Value to set vector as. + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @noreturn +*/ +native void DHookSetParamVector(Handle hParams, int num, float vec[3]); + +/* Set string param value + * + * @param hParams Handle to params structure + * @param num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) + * @param value Value to set string as. + * + * @error Invalid handle. Invalid param number. Invalid param type. + * @noreturn +*/ +native void DHookSetParamString(Handle hParams, int num, char[] value); + +/* Get return value (Use only for: int, entity, bool or float return types) + * + * @param hReturn Handle to return structure + * + * @error Invalid Handle, invalid type. + * @return Returns default value if prehook returns actual value if post hook. +*/ +native any DHookGetReturn(Handle hReturn); + +/* Get return vector value + * + * @param hReturn Handle to return structure + * @param vec Vector buffer to store result in. (In pre hooks will be default value (0.0,0.0,0.0)) + * + * @error Invalid Handle, invalid type. + * @noreturn +*/ +native void DHookGetReturnVector(Handle hReturn, float vec[3]); + +/* Get return string value + * + * @param hReturn Handle to return structure + * @param buffer String buffer to store result in. (In pre hooks will be default value "") + * @param size String buffer size + * + * @error Invalid Handle, invalid type. + * @noreturn +*/ +native void DHookGetReturnString(Handle hReturn, char[] buffer, int size); + +/* Set return value (Use only for: int, entity, bool or float return types) + * + * @param hReturn Handle to return structure + * @param value Value to set return as + * + * @error Invalid Handle, invalid type. + * @noreturn +*/ +native void DHookSetReturn(Handle hReturn, any value); + +/* Set return vector value + * + * @param hReturn Handle to return structure + * @param vec Value to set return vector as + * + * @error Invalid Handle, invalid type. + * @noreturn +*/ +native void DHookSetReturnVector(Handle hReturn, float vec[3]); + +/* Set return string value + * + * @param hReturn Handle to return structure + * @param value Value to set return string as + * + * @error Invalid Handle, invalid type. + * @noreturn +*/ +native void DHookSetReturnString(Handle hReturn, char[] value); + +//WE SHOULD WRAP THESE AROUND STOCKS FOR NON PTR AS WE SUPPORT BOTH WITH THESE NATIVE'S + +/* Gets an objects variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @return Value of the objects var. If EHANDLE type or entity returns entity index. +*/ +native any DHookGetParamObjectPtrVar(Handle hParams, int num, int offset, ObjectValueType type); + +/* Sets an objects variable value + * + * @param hParams Handle to params structure + * @param num Param number to set. + * @param offset Offset within the object to the var to set. + * @param type Type of var it is + * @param value The value to set the var to. + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @noreturn +*/ +native void DHookSetParamObjectPtrVar(Handle hParams, int num, int offset, ObjectValueType type, any value); + +/* Gets an objects vector variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * @param buffer Buffer to store the result vector + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @noreturn +*/ +native void DHookGetParamObjectPtrVarVector(Handle hParams, int num, int offset, ObjectValueType type, float buffer[3]); + +/* Sets an objects vector variable value + * + * @param hParams Handle to params structure + * @param num Param number to set. + * @param offset Offset within the object to the var to set. + * @param type Type of var it is + * @param value The value to set the vector var to. + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @noreturn +*/ +native void DHookSetParamObjectPtrVarVector(Handle hParams, int num, int offset, ObjectValueType type, float value[3]); + +/* Gets an objects string variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * @param buffer Buffer to store the result vector + * @param size Size of the buffer + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @noreturn +*/ +native void DHookGetParamObjectPtrString(Handle hParams, int num, int offset, ObjectValueType type, char[] buffer, int size); + +/* Checks if a pointer param is null + * + * @param hParams Handle to params structure + * @param num Param number to check. + * + * @error Non pointer param + * @return True if null false otherwise. +*/ +native bool DHookIsNullParam(Handle hParams, int num); + +public Extension __ext_dhooks = +{ + name = "dhooks", + file = "dhooks.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_EXTENSIONS +public __ext_dhooks_SetNTVOptional() +{ + MarkNativeAsOptional("DHookAddEntityListener"); + MarkNativeAsOptional("DHookRemoveEntityListener"); + MarkNativeAsOptional("DHookCreate"); + MarkNativeAsOptional("DHookCreateDetour"); + MarkNativeAsOptional("DHookCreateFromConf"); + MarkNativeAsOptional("DHookSetFromConf"); + MarkNativeAsOptional("DHookEnableDetour"); + MarkNativeAsOptional("DHookDisableDetour"); + MarkNativeAsOptional("DHookAddParam"); + MarkNativeAsOptional("DHookEntity"); + MarkNativeAsOptional("DHookGamerules"); + MarkNativeAsOptional("DHookRaw"); + MarkNativeAsOptional("DHookRemoveHookID"); + MarkNativeAsOptional("DHookGetParam"); + MarkNativeAsOptional("DHookGetParamVector"); + MarkNativeAsOptional("DHookGetParamString"); + MarkNativeAsOptional("DHookSetParam"); + MarkNativeAsOptional("DHookSetParamVector"); + MarkNativeAsOptional("DHookSetParamString"); + MarkNativeAsOptional("DHookGetReturn"); + MarkNativeAsOptional("DHookGetReturnVector"); + MarkNativeAsOptional("DHookGetReturnString"); + MarkNativeAsOptional("DHookSetReturn"); + MarkNativeAsOptional("DHookSetReturnVector"); + MarkNativeAsOptional("DHookSetReturnString"); + MarkNativeAsOptional("DHookGetParamObjectPtrVar"); + MarkNativeAsOptional("DHookSetParamObjectPtrVar"); + MarkNativeAsOptional("DHookGetParamObjectPtrVarVector"); + MarkNativeAsOptional("DHookSetParamObjectPtrVarVector"); + MarkNativeAsOptional("DHookIsNullParam"); + MarkNativeAsOptional("DHookGetParamObjectPtrString"); + + MarkNativeAsOptional("DHookParam.IsNull"); + MarkNativeAsOptional("DHookParam.Get"); + MarkNativeAsOptional("DHookParam.GetVector"); + MarkNativeAsOptional("DHookParam.GetString"); + MarkNativeAsOptional("DHookParam.Set"); + MarkNativeAsOptional("DHookParam.SetVector"); + MarkNativeAsOptional("DHookParam.SetString"); + MarkNativeAsOptional("DHookParam.GetObjectVar"); + MarkNativeAsOptional("DHookParam.GetObjectVarVector"); + MarkNativeAsOptional("DHookParam.GetObjectVarString"); + MarkNativeAsOptional("DHookParam.SetObjectVar"); + MarkNativeAsOptional("DHookParam.SetObjectVarVector"); + MarkNativeAsOptional("DHookReturn.Value.get"); + MarkNativeAsOptional("DHookReturn.Value.set"); + MarkNativeAsOptional("DHookReturn.GetVector"); + MarkNativeAsOptional("DHookReturn.GetString"); + MarkNativeAsOptional("DHookReturn.SetVector"); + MarkNativeAsOptional("DHookReturn.SetString"); + MarkNativeAsOptional("DHookSetup.SetFromConf"); + MarkNativeAsOptional("DHookSetup.AddParam"); + MarkNativeAsOptional("DynamicHook.DynamicHook"); + MarkNativeAsOptional("DynamicHook.FromConf"); + MarkNativeAsOptional("DynamicHook.HookEntity"); + MarkNativeAsOptional("DynamicHook.HookGamerules"); + MarkNativeAsOptional("DynamicHook.HookRaw"); + MarkNativeAsOptional("DynamicHook.RemoveHook"); + MarkNativeAsOptional("DynamicDetour.DynamicDetour"); + MarkNativeAsOptional("DynamicDetour.FromConf"); + MarkNativeAsOptional("DynamicDetour.Enable"); + MarkNativeAsOptional("DynamicDetour.Disable"); +} +#endif \ No newline at end of file diff --git a/scripting/include/epi/director.sp b/scripting/include/epi/director.sp new file mode 100644 index 0000000..99b22b0 --- /dev/null +++ b/scripting/include/epi/director.sp @@ -0,0 +1,521 @@ +// SETTINGS +// TODO: make cvars +#define DIRECTOR_TIMER_INTERVAL 3.0 +#define DIRECTOR_WITCH_MIN_TIME 120 // The minimum amount of time to pass since last witch spawn for the next extra witch to spawn +#define DIRECTOR_WITCH_CHECK_TIME 30.0 // How often to check if a witch should be spawned +#define DIRECTOR_WITCH_MAX_WITCHES 5 // The maximum amount of extra witches to spawn +#define DIRECTOR_WITCH_ROLLS 3 // The number of dice rolls, increase if you want to increase freq +#define DIRECTOR_MIN_SPAWN_TIME 13.0 // Possibly randomized, per-special +#define DIRECTOR_SPAWN_CHANCE 0.04 // The raw chance of a spawn +#define DIRECTOR_CHANGE_LIMIT_CHANCE 0.05 // The chance that the maximum amount per-special is changed +#define DIRECTOR_SPECIAL_TANK_CHANCE 0.05 // The chance that specials can spawn when a tank is active +#define DIRECTOR_STRESS_CUTOFF 0.75 // The minimum chance a random cut off stress value is chosen [this, 1.0] +#define DIRECTOR_REST_CHANCE 0.04 // The chance the director ceases spawning +#define DIRECTOR_REST_MAX_COUNT 8 // The maximum amount of rest given (this * DIRECTOR_TIMER_INTERVAL) + +#define DIRECTOR_DEBUG_SPAWN 1 // Dont actually spawn + +/// DEFINITIONS +#define NUM_SPECIALS 6 +#define TOTAL_NUM_SPECIALS 8 +char SPECIAL_IDS[TOTAL_NUM_SPECIALS][] = { + "smoker", + "boomer", + "hunter", + "spitter", + "jockey", + "charger", + "witch", + "tank" +}; +enum specialType { + Special_Smoker = 0, + Special_Boomer = 1, + Special_Hunter = 2, + Special_Spitter = 3, + Special_Jockey = 4, + Special_Charger = 5, + Special_Witch = 6, + Special_Tank = 7, +}; +enum directorState { + DState_Normal, + DState_NoPlayersOrNotCoop, + DState_PendingMinFlowOrDisabled, + DState_MaxSpecialTime, + DState_PlayerChance, + DState_Resting, + DState_TankInPlay, + DState_HighStress, + DState_MaxDirectorSpecials, +} +char DIRECTOR_STATE[9][] = { + "normal", + "no players / not coop", + "pending minflow OR disabled", + "max special in window", + "player scaled chance", + "rest period", + "tank in play", + "high stress", + "director MaxSpecials" +}; +static directorState g_lastState; + +static float g_highestFlowAchieved; +static float g_lastSpawnTime[TOTAL_NUM_SPECIALS]; +static float g_lastSpecialSpawnTime; // for any special +static int g_spawnLimit[TOTAL_NUM_SPECIALS]; +static int g_spawnCount[TOTAL_NUM_SPECIALS]; +static int gd_maxSpecials; +static float g_minFlowSpawn; // The minimum flow for specials to start spawning (waiting for players to leave saferom) +static float g_maxStressIntensity; // The max stress that specials arent allowed to spawn + +int g_extraWitchCount; +static int g_infectedCount; +int g_restCount; +static Handle witchSpawnTimer = null; + +float g_extraWitchFlowPositions[DIRECTOR_WITCH_MAX_WITCHES] = {}; + +/// EVENTS + +void Director_OnMapStart() { + // Only spawn witches if enabled, and not loate loaded + if(!g_isLateLoaded && cvEPISpecialSpawning.IntValue & 2 && IsEPIActive()) { + InitExtraWitches(); + } + float time = GetGameTime(); + for(int i = 0; i < TOTAL_NUM_SPECIALS; i++) { + g_lastSpawnTime[i] = time; + g_spawnLimit[i] = 1; + g_spawnCount[i] = 0; + } + g_highestFlowAchieved = 0.0; + g_lastSpecialSpawnTime = time; + g_infectedCount = 0; + g_restCount = 0; + Director_RandomizeThings(); +} + +void Director_OnMapEnd() { + for(int i = 0; i < DIRECTOR_WITCH_MAX_WITCHES; i++) { + g_extraWitchFlowPositions[i] = 0.0; + } + delete witchSpawnTimer; +} + +void Cvar_SpecialSpawningChange(ConVar convar, const char[] oldValue, const char[] newValue) { + if(convar.IntValue & 2) { + if(witchSpawnTimer == null) + witchSpawnTimer = CreateTimer(DIRECTOR_WITCH_CHECK_TIME, Timer_DirectorWitch, _, TIMER_REPEAT); + } else { + delete witchSpawnTimer; + } +} + +void Event_WitchSpawn(Event event, const char[] name, bool dontBroadcast) { + g_spawnCount[Special_Witch]++; +} +void Director_OnClientPutInServer(int client) { + // Wait a frame for the bot to be assigned a team + RequestFrame(Director_CheckClient, client); +} +void Director_CheckClient(int client) { + if(IsClientConnected(client) && GetClientTeam(client) == 3) { + // To bypass director limits many plugins spawn an infected "bot" that immediately gets kicked, which allows a window to spawn a special + // The fake bot's class is usually 9, an invalid + int class = GetEntProp(client, Prop_Send, "m_zombieClass") - 1; + if(class > view_as(Special_Tank)) { + return; + } else if(IsFakeClient(client)) { + // Sometimes the bot class is _not_ invalid, but usually has BOT in its name. Ignore those players. + char name[32]; + GetClientName(client, name, sizeof(name)); + if(StrContains(name, "bot", false) != -1) { + return; + } + } + + if(IsFakeClient(client) && class == view_as(Special_Tank)) { + OnTankBotSpawn(client); + } + + g_spawnCount[class]++; + float time = GetGameTime(); + g_lastSpawnTime[class] = time; + g_lastSpecialSpawnTime = time; + g_infectedCount++; + + } +} + +static int g_newTankHealth = 0; +void OnTankBotSpawn(int client) { + if(!IsEPIActive() || !(cvEPISpecialSpawning.IntValue & 4)) return; + // Check if any finale is active + if(g_newTankHealth > 0) { + // A split tank has spawned, set its health + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: split tank spawned, setting health to %d", g_newTankHealth); + SetEntProp(client, Prop_Send, "m_iHealth", g_newTankHealth); + g_newTankHealth = 0; + return; + } else if(g_realSurvivorCount >= hExtraTankThreshold.IntValue && g_extraFinaleTankEnabled && hExtraFinaleTank.IntValue > 1) { + // If we have hExtraTankThreshold or more and finale tanks enabled, spawn finale tanks: + if(g_finaleStage == Stage_Active) { + // 1st tank spawned + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: [FINALE] 1st tank spawned"); + int health = CalculateExtraTankHealth(client); + SetEntProp(client, Prop_Send, "m_iHealth", health); + g_finaleStage = Stage_FirstTankSpawned; + return; + } else if(g_realSurvivorCount < 6 && g_finaleStage == Stage_FirstTankSpawned) { + // 2nd tank spawned + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: [FINALE] 2nd tank spawned"); + float duration = GetRandomFloat(EXTRA_TANK_MIN_SEC, EXTRA_TANK_MAX_SEC); + // Pass it 0, which doesnt make it a split tank, has default health + CreateTimer(duration, Timer_SpawnSplitTank, 0); + int health = CalculateExtraTankHealth(client); + SetEntProp(client, Prop_Send, "m_iHealth", health); + g_finaleStage = Stage_SecondTankSpawned; + return; + } + } + + // End finale logic: + if(g_finaleStage == Stage_SecondTankSpawned) { + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: [FINALE] Health set, tank logic done"); + g_finaleStage = Stage_ActiveDone; + // We don't return, letting the 2nd 5+ finale tank get buffed: + } + // This should not run on active finales (different than finale maps, such as swamp fever's, where finale isnt full map) + // Normal tank (not stage 2 / not secondary tank) spawned. Set its health and spawn split tank + int health = CalculateExtraTankHealth(client); + + /* Split tank can only spawn if: + (1) not finale + (2) over threshold hExtraTankThreshold + (3) split tanks enabled + (4) random chance set by hSplitTankChance + Otherwise, just scale health based on survivor count + */ + if(g_finaleStage == Stage_Inactive && g_realSurvivorCount >= hExtraTankThreshold.IntValue && hExtraFinaleTank.IntValue & 1 && GetURandomFloat() <= hSplitTankChance.FloatValue) { + float duration = GetRandomFloat(EXTRA_TANK_MIN_SEC, EXTRA_TANK_MAX_SEC); + int splitHealth = health / 2; + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: split tank in %.1fs, health=%d", duration, splitHealth); + CreateTimer(duration, Timer_SpawnSplitTank, splitHealth); + SetEntProp(client, Prop_Send, "m_iHealth", splitHealth); + } else { + PrintDebug(DEBUG_SPAWNLOGIC, "OnTankBotSpawn: Setting tank health to %d", health); + SetEntProp(client, Prop_Send, "m_iHealth", health); + } +} + +int CalculateExtraTankHealth(int client) { + int health = GetEntProp(client, Prop_Send, "m_iHealth"); + float additionalHealth = float(g_survivorCount - 4) * cvEPITankHealth.FloatValue; + health += RoundFloat(additionalHealth); + return health; +} + +Action Timer_SpawnSplitTank(Handle h, int health) { + PrintDebug(DEBUG_SPAWNLOGIC, "Timer_SpawnSplitTank(%d)", health); + g_newTankHealth = health; + DirectorSpawn(Special_Tank); + return Plugin_Handled; +} + +void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + int team = GetClientTeam(client); + if(team == 3) { + int class = GetEntProp(client, Prop_Send, "m_zombieClass") - 1; + if(class > view_as(Special_Tank)) return; + g_spawnCount[class]--; + if(g_spawnCount[class] < 0) { + g_spawnCount[class] = 0; + } + g_infectedCount--; + if(g_infectedCount < 0) { + g_infectedCount = 0; + } + } else if(team == 2) { + TryGrantRest(); + } + } +} + +void Event_PlayerIncapped(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && GetClientTeam(client) == 2) { + TryGrantRest(); + } +} + +/// METHODS + + +/* +Extra Witch Algo: +On map start, knowing # of total players, compute a random number of witches. +The random number calculated by DiceRoll with 2 rolls and biased to the left. [min, 6] +The minimum number in the dice is shifted to the right by the # of players (abmExtraCount-4)/4 (1 extra=0, 10 extra=2) + +Then, with the # of witches, as N, calculate N different flow values between [0, L4D2Direct_GetMapMaxFlowDistance()] +Timer_Director then checks if highest flow achieved (never decreases) is >= each flow value, if one found, a witch is spawned +(the witch herself is not spawned at the flow, just her spawning is triggered) +*/ +void InitExtraWitches() { + float flowMax = L4D2Direct_GetMapMaxFlowDistance() - FLOW_CUTOFF; + // Just in case we don't have max flow or the map is extremely tiny, don't run: + if(flowMax > 0.0) { + int count = g_survivorCount; + if(count < 4) count = 4; + // Calculate the number of witches we want to spawn. + // We bias the dice roll to the right. We slowly increase min based on player count to shift distribution to the right + int min = RoundToFloor(float(count - 5) / 4.0); + int max = RoundToFloor(float(count) / 4.0); + + // TODO: inc chance based on map max flow + g_extraWitchCount = DiceRoll(min, DIRECTOR_WITCH_MAX_WITCHES, DIRECTOR_WITCH_ROLLS, BIAS_LEFT); + PrintDebug(DEBUG_SPAWNLOGIC, "InitExtraWitches: %d witches (min=%d, max=%d, rolls=%d) checkInterval=%f", g_extraWitchCount, min, max, DIRECTOR_WITCH_ROLLS, DIRECTOR_WITCH_CHECK_TIME); + for(int i = 0; i < g_extraWitchCount; i++) { + g_extraWitchFlowPositions[i] = GetURandomFloat() * (flowMax-FLOW_CUTOFF) + FLOW_CUTOFF; + PrintDebug(DEBUG_SPAWNLOGIC, "Witch position #%d: flow %.2f (%.0f%%)", i, g_extraWitchFlowPositions[i], g_extraWitchFlowPositions[i] / flowMax); + } + witchSpawnTimer = CreateTimer(DIRECTOR_WITCH_CHECK_TIME, Timer_DirectorWitch, _, TIMER_REPEAT); + } + // TODO: spawn them early instead +} + +void Director_PrintDebug(int client) { + PrintToConsole(client, "State: %s(%d)", DIRECTOR_STATE[g_lastState], g_lastState); + float eCount = float(g_survivorCount - 3); + float chance = (eCount - float(g_infectedCount)) / eCount; + PrintToConsole(client, "Player Scale Chance: %f%%", chance * 100.0); + PrintToConsole(client, "Map Bounds: [%f, %f]", FLOW_CUTOFF, L4D2Direct_GetMapMaxFlowDistance() - (FLOW_CUTOFF*2.0)); + PrintToConsole(client, "Total Witches Spawned: %d | Target: %d", g_spawnCount[Special_Witch], g_extraWitchCount); + for(int i = 0; i < g_extraWitchCount && i < DIRECTOR_WITCH_MAX_WITCHES; i++) { + PrintToConsole(client, "%d. %f", i+1, g_extraWitchFlowPositions[i]); + } + PrintToConsole(client, "highestFlow = %f, g_minFlowSpawn = %f, current flow = %f", g_highestFlowAchieved, g_minFlowSpawn, L4D2Direct_GetFlowDistance(client)); + PrintToConsole(client, "g_maxStressIntensity = %f, current avg = %f", g_maxStressIntensity, L4D_GetAvgSurvivorIntensity()); + PrintToConsole(client, "TankInPlay=%b, FinaleStage=%d, FinaleEscapeReady=%b, DirectorTankCheck:%b", L4D2_IsTankInPlay(), g_finaleStage, g_isFinaleEnding, L4D2_IsTankInPlay() && !g_isFinaleEnding); + char buffer[128]; + float time = GetGameTime(); + PrintToConsole(client, "Last Spawn Deltas: (%.1f s) (min %f)", time - g_lastSpecialSpawnTime, DIRECTOR_MIN_SPAWN_TIME); + for(int i = 0; i < TOTAL_NUM_SPECIALS; i++) { + Format(buffer, sizeof(buffer), "%s %s=%.1f", buffer, SPECIAL_IDS[i], time-g_lastSpawnTime[i]); + } + PrintToConsole(client, "\t%s", buffer); + buffer[0] = '\0'; + PrintToConsole(client, "Spawn Counts: (%d/%d)", g_infectedCount, g_survivorCount - 4); + for(int i = 0; i < TOTAL_NUM_SPECIALS; i++) { + Format(buffer, sizeof(buffer), "%s %s=%d/%d", buffer, SPECIAL_IDS[i], g_spawnCount[i], g_spawnLimit[i]); + } + PrintToConsole(client, "\t%s", buffer); + PrintToConsole(client, "timer interval=%.0f, rest count=%d, rest time left=%.0fs", DIRECTOR_TIMER_INTERVAL, g_restCount, float(g_restCount) * DIRECTOR_TIMER_INTERVAL); +} + +void Director_RandomizeLimits() { + // We add +1 to spice it up + int max = RoundToCeil(float(g_survivorCount - 4) / 4) + 1; + for(int i = 0; i < NUM_SPECIALS; i++) { + g_spawnLimit[i] = GetRandomInt(0, max); + // PrintDebug(DEBUG_SPAWNLOGIC, "new spawn limit (special=%d, b=[0,%d], limit=%d)", i, max, g_spawnLimit[i]); + } + gd_maxSpecials = L4D2_GetScriptValueInt("MaxSpecials", 0); +} +void Director_RandomizeThings() { + g_maxStressIntensity = GetRandomFloat(DIRECTOR_STRESS_CUTOFF, 1.0); + g_minFlowSpawn = GetRandomFloat(500.0 + FLOW_CUTOFF, FLOW_CUTOFF * 2); + Director_RandomizeLimits(); +} + +bool Director_ShouldRest() { + if(g_restCount > 0) { + g_restCount--; + return true; + } + TryGrantRest(); + return false; +} + +void TryGrantRest() { + if(GetURandomFloat() <= DIRECTOR_REST_CHANCE) { + g_restCount = GetRandomInt(0, DIRECTOR_REST_MAX_COUNT); + } +} + +// Little hacky, need to track when one leaves instead +void Director_CheckSpawnCounts() { + if(!IsEPIActive()) return; + for(int i = 0; i < TOTAL_NUM_SPECIALS; i++) { + g_spawnCount[i] = 0; + } + g_infectedCount = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientInGame(i) && GetClientTeam(i) == 3) { + int class = GetEntProp(i, Prop_Send, "m_zombieClass") - 1; // make it 0-based + if(class > view_as(Special_Tank)) continue; + g_spawnCount[class]++; + g_infectedCount++; + } + } +} + +/// TIMERS + +// TODO: maybe make specials spaw nmore during horde events (alarm car, etc) +// less during calms, making that the automatic rest periods? +directorState Director_Think() { + if(!IsEPIActive()) return DState_NoPlayersOrNotCoop; + float time = GetGameTime(); + + // Calculate the new highest flow + int highestPlayer = L4D_GetHighestFlowSurvivor(); + if(highestPlayer <= 0) return DState_NoPlayersOrNotCoop; + float flow = L4D2Direct_GetFlowDistance(highestPlayer); + if(flow > g_highestFlowAchieved) { + g_highestFlowAchieved = flow; + } + + + // Only run once until: + // A. They reach minimum flow (little past start saferoom) + // B. Under the total limited (equal to player count) + // C. Special spawning is enabled + gd_maxSpecials = L4D2_GetScriptValueInt("MaxSpecials", 0); + if(gd_maxSpecials <= 0) return DState_MaxDirectorSpecials; + if( ~cvEPISpecialSpawning.IntValue & 1 || !L4D_HasAnySurvivorLeftSafeArea() || g_highestFlowAchieved < g_minFlowSpawn) return DState_PendingMinFlowOrDisabled; + + // Check if a rest period is given + if(Director_ShouldRest()) { + return DState_Resting; + } + + // Only spawn more than one special within 2s at 10% + // TODO: randomized time between spawns? 0, ?? instead of repeat timer? + if(time - g_lastSpecialSpawnTime < 1.0 && GetURandomFloat() > 0.45) return DState_MaxSpecialTime; + + if(GetURandomFloat() < DIRECTOR_CHANGE_LIMIT_CHANCE) { + Director_RandomizeLimits(); + } + + // Decrease chance of spawning based on how close to infected count + // abmExtraCount=6 g_infectedCount=0 chance=1.0 ((abmExtraCount-g_infectedCount)/abmExtraCount) + // abmExtraCount=6 g_infectedCount=1 chance=0.9 ((6-1)/6)) = (5/6) + // abmExtraCount=6 g_infectedCount=6 chance=0.2 + // TODO: in debug calculate this + float eCount = float(g_survivorCount - 3); + float chance = (eCount - float(g_infectedCount)) / eCount; + // TODO: verify (abmExtraCount-4) + if(GetURandomFloat() > chance) return DState_PlayerChance; + + + float curAvgStress = L4D_GetAvgSurvivorIntensity(); + // Don't spawn specials when tanks active, but have a small chance (DIRECTOR_SPECIAL_TANK_CHANCE) to bypass + if((L4D2_IsTankInPlay() && !g_isFinaleEnding) && GetURandomFloat() > DIRECTOR_SPECIAL_TANK_CHANCE) { + return DState_TankInPlay; + } else if(curAvgStress >= g_maxStressIntensity) { + // Stop spawning when players are stressed from a random value chosen by [DIRECTOR_STRESS_CUTOFF, 1.0] + return DState_HighStress; + } + // Scale the chance where stress = 0.0, the chance is 50% more, and stress = 1.0, the chance is 50% less + float spawnChance = DIRECTOR_SPAWN_CHANCE + ((0.5 - curAvgStress) / 10.0); + for(int i = 0; i < NUM_SPECIALS; i++) { + specialType special = view_as(i); + // Skip if we hit our limit, or too soon: + if(g_spawnCount[i] >= g_spawnLimit[i]) continue; + if(time - g_lastSpawnTime[i] < DIRECTOR_MIN_SPAWN_TIME) continue; + + if(GetURandomFloat() <= spawnChance) { + DirectorSpawn(special); + } + } + + return DState_Normal; +} + +Action Timer_Director(Handle h) { + g_lastState = Director_Think(); + return Plugin_Continue; +} + + +Action Timer_DirectorWitch(Handle h) { + // TODO: instead of +1, do it when director spawned a witch + if(!IsEPIActive()) return Plugin_Continue; + if(g_spawnCount[Special_Witch] < g_extraWitchCount + 1) { //&& time - g_lastSpawnTimes.witch > DIRECTOR_WITCH_MIN_TIME + for(int i = 0; i <= g_extraWitchCount; i++) { + if(g_extraWitchFlowPositions[i] > 0.0 && g_highestFlowAchieved >= g_extraWitchFlowPositions[i]) { + // Reset the flow so we don't spawn another + g_extraWitchFlowPositions[i] = 0.0; + int target = L4D_GetHighestFlowSurvivor(); + if(!target) return Plugin_Continue; + DirectorSpawn(Special_Witch, target); + return Plugin_Continue; + } + } + } + witchSpawnTimer = null; + return Plugin_Stop; +} + +// UTIL functions +void DirectorSpawn(specialType special, int player = -1) { + if(player <= 0) + player = GetSuitableVictim(); + if(special != Special_Witch && special != Special_Tank) { + // Bypass director + int bot = CreateFakeClient("EPI_BOT"); + if (bot != 0) { + ChangeClientTeam(bot, 3); + CreateTimer(0.1, Timer_Kick, bot); + } + } + float pos[3]; + if(L4D_GetRandomPZSpawnPosition(player, view_as(special) + 1, 10, pos)) { + // They use 1-index + if(special == Special_Tank) { + L4D2_SpawnTank(pos, NULL_VECTOR); + } else { + L4D2_SpawnSpecial(view_as(special) + 1, pos, NULL_VECTOR); + } + } +} + +// Finds a player that is suitable (lowest intensity) +// TODO: biased random (lower intensity : bias) +// dice roll, #sides = #players, sort list of players by intensity +// then use biased left dice, therefore lower intensity = higher random weight +int g_iLastVictim; +int GetSuitableVictim() { + // TODO: randomize? + return GetRandomSurvivor(1, -1); + // ArrayList survivors = new ArrayList(2); + // for(int i = 1; i <= MaxClients; i++) { + // if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + // int index = survivors.Push(i); + // survivors.Set(index, 1, L4D_GetPlayerIntensity(i)); + // } + // } + // // Soe + // survivors.SortCustom() + + int victim = -1; + float lowestIntensity = 0.0; + for(int i = 1; i <= MaxClients; i++) { + if(g_iLastVictim != i && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + float intensity = L4D_GetPlayerIntensity(i); + // TODO: possibly add perm health into calculations + if(intensity < lowestIntensity || victim == -1) { + lowestIntensity = intensity; + victim = i; + } + } + } + g_iLastVictim = victim; + return victim; +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls.inc b/scripting/include/feedthetrolls.inc new file mode 100644 index 0000000..7af8ceb --- /dev/null +++ b/scripting/include/feedthetrolls.inc @@ -0,0 +1,18 @@ +#if defined _ftt_included_ + #endinput +#endif +#define _ftt_included_ + + +enum TrollModifier { + TrollMod_Invalid = 0, + TrollMod_Instant = 1 << 0, + TrollMod_Constant = 1 << 1, + TrollMod_PlayerOnly = 1 << 2, // Does the troll only work on players, not bots? If set, troll only applied on real user. If not, troll applied to both bot and idler +} + +native void ApplyTroll(int victim, const char[] name, TrollModifier modifier = TrollMod_Invalid, int flags, int activator, bool silent = false); + +forward void OnTrollApplied(int victim, const char[] trollName, int flags = 0, int activator = 0); + +forward void OnTrollMarked(int activator, int victim); \ No newline at end of file diff --git a/scripting/include/feedthetrolls/base.inc b/scripting/include/feedthetrolls/base.inc new file mode 100644 index 0000000..cc3a067 --- /dev/null +++ b/scripting/include/feedthetrolls/base.inc @@ -0,0 +1,507 @@ + +#define MAX_TROLL_NAME_LENGTH 32 +#define MAX_TROLL_FLAG_LENGTH 32 +//Allow MAX_TROLLS to be defined elsewhere +#if defined MAX_TROLLS +#else + #define MAX_TROLLS 55 +#endif + +enum trollModifier { + TrollMod_Invalid = 0, + TrollMod_Instant = 1 << 0, + TrollMod_Constant = 1 << 1, + TrollMod_PlayerOnly = 1 << 2, // Does the troll only work on players, not bots? If set, troll only applied on real user. If not, troll applied to both bot and idler +} + +enum TrollEffectResponse { + TE_Success, // Success, continue menu + TE_Error, // Error, continue menu (retry) + TE_Menu // Switching menus / etc, don't continue menu +} + +StringMap trollKV; +char trollIds[MAX_TROLLS+1][MAX_TROLL_NAME_LENGTH]; +char DEFAULT_FLAG_PROMPT_MULTIPLE[] = "Enable options (Multiple)"; +char DEFAULT_FLAG_PROMPT[] = "Select an option"; +bool SilentMenuSelected[MAXPLAYERS+1]; + +static int g_trollAddPromptIndex; +ArrayList gRandomClients; + +char SPECIAL_NAMES[][] = { + "Smoker", "Boomer", "Hunter", "Spitter", "Jockey", "Charger", "Witch", "Tank" +}; + +enum struct TrollFlagPrompt { + char promptText[MAX_TROLL_FLAG_LENGTH]; + int flags; + int defaults; + bool multiselect; + int requireFlags; + + void GetPromptText(char[] prompt, int maxlength) { + if(this.promptText[0] != '\0') { + strcopy(prompt, maxlength, this.promptText); + } else if(this.multiselect) { + strcopy(prompt, maxlength, DEFAULT_FLAG_PROMPT_MULTIPLE); + } else { + strcopy(prompt, maxlength, DEFAULT_FLAG_PROMPT); + } + } +} + + +// Very hacky but map a power (say 16, 32) to the index in a list +// Used to get the name of a flag (flag #16 for example) in ArrayList of flag names +int GetIndexFromPower(int powerOfTwo) { + for(int i = 0; i < 16; i++) { + if(1 << i == powerOfTwo) { + return i; + } + } + return -1; +} + +enum struct Troll { + int id; // The id or the index into the global Trolls[] array + int categoryID; // The category this troll belongs in + + char name[MAX_TROLL_NAME_LENGTH]; + char description[128]; + bool hidden; + + int mods; // Combination of valid modifiers. Only two are ever supported + + // Flags + int activeFlagClients[MAXPLAYERS+1]; + ArrayList flagNames; + ArrayList flagPrompts; + + // Custom timer + Timer timerFunction; + Handle timerHandles[MAXPLAYERS+1]; + float timerInterval; + int timerRequiredFlags; + + void SetTimer(float interval, Timer timer, int requiredFlags = 0) { + this.timerInterval = interval; + this.timerFunction = timer; + this.timerRequiredFlags = requiredFlags; + for(int i = 0; i <= MAXPLAYERS; i++) { + this.timerHandles[i] = null; + } + } + + bool HasMod(trollModifier mod) { + return ((this.mods >> (view_as(mod)) - 1) & 1) == 1; + } + + // Gets the default modifier to use + trollModifier GetDefaultMod() { + // If the flags is equal to the 2^n flag, then it must be the only flag: + if(this.mods == view_as(TrollMod_Instant)) return TrollMod_Instant; + else if(this.mods == view_as(TrollMod_Constant)) return TrollMod_Constant; + else return TrollMod_Invalid; + } + +/////// FLAGS + + bool GetFlagName(int index, char[] buffer, int maxlength) { + if(this.flagNames == null || index >= this.flagNames.Length) return false; + this.flagNames.GetString(index, buffer, maxlength); + return true; + } + + bool GetFlagNames(int client, char[] output, int maxlength) { + if(this.flagNames == null) return false; + char buffer[16]; + for(int i = 0; i < this.flagNames.Length; i++) { + int value = 1 << i; + // If client has this flag: + if(this.activeFlagClients[client] & value) { + this.flagNames.GetString(i, buffer, sizeof(buffer)); + Format(output, maxlength, "%s%s,", output, buffer); + } + } + return true; + } + + int AddCustomFlagPrompt(const char[] promptText, bool multiselect = false, int requireFlags = 0) { + TrollFlagPrompt prompt; + prompt.multiselect = multiselect; + prompt.requireFlags = requireFlags; + strcopy(prompt.promptText, MAX_TROLL_FLAG_LENGTH, promptText); + int index = this.flagPrompts.PushArray(prompt); + g_trollAddPromptIndex = index; + return index; + } + + int AddFlagPrompt(bool multiselect = false, int requireFlags = 0) { + //g_trollAddPromptIndex + TrollFlagPrompt prompt; + prompt.multiselect = multiselect; + prompt.requireFlags = requireFlags; + int index = this.flagPrompts.PushArray(prompt); + g_trollAddPromptIndex = index; + return index; + } + + int AddFlag(const char[] name, bool defaultOn) { + if(this.flagNames == null) { + this.flagNames = new ArrayList(MAX_TROLL_FLAG_LENGTH); + } + + // Check if flag already added + int flagIndex = this.GetFlagIndex(name); + if(flagIndex == -1) flagIndex = this.flagNames.PushString(name); + + // Grab the prompt + static TrollFlagPrompt prompt; + // TODO: CHECK IF MISSING PROMPT + if(g_trollAddPromptIndex >= this.flagPrompts.Length) { + ThrowError("No prompt added for troll \"%s\", for flag \"%s\"", this.id, name); + } + this.flagPrompts.GetArray(g_trollAddPromptIndex, prompt); + + + prompt.flags |= (1 << flagIndex); + + if(defaultOn) { + // If out of bounds, set to default -1 -> pick global prompt + if(this.flagPrompts.Length == 0) { + ThrowError("Troll \"%s\" does not have any flag prompts, thus a default value cannot be set. (flag=\"%s\")", this.name, name); + return -1; + } + if(!prompt.multiselect && prompt.defaults > 0) { + ThrowError("Flag \"%s\" cannot be set as default flag in single select mode, as one has already been set for prompt %d", name, g_trollAddPromptIndex); + return -1; + } + prompt.defaults |= (1 << flagIndex); + } + this.flagPrompts.SetArray(g_trollAddPromptIndex, prompt); //May not be required + return flagIndex; + } + + int GetFlagIndex(const char[] flagName) { + static char comprFlag[MAX_TROLL_FLAG_LENGTH]; + for(int i = 0; i < this.flagNames.Length; i++) { + this.flagNames.GetString(i, comprFlag, sizeof(comprFlag)); + if(StrEqual(comprFlag, flagName)) { + return i; + } + } + return -1; + } + + bool HasFlags() { + return this.flagNames != null && this.flagNames.Length > 0 && this.flagPrompts.Length > 0; + } + + int GetFlagCount() { + return this.flagNames != null ? this.flagNames.Length : 0; + } + + int GetClientFlags(int client) { + return this.activeFlagClients[client]; + } + void GetFlagPrompt(int index, TrollFlagPrompt prompt) { + this.flagPrompts.GetArray(index, prompt); + } + +/////// TROLL ACTIVATION + + TrollEffectResponse Activate(int client, int activator, trollModifier modifier = TrollMod_Invalid, int flags = 0, bool silent = false) { + if(modifier == TrollMod_Invalid) modifier = this.GetDefaultMod(); + // Sadly, unable to pass in to ApplyTroll, so it has to do unnecessary lookup via string + return ApplyTroll(client, this.name, activator, modifier, flags, silent); + } + + + void Toggle(int client, int flags) { + if(this.IsActive(client)) { + this.Disable(client); + } else { + this.Enable(client, flags); + } + } + + void Enable(int client, int flags) { + this.activeFlagClients[client] = flags; + // If a timer is assigned, start it: + if(this.timerHandles[client] != null) { + delete this.timerHandles[client]; + PrintToServer("FTT Debug: Old timer for %N, killing", client); + } + if(this.timerInterval > 0.0) { + this.timerHandles[client] = CreateTimer(this.timerInterval, this.timerFunction, GetClientUserId(client), TIMER_REPEAT); + } + } + + void Disable(int client) { + this.activeFlagClients[client] = -1; + // Stop any running timer: + if(this.timerHandles[client] != null) { + PrintToServer("FTT Debug: Disabling timer for %N", client); + delete this.timerHandles[client]; + } + } + + bool IsActive(int client) { + return this.activeFlagClients[client] != -1; + } + + int GetRandomClient(int start = 0) { + gRandomClients.Clear(); + for(int i = start + 1; i <= MaxClients; i++) { + if(this.activeFlagClients[i] != -1) { + gRandomClients.Push(i); + } + } + if(gRandomClients.Length == 0) return -1; + return GetRandomInt(0, gRandomClients.Length); + } +} + +Troll Trolls[MAX_TROLLS+1]; + +ArrayList categories; +static int categoryID = -1; + +void ResetClient(int victim, bool wipe = true) { + if(victim == 0 || !IsClientConnected(victim)) return; + if(wipe) { + for(int i = 0; i <= MAX_TROLLS; i++) { + Trolls[i].Disable(victim); + } + } + noRushingUsSpeed[victim] = 1.0; + BaseComm_SetClientMute(victim, false); + SetEntityGravity(victim, 1.0); + SetEntPropFloat(victim, Prop_Send, "m_flLaggedMovementValue", 1.0); + SetEntProp(victim, Prop_Send, "m_iHideHUD", 0) + SDKUnhook(victim, SDKHook_WeaponCanUse, Event_ItemPickup); + int wpn = GetClientWeaponEntIndex(victim, 0); + if(wpn > -1) + SDKUnhook(wpn, SDKHook_Reload, Event_WeaponReload); +} + +int SetupTroll(const char[] name, const char description[128], int mods) { + static int i = 0; + if(mods == 0) { + ThrowError("Troll \"%s\" has no modifiers defined.", name); + return -1; + } else if(i == MAX_TROLLS + 1) { + ThrowError("Maximum number of trolls (%d) reached. Up MAX_TROLLS value.", MAX_TROLLS); + return -1; + } + g_trollAddPromptIndex = 0; + Trolls[i].id = i; + strcopy(Trolls[i].name, MAX_TROLL_NAME_LENGTH, name); + strcopy(Trolls[i].description, 128, description); + Trolls[i].categoryID = categoryID; + Trolls[i].mods = mods; + Trolls[i].flagPrompts = new ArrayList(sizeof(TrollFlagPrompt)); + + strcopy(trollIds[i], MAX_TROLL_NAME_LENGTH, name); + trollKV.SetValue(name, i); + return i++; +} + +// Gets the Troll enum struct via name +// Returns index of troll enum +int GetTroll(const char[] name, Troll troll) { + static int i = 0; + if(trollKV.GetValue(name, i)) { + troll = Trolls[i]; + return i; + } + ThrowError("GetTroll: Troll was not found \"%s\"", name); + return -1; +} +int GetTrollID(const char[] name) { + static int i = 0; + if(trollKV.GetValue(name, i)) { + return i; + } + PrintToServer("GetTrollID: Troll was not found \"%s\"", name); + return -1; +} + +bool IsAnyTrollActive(int victim) { + for(int i = 0; i <= MAX_TROLLS; i++) { + if(Trolls[i].activeFlagClients[victim] >= 0) return true; + } + return false; +} +// Gets the Troll enum struct via key index +// Returns index of troll enum +void GetTrollByKeyIndex(int index, Troll troll) { + troll = Trolls[index]; +} + +void SetTrollFlags(int client, const char[] name, int flags = -1) { + int index = GetTrollID(name); + if(flags == -1) + Trolls[index].Disable(client); + else + Trolls[index].Enable(client, flags); +} + + +TrollEffectResponse ApplyTroll(int victim, const char[] name, int activator, trollModifier modifier, int flags = 0, bool silent = false) { + static Troll troll; + int trollIndex = GetTroll(name, troll); + if(trollIndex == -1) { + ReplyToCommand(activator, "Unknown troll \"%s\"", name); + PrintToServer("[FTT] %N attempted to apply unknown troll: %s", activator, name); + return TE_Error; + } + + bool isActive = Trolls[trollIndex].activeFlagClients[victim] > -1; + + // Clear troll specific timer: + if(Trolls[trollIndex].timerInterval > 0.0) { + if(!isActive) { + if(modifier & TrollMod_Constant && (Trolls[trollIndex].timerRequiredFlags == 0 || Trolls[trollIndex].timerRequiredFlags & flags)) { + Trolls[trollIndex].timerHandles[victim] = CreateTimer(Trolls[trollIndex].timerInterval, Trolls[trollIndex].timerFunction, victim, TIMER_REPEAT); + } + } else if(Trolls[trollIndex].timerHandles[victim] != null) { + delete Trolls[trollIndex].timerHandles[victim]; + } + } + + + if(!silent && SilentMenuSelected[activator]) silent = true; + + static int MetaInverseTrollID; + if(!MetaInverseTrollID) MetaInverseTrollID = GetTrollID("Meta: Inverse"); + + if(activator > 0 && Trolls[MetaInverseTrollID].IsActive(activator)) { + float max = 1.0; + if(Trolls[MetaInverseTrollID].activeFlagClients[activator] & 2) max = 0.5; + else if(Trolls[MetaInverseTrollID].activeFlagClients[activator] & 4) max = 0.1; + if(GetURandomFloat() <= max) { + victim = activator; + } + } + + // If victim is a survivor bot, check if has an idle player + if(IsFakeClient(victim) && GetClientTeam(victim) == 2) { + int player = GetSpectatorClient(victim); + if(player > 0) { + // If there is an idle player, apply troll to them + ApplyTroll(player, name, activator, modifier, flags, silent); + // And continue IF there is TrollMod_PlayerOnly mod + if(troll.mods & view_as(TrollMod_PlayerOnly)) return TE_Success; + // Don't want to show two logs, so just ignore the bot + silent = true; + } + } + + + // Toggle on flags for client, if it's not a single run. + if(modifier & TrollMod_Constant) { + Trolls[trollIndex].activeFlagClients[victim] = isActive ? -1 : flags; + } + + // Applies any custom logic needed for a troll, mostly only used for TrollMod_Instant + TrollEffectResponse response = ApplyAffect(victim, troll, activator, modifier, flags); + if(response != TE_Success) return response; // Let the menu handler deal with checking + + // Log all actions, indicating if constant or single-fire, and if any flags + if(!silent) { + if(isActive) { + CShowActivityEx(activator, "[FTT] ", "deactivated {yellow}%s{default} on %N. ", troll.name, victim); + LogAction(activator, victim, "\"%L\" deactivated \"%s\" on \"%L\"", activator, troll.name, victim); + } else { + char flagName[MAX_TROLL_FLAG_LENGTH]; + // strcopy(flagName, sizeof(flagName), troll.name) + // Call_StartForward(g_TrollAppliedForward); + // Call_PushCell(victim); + // Call_PushString(flagName); + // Call_PushCell(flags); + // Call_PushCell(activator); + // Call_Finish(); + if(flags > 0) { + troll.GetFlagNames(victim, flagName, sizeof(flagName)); + // Checks if there is not more than one flag set on the bitfield + // if(flags & flags - 1 == 0 && flags & flags + 1 == 0) { + // // Get the flag name if there is only one flag set + // troll.GetFlagName(GetIndexFromPower(flags), flagName, sizeof(flagName)); + // } else { + // Format(flagName, sizeof(flagName), "%d", flags); + // } + Format(flagName, sizeof(flagName), " (\x04%s|%d\x01)", flagName, flags); + // CFormatColor(flagName, sizeof(flagName)); + } + + if(modifier & TrollMod_Constant) { + CShowActivityEx(activator, "[FTT] ", "activated constant {yellow}%s{default}%s for %N. ", troll.name, flagName, victim); + } else { + CShowActivityEx(activator, "[FTT] ", "activated {yellow}%s{default}%s for %N. ", troll.name, flagName, victim); + } + LogAction(activator, victim, "\"%L\" activated \"%s\" (%d) for \"%L\"", activator, troll.name, flags, victim); + } + } else { + CReplyToCommand(activator, "[FTT] Applied silently {yellow}\"%s\"{default} on %N with flags=%d", troll.name, victim, flags); + } + return TE_Success; +} + +bool IsTrollActive(int client, const char[] troll) { + if(troll[0] == '\0') { + ThrowError("Troll name is empty"); + return false; + } + static int i = 0; + if(trollKV.GetValue(troll, i)) { + return Trolls[i].activeFlagClients[client] != -1; + } + ThrowError("Troll \"%s\" does not exist", troll); + return false; //errors instead but compiler no like +} + +bool IsTrollActiveByRawID(int client, int id) { + return Trolls[id].activeFlagClients[client] != -1; +} + + +void EnableTroll(int client, const char[] troll, int flags = 0) { + SetTrollFlags(client, troll, flags); +} + +void DisableTroll(int client, const char[] troll) { + SetTrollFlags(client, troll, -1); +} + +public void SetCategory(const char[] newCat) { + categoryID = categories.FindString(newCat); + if(categoryID == -1) + categoryID = categories.PushString(newCat); +} +void GetCategory(int category, char[] buffer, int size) { + categories.GetString(category, buffer, size); +} + + +public int Native_ApplyTroll(Handle plugin, int numParams) { + int victim = GetNativeCell(1); + char name[MAX_TROLL_NAME_LENGTH]; + GetNativeString(2, name, sizeof(name)); + trollModifier modifier = view_as(GetNativeCell(3)); + if(view_as(modifier) < 0) { + ThrowNativeError(SP_ERROR_NATIVE, "Provided modifier is invalid (out of range)"); + } + int flags = GetNativeCell(4); + int activator = GetNativeCell(5); + + int index = GetTrollID(name); + if(index > 0) { + Trolls[index].Activate(victim, activator, modifier, flags, GetNativeCell(6)); + } else { + ThrowNativeError(SP_ERROR_NATIVE, "Could not find troll with name \"%s\"", name); + } + return 0; +} + \ No newline at end of file diff --git a/scripting/include/feedthetrolls/combos.inc b/scripting/include/feedthetrolls/combos.inc new file mode 100644 index 0000000..acb9e90 --- /dev/null +++ b/scripting/include/feedthetrolls/combos.inc @@ -0,0 +1,95 @@ + +ArrayList combos; + +enum struct SpecifiedTroll { + int id; + trollModifier mod; + int flags; +} +enum struct TrollCombo { + char name[32]; + ArrayList trolls; + + void AddTroll(const char[] name, int flags = 0, trollModifier mod = TrollMod_Invalid) { + int id = GetTrollID(name); + if(mod == TrollMod_Invalid) mod = Trolls[id].GetDefaultMod(); + SpecifiedTroll troll; + troll.id = id; + troll.mod = mod; + troll.flags = flags; + this.trolls.PushArray(troll, sizeof(troll)); + } + + void Activate(int client, int target) { + for(int i = 0; i < this.trolls.Length; i++) { + SpecifiedTroll troll; + this.trolls.GetArray(i, troll, sizeof(troll)); + Trolls[troll.id].Activate(target, client, troll.mod, troll.flags); + } + } +} + +void SetupCombo(TrollCombo combo, const char[] name) { + strcopy(combo.name, sizeof(combo.name), name); + combo.trolls = new ArrayList(sizeof(SpecifiedTroll)); + combos.PushArray(combo, sizeof(combo)); +} + +void SetupsTrollCombos() { + combos = new ArrayList(sizeof(TrollCombo)); + + TrollCombo combo; + SetupCombo(combo, "Magnet Galore"); + combo.AddTroll("Special Magnet"); + combo.AddTroll("Tank Magnet"); + #if defined _behavior_included + combo.AddTroll("Witch Magnet"); + #endif + + SetupCombo(combo, "Rush Stopper"); + combo.AddTroll("Special Magnet"); + combo.AddTroll("Tank Magnet"); + #if defined _behavior_included + combo.AddTroll("Witch Magnet"); + #endif + combo.AddTroll("No Button Touchie", 17, TrollMod_Constant); + combo.AddTroll("Slow Speed", 2, TrollMod_Constant); + combo.AddTroll("Instant Commons", 1, TrollMod_Instant); + // combo.AddTroll("Swarm", TrollMod_Instant); + combo.AddTroll("Vomit Player"); + combo.AddTroll("Dull Melee", .flags=2); + + SetupCombo(combo, "Tank Run Noob"); + combo.AddTroll("Slow Speed"); + combo.AddTroll("Tank Magnet"); + + SetupCombo(combo, "Nuclear"); + combo.AddTroll("Slow Speed"); + combo.AddTroll("Special Magnet", .flags=1); + combo.AddTroll("Tank Magnet", .flags=1); + #if defined _behavior_included + combo.AddTroll("Witch Magnet"); + #endif + combo.AddTroll("Reverse FF", .flags=2); + combo.AddTroll("Vomit Player"); + + SetupCombo(combo, "No more survival"); + combo.AddTroll("No Pickup", .flags = 8) + combo.AddTroll("Throw It All", .flags = 1) + + SetupCombo(combo, "Shut up"); + combo.AddTroll("Vocalize Gag"); + combo.AddTroll("Honk / Meow / Woof", .flags=1); + + SetupCombo(combo, "Weakness Compels You"); + combo.AddTroll("No Shove"); + combo.AddTroll("Dull Melee", .flags=2); + combo.AddTroll("Temp Health Quick Drain"); + + SetupCombo(combo, "Blindness"); + combo.AddTroll("Vomit Player", 0, TrollMod_Constant); + combo.AddTroll("Shakey Camera", .flags=16); + combo.AddTroll("Randomize Angles", .flags=16); + + PrintToServer("[FTT] Loaded %d troll combos", combos.Length); +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/commands.inc b/scripting/include/feedthetrolls/commands.inc new file mode 100644 index 0000000..6d844f2 --- /dev/null +++ b/scripting/include/feedthetrolls/commands.inc @@ -0,0 +1,787 @@ +Action Command_InstaSpecial(int client, int args) { + if(args < 1) { + Menu menu = new Menu(Insta_PlayerHandler); + menu.SetTitle("InstaSpecial: Choose a player"); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + static char userid[8], display[16]; + Format(userid, sizeof(userid), "%d|0", GetClientUserId(i)); + GetClientName(i, display, sizeof(display)); + menu.AddItem(userid, display); + } + } + menu.ExitButton = true; + menu.Display(client, 0); + } else { + char arg1[32], arg2[32] = "jockey"; + GetCmdArg(1, arg1, sizeof(arg1)); + if(args >= 2) { + GetCmdArg(2, arg2, sizeof(arg2)); + } + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MaxClients, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + SpecialType specialType = GetSpecialType(arg2); + if(specialType == Special_Invalid) { + ReplyToCommand(client, "Unknown special \"%s\"", arg2); + return Plugin_Handled; + } + + int successes = 0; + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(GetClientTeam(target) == 2) { + if(SpawnSpecialForTarget(specialType, target, view_as(Special_AlwaysTarget))) { + LogAction(client, target, "\"%L\" spawned Insta-%s™ nearby \"%L\"", client, arg2, target); + successes++; + } else { + ReplyToCommand(client, "[FTT] Could not spawn %s near %s", arg2, target_name); + } + } else { + ReplyToTargetError(client, target_count); + } + } + if(successes > 0) + CShowActivityEx(client, "[FTT] ", "spawned {green}Insta-%s™{default} near {green}%s", arg2, target_name); + } + + + return Plugin_Handled; +} + +Action Command_InstaSpecialFace(int client, int args) { + if(args < 1) { + Menu menu = new Menu(Insta_PlayerHandler); + menu.SetTitle("Inface: Choose a player"); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + static char userid[8], display[16]; + Format(userid, sizeof(userid), "%d|1", GetClientUserId(i)); + GetClientName(i, display, sizeof(display)); + menu.AddItem(userid, display); + } + } + menu.ExitButton = true; + menu.Display(client, 0); + } else { + char arg1[32], arg2[32] = "jockey"; + GetCmdArg(1, arg1, sizeof(arg1)); + if(args >= 2) { + GetCmdArg(2, arg2, sizeof(arg2)); + } + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MaxClients, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + SpecialType specialType = GetSpecialType(arg2); + if(specialType == Special_Invalid) { + ReplyToCommand(client, "Unknown special \"%s\"", arg2); + return Plugin_Handled; + } + + int successes = 0; + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(GetClientTeam(target) == 2) { + if(SpawnSpecialForTarget(specialType, target, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget))) { + LogAction(client, target, "\"%L\" spawned Insta-%s™ at player \"%L\"", client, arg2, target); + successes++; + } else { + ReplyToCommand(client, "[FTT] Could not spawn %s on %s", arg2, target_name); + } + }else{ + ReplyToTargetError(client, target_count); + } + } + if(successes > 0) + CShowActivityEx(client, "[FTT] ", "spawned {olive}Insta-%s™{default} on {olive}%s", arg2, target_name); + } + return Plugin_Handled; +} + + +Action Command_WitchAttack(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_witch_attack [# of witches or 0 for all]"); + }else{ + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE, /* Only allow alive players */ + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + int target = target_list[0]; + if(GetClientTeam(target) == 2) { + GetCmdArg(2, arg1, sizeof(arg1)); + + int maxCount = StringToInt(arg1); + if(maxCount < 0) maxCount = 0; + int count; + + int witch = INVALID_ENT_REFERENCE; + while ((witch = FindEntityByClassname(witch, "witch")) != INVALID_ENT_REFERENCE) { + if(SetWitchTarget(witch, target)) { + ++count; + } + if(maxCount > 0 && count >= maxCount) break; + } + ShowActivity(client, "set %d witches to target %s", count, target_name); + }else{ + ReplyToTargetError(client, target_count); + } + } + return Plugin_Handled; +} + +public Action Command_FeedTheCrescendoTroll(int client, int args) { + if(lastCrescendoUser > -1) { + ActivateAutoPunish(lastCrescendoUser); + ReplyToCommand(client, "Activated auto punish on %N", lastCrescendoUser); + LogAction(client, lastCrescendoUser, "\"%L\" autopunished crescendo rusher \"%L\"", client, lastCrescendoUser); + ShowActivityEx(client, "[FTT] ", "activated autopunish for crescendo activator %N",lastCrescendoUser); + }else{ + ReplyToCommand(client, "No player could be found to autopunish."); + } + return Plugin_Handled; +} + +public Action Command_ResetUser(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_ftr "); + }else{ + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_CONNECTED | COMMAND_FILTER_NO_IMMUNITY, /* Only allow alive players */ + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + for (int i = 0; i < target_count; i++) { + if(IsAnyTrollActive(target_list[i])) { + LogAction(client, target_list[i], "\"%L\" reset all troll effects for \"%L\"", client, target_list[i]); + } + ResetClient(target_list[i], true); + } + ShowActivityEx(client, "[FTT] ", "reset troll effects for %s.",target_name); + } + return Plugin_Handled; +} + +public Action Command_ApplyUser(int client, int args) { + if(args < 1) { + SilentMenuSelected[client] = false; + ShowTrollMenu(client, false); + }else{ + char arg1[32], arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + StringToLower(arg2); + + static char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + && target_list[0] == 0) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + if(args == 2) { + static char key[32]; + for(int i = 0; i < categories.Length; i++) { + categories.GetString(i, key, sizeof(key)); + if(StrEqual(key, arg2, false)) { + SilentMenuSelected[client] = false; + ShowTrollsForCategory(client, GetClientUserId(target_list[0]), i); + return Plugin_Handled; + } + } + ReplyToCommand(client, "[FTT] Unknown category: '%s'", arg2); + } else if(args == 1) { + SetupCategoryMenu(client, GetClientUserId(target_list[0])); + } + + SilentMenuSelected[client] = false; + SetupCategoryMenu(client, GetClientUserId(target_list[0])); + } + return Plugin_Handled; +} + +public Action Command_ApplyComboTrolls(int client, int args) { + if(args < 1) { + ShowTrollMenu(client, true); + }else{ + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + + static char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + && target_list[0] > 0) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + ShowTrollCombosMenu(client, GetClientUserId(target_list[0])); + } + return Plugin_Handled; +} + +public Action Command_ApplyUserSilent(int client, int args) { + if(args < 1) { + SilentMenuSelected[client] = true; + ShowTrollMenu(client, false); + }else{ + char arg1[32], arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + StringToLower(arg2); + + static char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + && target_list[0] > 0) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + SilentMenuSelected[client] = true; + if(args == 2) { + static char key[32]; + for(int i = 0; i < categories.Length; i++) { + categories.GetString(i, key, sizeof(key)); + if(StrEqual(key, arg2, false)) { + ShowTrollsForCategory(client, GetClientUserId(target_list[0]), i); + return Plugin_Handled; + } + } + ReplyToCommand(client, "[FTT] Unknown category: '%s'", arg2); + } + SetupCategoryMenu(client, GetClientUserId(target_list[0])); + } + return Plugin_Handled; +} + +public Action Command_ListModes(int client, int args) { + for(int i = 0; i <= MAX_TROLLS; i++) { + if(Trolls[i].hidden) continue; + ReplyToCommand(client, "%d. %s - %s", i, Trolls[i].name, Trolls[i].description); + } + return Plugin_Handled; +} + +public Action Command_ListTheTrolls(int client, int args) { + // View more info about a user + if(args == 1) { + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + + static char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_list[0] == 0) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + for(int p = 0; p < target_count; p++) { + int target = target_list[p]; + if(IsPlayerAlive(target)) + ReplyToCommand(client, "> Active Trolls for %N:", target); + else + ReplyToCommand(client, "> Active Trolls for %N: (Paused)", target); + + if(IsFakeClient(target)) { + int player = GetRealClient(target); + if(player != -1) target = player; + } + + for(int j = 1; j <= MAX_TROLLS; j++) { + if(Trolls[j].hidden) continue; + if(trollIds[j][0] != '\0' && IsTrollActive(target, trollIds[j])) { + if(Trolls[j].activeFlagClients[target] > 0) { + static char list[MAX_TROLL_FLAG_LENGTH*8]; //May in future need to up magic number 8 (supports 8 active flags ) + static char buffer[MAX_TROLL_FLAG_LENGTH]; + for(int i = 0; i < Trolls[j].flagNames.Length; i++) { + int a = (1 << i); + if(Trolls[j].activeFlagClients[target] & a) { + Trolls[j].flagNames.GetString(i, buffer, sizeof(buffer)); + Format(list, sizeof(list), "%s%s;", list, buffer); + } else { + Trolls[j].flagNames.GetString(i, buffer, sizeof(buffer)); + } + } + ReplyToCommand(client, "\"%s\" Flags: %s", trollIds[j], list); + } else + ReplyToCommand(client, trollIds[j]); + } + } + } + return Plugin_Handled; + } + + int count = 0; + char[][] modeListArr = new char[MAX_TROLLS+1][MAX_TROLL_NAME_LENGTH]; + static char modeList[255]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) > 1 && IsAnyTrollActive(i)) { + if(IsFakeClient(i)) { + int player = GetRealClient(i); + if(player != -1) i = player; + } + int modeCount = 0; + for(int j = 1; j <= MAX_TROLLS; j++) { + if(trollIds[j][0] != '\0' && IsTrollActive(i, trollIds[j])) { + if(Trolls[j].activeFlagClients[i] > 0) + Format(modeListArr[modeCount], MAX_TROLL_NAME_LENGTH, "%s(%d)", trollIds[j], Trolls[j].activeFlagClients[i]); + else + strcopy(modeListArr[modeCount], MAX_TROLL_NAME_LENGTH, trollIds[j]); + modeCount++; + } + } + + ImplodeStrings(modeListArr, modeCount, ", ", modeList, sizeof(modeList)); + if(IsPlayerAlive(i)) + ReplyToCommand(client, "%N | %s", i, modeList); + else + ReplyToCommand(client, "%N (Paused) | %s", i, modeList); + count++; + } + } + if(count == 0) { + ReplyToCommand(client, "No clients have a mode applied."); + } + return Plugin_Handled; +} + +public Action Command_MarkPendingTroll(int client, int args) { + if(args == 0) { + Menu menu = new Menu(ChooseMarkedTroll); + menu.SetTitle("Choose a troll to mark"); + static char userid[8], display[16]; + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i)) { + if(GetUserAdmin(i) == INVALID_ADMIN_ID) { + Format(userid, sizeof(userid), "%d", GetClientUserId(i)); + GetClientName(i, display, sizeof(display)); + menu.AddItem(userid, display); + } else { + ReplyToCommand(client, "%N is an admin cannot be marked.", i); + } + } + } + menu.ExitButton = true; + menu.Display(client, 0); + } else { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI , /* Only allow alive players */ + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + int target = target_list[0]; + if (GetClientTeam(target) == 2) { + ToggleMarkPlayer(client, target); + } else { + ReplyToCommand(client, "Player does not exist or is not a survivor."); + } + } + return Plugin_Handled; +} + +public Action Command_FeedTheTrollMenu(int client, int args) { + ReplyToCommand(client, "sm_ftl [player(s)] - Lists all the active trolls on players. Will show flag names if a player is specified."); + ReplyToCommand(client, "sm_ftm - Lists all available trolls & descriptions"); + ReplyToCommand(client, "sm_ftr - Resets target users' of any active trolls"); + ReplyToCommand(client, "sm_fta [player] [category] - Apply a troll on a player, with optional shortcut to player and/or category"); + ReplyToCommand(client, "sm_ftt - Shows this text"); + ReplyToCommand(client, "sm_ftc - Will apply a punishment to the last crescendo/event activator"); + ReplyToCommand(client, "sm_mark - Marks the user to be banned on disconnect, prevents their FF."); + return Plugin_Handled; +} + +public Action Command_BotsAttack(int client, int args) { + if(args > 0) { + static char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + int targetHP; + if(StringToIntEx(arg2, targetHP) == 0 || targetHP < 0 || targetHP > 100) { + ReplyToCommand(client, "Invalid target HP value. Must be between 0 and 100"); + return Plugin_Handled; + } + + int target_list[1], target_count; + static char target_name[MAX_TARGET_LENGTH]; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE | COMMAND_FILTER_NO_MULTI, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + int target = target_list[0]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsFakeClient(i) && GetClientTeam(i) == 2) { + if(!SetBotTarget(target, i, targetHP, 80)) { + ReplyToCommand(client, "%N could not target %s", i, target_name); + } + } + } + ShowActivity(client, "set all bots to attack %s", target_name); + } else { + ReplyToCommand(client, "syntax: sm_bots_attack [target-hp]"); + } + return Plugin_Handled; +} + +public Action Command_Stagger(int client, int args) { + if(args > 0) { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + + int target_list[MAXPLAYERS], target_count; + static char target_name[MAX_TARGET_LENGTH]; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MaxClients, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + for(int i = 0; i < target_count; i++) { + L4D_StaggerPlayer(target_list[i], target_list[i], NULL_VECTOR); + } + } else { + ReplyToCommand(client, "syntax: sm_stagger "); + } + return Plugin_Handled; +} + +public Action Command_SmartCharge(int client, int args) { + if(args > 0) { + static char arg1[32], arg2[8]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + int timeout = StringToInt(arg2); + if(timeout == 0) timeout = 15; + + int target_list[1], target_count; + static char target_name[MAX_TARGET_LENGTH]; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE | COMMAND_FILTER_NO_MULTI, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + if(pdata[target_list[0]].smartChargeActivator > 0) { + ReplyToCommand(client, "Target already has auto smart charge enabled"); + } else { + pdata[target_list[0]].smartChargeAttempts = 0; + pdata[target_list[0]].smartChargeMaxAttempts = timeout; + pdata[target_list[0]].smartChargeActivator = GetClientUserId(client); + CreateTimer(1.0, Timer_CheckForChargerOpportunity, GetClientUserId(target_list[0]), TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + ShowActivity(client, "Enabling smart auto-charge on %N for %d seconds", target_list[0], timeout); + } + } else { + ReplyToCommand(client, "syntax: sm_smartcharge [timeout or default 10s]"); + } + return Plugin_Handled; +} + +Action Command_HealTarget(int client, int args) { + if(args > 0) { + char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + int target_list[1], target_count; + static char target_name[MAX_TARGET_LENGTH]; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE | COMMAND_FILTER_NO_MULTI | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + int target = target_list[0]; + int targetUserId = GetClientUserId(target); + if(targetUserId == healTargetPlayer) { + ShowActivity(client, "cleared bots healing for %N", target); + StopHealingBots(); + } else { + healTargetPlayer = targetUserId; + CreateTimer(2.0, Timer_UpdateHealTargetPos, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + + int limit = StringToInt(arg2); + bool addBots = limit < 0; + if(limit < 0) limit = -limit; + else if(limit == 0) limit = MaxClients; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2 && IsFakeClient(i)) { + int kit = GetPlayerWeaponSlot(i, 3); + if(kit > 0) { + GetEntityClassname(kit, arg1, sizeof(arg1)); + if(StrEqual(arg1, "weapon_first_aid_kit")) { + pdata[i].flags |= view_as(Flag_IsTargettingHealer); + + if(--limit == 0) { + break; + } + } + } + } + } + if(addBots && limit > 0) { + wasAbmAutoHard = hAbmAutoHard.IntValue; + hAbmAutoHard.IntValue = 0; + CreateTimer(0.2, Timer_SpawnHealBots, limit, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); + } + ShowActivity(client, "made all bots heal %N", target); + wasSbFixEnabled = hSbFixEnabled.BoolValue; + hSbFixEnabled.BoolValue = false; + } + } else { + ReplyToCommand(client, "Usage: /healbots [# of bots or 0 for all]"); + } + return Plugin_Handled; +} +Action Command_SetReverseFF(int client, int args) { + if(args < 2) { + ReplyToCommand(client, "Usage: sm_rff [fire/explosion]*"); + return Plugin_Handled; + } + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int target = GetSinglePlayer(client, arg, COMMAND_FILTER_NO_BOTS); + if(target <= 0) { + return Plugin_Handled; + } + GetCmdArg(1, arg, sizeof(arg)); + GetCmdArg(2, arg, sizeof(arg)); + int flag = -1; + if(StrEqual(arg, "0") || StrEqual(arg, "0.0")) { + flag = 8; + } else if(StrEqual(arg, "2")) { + flag = 2; + } else if(StrEqual(arg, "0.5") || StrEqual(arg, ".5")) { + flag = 4; + } else if(StrEqual(arg, "3")) { + flag = 8; + } else if(StrEqual(arg, "1")) { + flag = 1; + } else { + ReplyToCommand(client, "Unsupported amount. Possible values: 0, 2, 0.5, 3, 1"); + return Plugin_Handled; + } + // args are 1-indexed so <= + for(int i = 3; i <= args; i++) { + GetCmdArg(i, arg, sizeof(arg)); + if(arg[0] == 'f') { + flag |= 32; + } else if(arg[0] == 'e') { + flag |= 64; + } else { + ReplyToCommand(client, "Unknown arg: %s", arg); + } + + } + ApplyTroll(target, "Reverse FF", client, TrollMod_Constant, flag); + return Plugin_Handled; +} + +Action Command_SetMagnetShortcut(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_magnet "); + return Plugin_Handled; + } + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int target = GetSinglePlayer(client, arg, COMMAND_FILTER_NO_BOTS); + if(target <= 0) { + return Plugin_Handled; + } + ShowTrollsForCategory(client, GetClientUserId(target), 0); + return Plugin_Handled; +} +Action Command_CarSplat(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_magnet [top/front/back]"); + return Plugin_Handled; + } + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int target = GetSinglePlayer(client, arg, COMMAND_FILTER_ALIVE); + if(target <= 0) { + return Plugin_Handled; + } + if(args == 2) { + GetCmdArg(2, arg, sizeof(arg)); + float speed = 450.0; + if(args == 3) { + GetCmdArg(3, arg, sizeof(arg)); + speed = StringToFloat(arg); + if(speed <= 0.0) speed = 450.0; + } + if(StrEqual(arg, "top")) { + SpawnCarOnPlayer(target); + } else if(StrEqual(arg, "front")) { + SpawnCarToPlayer(target, speed); + } else if(StrEqual(arg, "back")) { + SpawnCarToPlayer(target, -speed); + } else { + ReplyToCommand(client, "Invalid direction: top/front/back or blank for menu"); + return Plugin_Handled; + } + LogAction(client, target, "spawned car on/in %s of \"%L\"", arg, target); + ShowActivity(client, "spawned car (%s) of %N", arg, target); + } else { + Troll troll; + GetTroll("Car Splat", troll); + ShowSelectFlagMenu(client, GetClientUserId(target), view_as(TrollMod_Instant), troll); + } + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/events.inc b/scripting/include/feedthetrolls/events.inc new file mode 100644 index 0000000..fb85a37 --- /dev/null +++ b/scripting/include/feedthetrolls/events.inc @@ -0,0 +1,1108 @@ +public void OnConfigsExecuted() { + hSbFixEnabled = FindConVar("sb_fix_enabled"); + hAbmAutoHard = FindConVar("abm_autohard"); +} + +public void OnMapStart() { + if(hBotReverseFFDefend.IntValue > 0) hSbFriendlyFire.BoolValue = true; + AddFileToDownloadsTable("sound/custom/meow1.mp3"); + PrecacheSound("custom/meow1.mp3"); + AddFileToDownloadsTable("sound/custom/woof1.mp3"); + PrecacheSound("custom/woof1.mp3"); + + + lastButtonUser = -1; + HookEntityOutput("func_button", "OnPressed", Event_ButtonPress); + CreateTimer(MAIN_TIMER_INTERVAL_S, Timer_Main, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + PrecacheSound("player/footsteps/clown/concrete1.wav"); + PrecacheSound("weapons/ceda_jar/ceda_jar_explode.wav"); + PrecacheSound("weapons/molotov/molotov_detonate_1.wav"); + + PrecacheModel(MODEL_CAR); + + g_spSpawnQueue.Clear(); + spIsActive = false; + //CreateTimer(30.0, Timer_AutoPunishCheck, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); +} +public void OnClientPutInServer(int client) { + pdata[client].pendingTrollBan = 0; + pdata[client].shootAtTarget = 0; + fAntiRushFrequencyCounter[client] = 0.0; + if(IsTrollActive(client, "Voice Mute")) + BaseComm_SetClientMute(client, true); + SDKHook(client, SDKHook_OnTakeDamage, Event_TakeDamage); + SDKHook(client, SDKHook_OnTakeDamageAlive, NerfGun_OnTakeDamage); +} + +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + if(spIsActive || g_iPendingSurvivorAdd) { + int userid = event.GetInt("userid"); + CreateTimer(0.1, Timer_CheckSpecial, userid); + } +} + + + +public void OnEntityCreated(int entity, const char[] classname) { + if(entity >= MaxClients) { + if(StrEqual(classname, "infected", false)) + SDKHook(entity, SDKHook_OnTakeDamageAlive, NerfGun_OnTakeDamage); + else if(StrEqual(classname, "prop_physics")) { + HookSingleEntityOutput(entity, "OnHitByTank", OnCarHitByTank); + } else if(StrEqual(classname, "prop_car_alarm")) { + HookSingleEntityOutput(entity, "OnHitByTank", OnCarHitByTank); + } else if(StrEqual(classname, "tank_rock") || StrContains(classname, "_projectile", true) > -1 ) { + RequestFrame(EntityCreateCallback, entity); + } + } +} + +void OnCarHitByTank(const char[] output, int caller, int activator, float delay) { + entLastHeight[activator] = -10000.0; + CreateTimer(0.1, Timer_WaitForApex, EntIndexToEntRef(activator), TIMER_REPEAT); +} + +void EntityCreateCallback(int entity) { + if(!HasEntProp(entity, Prop_Send, "m_hOwnerEntity") || !IsValidEntity(entity)) return; + static char class[16]; + + static int badThrowID; + if(badThrowID == 0) badThrowID = GetTrollID("Bad Throw"); + + GetEntityClassname(entity, class, sizeof(class)); + int entOwner = GetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity"); + if(entOwner > 0 && entOwner <= MaxClients) { + if(Trolls[badThrowID].IsActive(entOwner)) { + static float pos[3]; + GetClientEyePosition(entOwner, pos); + if(Trolls[badThrowID].activeFlagClients[entOwner] & 1 && StrEqual(class, "vomitjar_projectile", true)) { + RemoveEntity(entity); + if(hBadThrowHitSelf.FloatValue > 0.0 && GetRandomFloat() <= hBadThrowHitSelf.FloatValue) { + L4D_CTerrorPlayer_OnVomitedUpon(entOwner, entOwner); + EmitSoundToAll("weapons/ceda_jar/ceda_jar_explode.wav", entOwner); + FindClosestClient(entOwner, false, pos); + } + SpawnItem("vomitjar", pos); + } else if(Trolls[badThrowID].activeFlagClients[entOwner] & 2 && StrEqual(class, "molotov_projectile", true)) { + // Burn them if no one near :) + if(hBadThrowHitSelf.FloatValue > 0.0 && GetRandomFloat() <= hBadThrowHitSelf.FloatValue) { + GetClientAbsOrigin(entOwner, pos); + // Kill molotov if too close to a player, else teleport to feet + if(IsAnyPlayerNear(entOwner, 500.0)) { + RemoveEntity(entity); + EmitSoundToAll("weapons/molotov/molotov_detonate_1.wav", entOwner); + } else { + float vel[3]; + vel[2] -= 50.0; + pos[2] += 50.0; + TeleportEntity(entity, pos, NULL_VECTOR, vel); + } + } else { + SpawnItem("molotov", pos); + AcceptEntityInput(entity, "Kill"); + } + } else if(Trolls[badThrowID].activeFlagClients[entOwner] & 3 && StrEqual(class, "pipe_bomb_projectile", true)) { + if(hBadThrowHitSelf.FloatValue > 0.0 && GetRandomFloat() <= hBadThrowHitSelf.FloatValue) { + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + ExplodeProjectile(entity); + } + SpawnItem("pipe_bomb", pos); + } + return; + } else if(Trolls[t_slipperyShoesIndex].IsActive(entOwner)) { + if(Trolls[t_slipperyShoesIndex].activeFlagClients[entOwner] & 4) { + L4D_StaggerPlayer(entOwner, entOwner, NULL_VECTOR); + } + return; + } + } + entLastHeight[entity] = -10000.0; + CreateTimer(0.1, Timer_WaitForApex, EntIndexToEntRef(entity), TIMER_REPEAT); +} + +enum ProjectileMagnetType { + ProjType_Specials = 1, + ProjType_Survivors = 2, + ProjType_Cars = 4, +} + + + +public void Event_DoorToggle(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && Trolls[t_slipperyShoesIndex].IsActive(client) && Trolls[t_slipperyShoesIndex].activeFlagClients[client] & 2) { + L4D_StaggerPlayer(client, client, NULL_VECTOR); + } +} + +void Event_SecondaryHealthUsed(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && Trolls[t_slipperyShoesIndex].IsActive(client) && Trolls[t_slipperyShoesIndex].activeFlagClients[client] & 8) { + L4D_StaggerPlayer(client, client, NULL_VECTOR); + } +} + +static float SPIT_VEL[3] = { 0.0, 0.0, -1.0 }; +Action Timer_CheckSpecial(Handle h, int specialID) { + int special = GetClientOfUserId(specialID); + if(special == 0) return Plugin_Continue; + // Check if new player is the spawned special: + if(g_iPendingSurvivorAdd && GetClientTeam(special) == 2 && GetEntProp(special, Prop_Send, "m_humanSpectatorUserID") == 0) { + g_iPendingSurvivorAdd = false; + isCustomSurvivor[special] = true; + PrintToServer("EPI Debug: Custom Survivor %N", special); + } else if(spIsActive && IsFakeClient(special)) { + //g_iPendingSurvivorAdd + if(GetClientTeam(special) == 3) { + SpecialType type = view_as(GetEntProp(special, Prop_Send, "m_zombieClass")); + if(type == spActiveRequest.type) { + // Ignore any fake clients with 'Bot' in name + static char buf[32]; + GetClientName(special, buf, sizeof(buf)); + if(StrContains(buf, "bot", false) == -1) { + // Set the special's target and flags + pdata[special].attackerTargetUid = spActiveRequest.targetUserId; + pdata[special].specialAttackFlags = spActiveRequest.flags; + // Warp to the spawn location + TeleportEntity(special, spActiveRequest.position, spActiveRequest.angle, NULL_VECTOR); + // Kill on spawn if enabled + if(spActiveRequest.flags & view_as(SPI_KillOnSpawn)) { + if(type == Special_Spitter) { + // Bug fix, spitter drops small puddle, so we spawn our own + float pos[3]; + GetClientEyePosition(special, pos); + L4D2_SpitterPrj(special, pos, SPIT_VEL); + } + RequestFrame(Frame_Boom, special); + } + + // Special spawned, run the next in the queue: + g_iSpId++; + ProcessSpecialQueue(); + } + } + } + } + return Plugin_Handled; +} +public void Frame_Boom(int special) { + SDKHooks_TakeDamage(special, special, special, 1000.0); +} +public void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) + ResetClient(client, true); +} + +public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int userid = event.GetInt("userid"); + int client = GetClientOfUserId(userid); + if(client > 0) { + if(pdata[client].attackerTargetUid > 0) { + // If special died, clear & subtract one from counter + pdata[client].attackerTargetUid = 0; + pdata[client].specialAttackFlags = 0; + } else { + // If player died, stop the targetting + for(int i = 1; i <= MaxClients; i++) { + if(pdata[i].attackerTargetUid == userid) { + pdata[i].attackerTargetUid = 0; + pdata[i].specialAttackFlags = 0; + break; + } + } + } + } +} +public Action Event_WeaponReload(int weapon) { + int client = GetEntPropEnt(weapon, Prop_Send, "m_hOwner"); + if(client > 0 && IsTrollActive(client, "Gun Jam")) { + if(GetRandomFloat() < 0.10) { //10% chance gun jams + return Plugin_Stop; + } + } + return Plugin_Continue; +} +public Action L4D2_CGasCan_EventKilled(int gascan, int &inflictor, int &attacker) { + static int noButtonPressIndex; + if(!noButtonPressIndex) noButtonPressIndex = GetTrollID("No Button Touchie"); + if(attacker > 0 && attacker <= MaxClients) { + if(Trolls[noButtonPressIndex].IsActive(attacker)) { + if(Trolls[noButtonPressIndex].activeFlagClients[attacker] & 1) { + return Plugin_Handled; + } + if(Trolls[noButtonPressIndex].activeFlagClients[attacker] & 2) { + L4D_CTerrorPlayer_OnVomitedUpon(attacker, attacker); + } + if(Trolls[noButtonPressIndex].activeFlagClients[attacker] & 4) { + L4D_SetPlayerIncapacitatedState(attacker, true); + } + if(Trolls[noButtonPressIndex].activeFlagClients[attacker] & 8) { + ServerCommand("sm_slay #%d", GetClientUserId(attacker)); + } + if(Trolls[noButtonPressIndex].activeFlagClients[attacker] & 16) { + float speed = GetEntPropFloat(attacker, Prop_Send, "m_flLaggedMovementValue"); + if(speed > 0.9) speed = 0.80; + speed -= 5.0; + SetEntPropFloat(attacker, Prop_Send, "m_flLaggedMovementValue", speed); + PrintToConsoleAdmins("[FTT] NoButtonTouchie: %N speed is now %f", speed); + } + } + lastButtonUser = attacker; + } + return Plugin_Continue; +} +public Action Event_ButtonPress(const char[] output, int entity, int client, float delay) { + static int noButtonPressIndex; + if(!noButtonPressIndex) noButtonPressIndex = GetTrollID("No Button Touchie"); + if(client > 0 && client <= MaxClients) { + if(Trolls[noButtonPressIndex].IsActive(client)) { + if(Trolls[noButtonPressIndex].activeFlagClients[client] & 1) { + AcceptEntityInput(entity, "Lock"); + RequestFrame(Frame_ResetButton, entity); + return Plugin_Handled; + } + if(Trolls[noButtonPressIndex].activeFlagClients[client] & 2) { + L4D_CTerrorPlayer_OnVomitedUpon(client, client); + } + if(Trolls[noButtonPressIndex].activeFlagClients[client] & 4) { + L4D_SetPlayerIncapacitatedState(client, true); + } + if(Trolls[noButtonPressIndex].activeFlagClients[client] & 8) { + ServerCommand("sm_slay #%d", GetClientUserId(client)); + } + if(Trolls[noButtonPressIndex].activeFlagClients[client] & 16) { + float speed = GetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue"); + if(speed > 0.9) speed = 0.80; + speed -= 5.0; + SetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue", speed); + PrintToConsoleAdmins("[FTT] NoButtonTouchie: %N speed is now %f", speed); + } + } + lastButtonUser = client; + } + return Plugin_Continue; +} + +public void Frame_ResetButton(int entity) { + AcceptEntityInput(entity, "Unlock"); +} + +public void Event_PanicEventCreate(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client) { + lastButtonUser = client; + } +} +public void Event_CarAlarm(Event event, const char[] name, bool dontBroadcast) { + int user = event.GetInt("userid"); + int client = GetClientOfUserId(user); + if(client) { + PrintToChatAll("%N has alerted the horde!", client); + CreateTimer(0.2, RushPlayer, user); + CreateTimer(0.6, RushPlayer, user); + CreateTimer(1.5, RushPlayer, user); + } + //Ignore car alarms for autopunish + lastButtonUser = -1; +} +public Action RushPlayer(Handle h, int user) { + L4D2_RunScript("RushVictim(GetPlayerFromUserID(%d), %d)", user, 15000); + return Plugin_Handled; +} +public Action L4D2_OnChooseVictim(int attacker, int &curTarget) { + static int spMagnetID, tankMagnetID; + if(spMagnetID == 0) spMagnetID = GetTrollID("Special Magnet"); + if(tankMagnetID == 0) tankMagnetID = GetTrollID("Tank Magnet"); + + L4D2Infected class = view_as(GetEntProp(attacker, Prop_Send, "m_zombieClass")); + // Check for any existing victims + int existingTarget = GetClientOfUserId(pdata[attacker].attackerTargetUid); + if(existingTarget > 0) { + if(IsPlayerAlive(existingTarget)) { + // Insta-specials ALWAYS target, if target has any attackers remaining + if(pdata[attacker].specialAttackFlags & view_as(SPI_AlwaysTarget)) { + curTarget = existingTarget; + return Plugin_Changed; + } + // Stop targetting if no longer magnetted: + if(class == L4D2Infected_Tank) { + if(!Trolls[tankMagnetID].IsActive(existingTarget) || !WillMagnetRun(Trolls[tankMagnetID], existingTarget)) return Plugin_Continue; + } else if(class != L4D2Infected_Tank) { + if(!Trolls[spMagnetID].IsActive(existingTarget) || !WillMagnetRun(Trolls[spMagnetID], existingTarget)) return Plugin_Continue; + } + + // Only set target based on incap rules: + if(class == L4D2Infected_Tank && (!IsPlayerIncapped(existingTarget) || hMagnetTargetMode.IntValue & 2) && WillMagnetRun(Trolls[tankMagnetID], existingTarget)) { + curTarget = existingTarget; + return Plugin_Changed; + } else if(class != L4D2Infected_Tank && (!IsPlayerIncapped(existingTarget) || hMagnetTargetMode.IntValue & 1) && WillMagnetRun(Trolls[spMagnetID], existingTarget)) { + curTarget = existingTarget; + return Plugin_Changed; + } + } else { + if(pdata[attacker].specialAttackFlags & view_as(SPI_KillOnTargetIncap)) { + ForcePlayerSuicide(attacker); + } + PrintToServer("target (%N) not alive, resetting target for %d", existingTarget, attacker) + pdata[attacker].attackerTargetUid = 0; + } + } + + // If no existing target, find closest valid victim + float closestDistance, survPos[3], spPos[3]; + GetClientAbsOrigin(attacker, spPos); + int closestClient = -1; + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + if(class == L4D2Infected_Tank) { + if(!Trolls[tankMagnetID].IsActive(i) || !WillMagnetRun(Trolls[tankMagnetID], i)) continue; + } else if(class != L4D2Infected_Tank) { + if(!Trolls[spMagnetID].IsActive(i) || !WillMagnetRun(Trolls[spMagnetID], i)) continue; + } + + if(IsPlayerIncapped(i)) { + if(class == L4D2Infected_Tank && hMagnetTargetMode.IntValue & 2 == 0) continue; + if(class != L4D2Infected_Tank && hMagnetTargetMode.IntValue & 1 == 0) continue; + } + + GetClientAbsOrigin(i, survPos); + float dist = GetVectorDistance(survPos, spPos, true); + if(dist < closestDistance || closestClient == -1) { + closestDistance = dist; + closestClient = i; + } + } + } + + // If found, set, else just let game decide + if(closestClient > 0) { + pdata[attacker].attackerTargetUid = GetClientUserId(closestClient); + curTarget = closestClient; + return Plugin_Changed; + } + return Plugin_Continue; +} + +bool WillMagnetRun(const Troll troll, int i) { + // In the case none of the flags are set, return true (100% chance) + // Some systems may give magnet w/ no flags + if(troll.activeFlagClients[i] == 0) return true; + + float cChance = 1.0; + //Skip first bit as it is ('Always') + if(troll.activeFlagClients[i] & 2) // 2nd: 50% + cChance = 0.5; + else if(troll.activeFlagClients[i] & 4) //3rd: 10% + cChance = 0.1; + return GetRandomFloat() <= cChance; +} + +public Action L4D2_OnEntityShoved(int client, int entity, int weapon, float vecDir[3], bool bIsHighPounce) { + if(client > 0 && client <= MaxClients) { + static int noShoveIndex; + if(noShoveIndex == 0) noShoveIndex == GetTrollID("No Shove"); + if(Trolls[noShoveIndex].IsActive(client) && GetRandomFloat() < hShoveFailChance.FloatValue) { + float shoveTime = L4D2Direct_GetNextShoveTime(client); + L4D2Direct_SetNextShoveTime(client, shoveTime + 2.0); + return Plugin_Handled; + } + } + return Plugin_Continue; +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) { + if(client <= 0 || sArgs[0] == '@') return Plugin_Continue; //Ignore admin chat or console + + static int honkID; + static int profanityID; + static int typooId; + if(honkID == 0) honkID = GetTrollID("Honk / Meow / Woof"); + if(profanityID == 0) profanityID = GetTrollID("No Profanity"); + if(typooId == 0) typooId = GetTrollID("Typoos"); + + if(Trolls[honkID].IsActive(client) && Trolls[honkID].activeFlagClients[client] & 1) { + // Honk Processing + static char strings[32][8]; + int words = ExplodeString(sArgs, " ", strings, sizeof(strings), 5); + + for(int i = 0; i < words; i++) { + // Strings should be padded by 7 characters (+ null term) to fill up 8 bytes + if(GetRandomFloat() <= 0.8) strings[i] = "honk "; + else strings[i] = "squeak "; + } + int length = 8 * words; + char[] message = new char[length]; + ImplodeStrings(strings, 32, " ", message, length); + if(Trolls[honkID].activeFlagClients[client] & 1) + CPrintToChatAll("{blue}%N {default}: %s", client, message); + else { + CPrintToChat(client, "{blue}%N {default}: %s", client, message); + bool showOriginalToOthers = Trolls[honkID].activeFlagClients[client] & 4 != 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && i != client) { + if(showOriginalToOthers) + CPrintToChat(i, "{blue}%N {default}: %s", client, sArgs); + else + CPrintToChat(i, "{blue}%N {default}: %s", client, message); + } + } + } + PrintToServer("%N: %s", client, sArgs); + return Plugin_Handled; + } else if(IsTrollActive(client, "Reversed")) { + int length = strlen(sArgs); + char[] message = new char[length+1]; + int j = 0; + for(int i = length - 1; i >= 0; i--) { + message[j++] = sArgs[i]; + } + message[j] = '\0'; + CPrintToChatAll("{blue}%N {default}: %s", client, message); + PrintToServer("%N: %s", client, sArgs); + return Plugin_Handled; + }else if(IsTrollActive(client, "iCantSpellNoMore")) { + int type = GetRandomInt(1, 14 + 3); + char letterSrc, replaceChar; + switch(type) { + case 1: { + letterSrc = 'e'; + replaceChar = 'b'; + } + case 2: { + letterSrc = 't'; + replaceChar = 'e'; + } + case 3: { + letterSrc = 'i'; + replaceChar = 'e'; + } + case 4: { + letterSrc = 'a'; + replaceChar = 's'; + } + case 5: { + letterSrc = 'u'; + replaceChar = 'i'; + } + case 6: { + letterSrc = '.'; + replaceChar = '/'; + } + case 7: { + letterSrc = 'm'; + replaceChar = 'n'; + } + case 8: { + letterSrc = 'n'; + replaceChar = 'm'; + } + case 9: { + letterSrc = 'l'; + replaceChar = 'b'; + } + case 10: { + letterSrc = 'l'; + replaceChar = 'b'; + } + case 11: { + letterSrc = 'h'; + replaceChar = 'j'; + } + case 12: { + letterSrc = 'o'; + replaceChar = 'i'; + } + case 13: { + letterSrc = 'e'; + replaceChar = 'r'; + } + case 14: { + letterSrc = 'w'; + replaceChar = 'h'; + } + + default: + return Plugin_Continue; + } + int strLength = strlen(sArgs); + char[] newMessage = new char[strLength + 20]; + int n = 0; + while (sArgs[n] != '\0') { + if(sArgs[n] == letterSrc) { + newMessage[n] = replaceChar; + }else{ + newMessage[n] = sArgs[n]; + } + n++; + } + PrintToServer("%N: %s", client, sArgs); + CPrintToChatAll("{blue}%N {default}: %s", client, newMessage); + return Plugin_Handled; + }else if(Trolls[profanityID].IsActive(client)) { + char strings[32][MAX_PHRASE_LENGTH]; + static ArrayList phrases; + bool foundWord = false; + int words = ExplodeString(sArgs, " ", strings, 32, MAX_PHRASE_LENGTH); + // Replace all swear words + for(int i = 0; i < words; i++) { + phrases = GetPhrasesArray(strings[i]); + if(phrases != null && phrases.Length > 0) { + foundWord = true; + phrases.GetString(GetRandomInt(0, phrases.Length - 1), strings[i], MAX_PHRASE_LENGTH); + } + } + int length = MAX_PHRASE_LENGTH * words; + char[] message = new char[length]; + + if(foundWord) { + // Found at least one word, keep modified intact + ImplodeStrings(strings, 32, " ", message, length); + } else if(Trolls[profanityID].activeFlagClients[client] & 2) { + // Replace full message content if flag enabled + if(!fullMessagePhraseList) { + PrintToServer("[FTT] Error: Could not find full message phrases!!!"); + return Plugin_Continue; + } + fullMessagePhraseList.GetString(GetRandomInt(0, fullMessagePhraseList.Length - 1), message, MAX_PHRASE_LENGTH); + } else { + // Flag off, keep original text + return Plugin_Continue; + } + + if(Trolls[profanityID].activeFlagClients[client] & 8) { //If 'show original' enabled + CPrintToChat(client, "{blue}%N {default}: %s", client, sArgs); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && i != client) { + CPrintToChat(i, "{blue}%N {default}: %s", client, message); + } + } + } else { //else show modified to all + CPrintToChatAll("{blue}%N {default}: %s", client, message); + } + // Print original in console no matter what + PrintToServer("%N: %s", client, sArgs); + return Plugin_Handled; + } else if(Trolls[typooId].IsActive(client)) { + char strings[32][MAX_TYPOS_LENGTH]; + int words = ExplodeString(sArgs, " ", strings, 32, MAX_TYPOS_LENGTH); + // Replace all typos + static char typoReplacement[32]; + for(int i = 0; i < words; i++) { + if(TYPOS_DICT.GetString(strings[i], typoReplacement, sizeof(typoReplacement))) { + strcopy(strings[i], MAX_TYPOS_LENGTH, typoReplacement); + } + } + int length = MAX_TYPOS_LENGTH * words; + char[] message = new char[length]; + ImplodeStrings(strings, 32, " ", message, length); + + CPrintToChatAll("{blue}%N {default}: %s", client, message); + PrintToServer("%N: %s", client, sArgs); + return Plugin_Handled; + } + return Plugin_Continue; +} +static char SMG[8] = "smg"; +static char AWP[16] = "sniper_awp"; + +public Action Event_ItemPickup(int client, int weapon) { + static int NoPickupIndex; + if(NoPickupIndex == 0) NoPickupIndex = GetTrollID("No Pickup"); + static int SpicyGasIndex; + if(SpicyGasIndex == 0) SpicyGasIndex = GetTrollID("Spicy Gas"); + static int UziRulesIndex; + if(UziRulesIndex == 0) UziRulesIndex = GetTrollID("UziRules / AwpSmells"); + + static char wpnName[64]; + if(Trolls[NoPickupIndex].IsActive(client)) { + int flags = Trolls[NoPickupIndex].activeFlagClients[client]; + if(flags & 1 && GetPlayerWeaponSlot(client, view_as(L4DWeaponSlot_Primary)) == weapon) { + // No Primary + return Plugin_Handled; + } else if(flags & 2 && GetEntityClassname(weapon, wpnName, sizeof(wpnName)) && StrEqual(wpnName, "weapon_melee")) { + // No melee + return Plugin_Handled; + } else if(flags & 4 && GetPlayerWeaponSlot(client, view_as(L4DWeaponSlot_Grenade)) == weapon) { + // No throwables + return Plugin_Handled; + } else if(flags & 8 && GetEntityClassname(weapon, wpnName, sizeof(wpnName)) && StrEqual(wpnName, "weapon_first_aid_kit")) { + // No Kits + return Plugin_Handled; + } else if(flags & 16 && GetPlayerWeaponSlot(client, view_as(L4DWeaponSlot_Pills)) == weapon) { + // No Pills / Adr + return Plugin_Handled; + } else if(flags & 32 && GetEntityClassname(weapon, wpnName, sizeof(wpnName)) && StrEqual(wpnName, "weapon_gascan")) { + return Plugin_Handled; + } + } else if(Trolls[UziRulesIndex].IsActive(client) || IsTrollActive(client, "Primary Disable")) { + GetEdictClassname(weapon, wpnName, sizeof(wpnName)); + if(strcmp(wpnName[7], "rifle") >= 0 + || strcmp(wpnName[7], "smg") >= 0 + || StrEqual(wpnName[7], "grenade_launcher") + || strcmp(wpnName[7], "sniper") > -1 + || StrContains(wpnName, "shotgun") > -1 + ) { + //If 4: Only UZI, if 5: Can't switch. + if(Trolls[UziRulesIndex].IsActive(client)) { + static char comp[16]; + if(Trolls[UziRulesIndex].activeFlagClients[client] & 1) + strcopy(comp, sizeof(comp), SMG); + else + strcopy(comp, sizeof(comp), AWP); + static char currentWpn[32]; + GetClientWeaponName(client, 0, currentWpn, sizeof(currentWpn)); + if(StrEqual(wpnName[7], comp)) { + return Plugin_Continue; + } else if(StrEqual(currentWpn[7], comp)) { + return Plugin_Stop; + } else { + int flags = GetCommandFlags("give"); + SetCommandFlags("give", flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "give %s", comp); + SetCommandFlags("give", flags); + return Plugin_Stop; + } + } else if(IsTrollActive(client, "Primary Disable")) { + return Plugin_Stop; + } + } + } else if(Trolls[SpicyGasIndex].IsActive(client)) { + if(GetEntityClassname(weapon, wpnName, sizeof(wpnName))) { + float max = 1.0; + if(Trolls[SpicyGasIndex].activeFlagClients[client] & 2) max = 0.5; + else if(Trolls[SpicyGasIndex].activeFlagClients[client] & 4) max = 0.1; + if(GetRandomFloat() <= max) { + if(StrEqual(wpnName, "weapon_gascan")) { + AcceptEntityInput(weapon, "Ignite", client, client); + } else if(StrEqual(wpnName, "weapon_propanetank") || StrEqual(wpnName, "weapon_oxygentank")) { + ExplodeProjectile(weapon, false); + } + } + } + } + return Plugin_Continue; +} + +public Action OnPlayerRunCmd(int client, int& buttons, int& impulse, float vel[3], float angles[3], int& weapon, int& subtype, int& cmdnum, int& tickcount, int& seed, int mouse[2]) { + int healTarget = GetClientOfUserId(healTargetPlayer); + if(healTarget > 0 && pdata[client].flags & view_as(Flag_IsTargettingHealer) && healTarget != client) { + static float pos[3]; + GetClientAbsOrigin(client, pos); + LookAtClient(client, healTarget); + if(GetVectorDistance(pos, healTargetPos, true) < 10000.0) { + if(GetClientAimTarget(client, true) == healTarget) { + buttons |= IN_ATTACK2; + return Plugin_Changed; + } + } + } + + // If 'KillMeSoftly' activated: + if(pdata[client].flags & view_as(Flag_PendingItemGive) && !(buttons & IN_ATTACK2)) { + int target = GetClientAimTarget(client, true); + if(target > -1) { + ClientCommand(client, "slot5"); + buttons |= IN_ATTACK2; + RequestFrame(StopItemGive, client); + return Plugin_Changed; + } + return Plugin_Continue; + } + + + if(pdata[client].shootAtTarget > 0 && (buttons & IN_ATTACK) == 0) { + if(GetClientAimTarget(client, true) == pdata[client].shootAtTarget) { + if(!IsActorBusy(client)) + PerformScene(client, "PlayerLaugh"); + buttons |= IN_ATTACK &~ (IN_RELOAD); + return Plugin_Changed; + } else { + if(!IsClientConnected(pdata[client].shootAtTarget)) { + pdata[client].shootAtTarget = 0; + } else { + LookAtClient(client, pdata[client].shootAtTarget); + } + } + } + + // Inverted control code: + if(Trolls[t_invertedTrollIndex].IsActive(client)) { + if(buttons & IN_MOVELEFT || buttons & IN_MOVERIGHT) { + vel[1] = -vel[1]; + } + if(buttons & IN_FORWARD || buttons & IN_BACK) { + vel[0] = -vel[0]; + } + if(buttons & IN_JUMP) { + buttons = buttons & ~IN_JUMP | IN_DUCK; + } else if(buttons & IN_DUCK) { + buttons = buttons & ~IN_DUCK | IN_JUMP; + } + if(buttons & IN_RUN) { + buttons = buttons & ~IN_RUN | IN_WALK; + } else if(buttons & IN_WALK) { + buttons = buttons & ~IN_WALK | IN_RUN; + } + if(buttons & IN_RELOAD) { + buttons = buttons & ~IN_RELOAD | IN_ATTACK2; + } else if(buttons & IN_ATTACK2) { + buttons = buttons & ~IN_ATTACK2 | IN_RELOAD; + } + return Plugin_Changed; + } + return Plugin_Continue; +} + +public Action NerfGun_OnTakeDamage(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + static int nerfGunIndex; + if(nerfGunIndex == 0) nerfGunIndex = GetTrollID("Nerf Gun"); + if(attacker > 0 && attacker <= MaxClients && GetClientTeam(attacker) == 2 && Trolls[nerfGunIndex].IsActive(attacker)) { + damage = 0.0; + return Plugin_Changed; + } + return Plugin_Continue; +} + +// Only triggered for players, victim is 0 < victim <= MaxClients +Action Event_TakeDamage(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + // Ignore passing bots from FF + if(attacker > 0 && attacker <= MaxClients) { + if(GetClientTeam(attacker) == 4 && IsFakeClient(attacker)) return Plugin_Continue; + } + // Boost all damage no matter what + if(Trolls[t_damageBoostIndex].IsActive(victim)) { + damage * 2; + return Plugin_Changed; + } + // Only apply for when attackers are players + if(attacker > 0 && attacker <= MaxClients && IsClientInGame(attacker) && IsPlayerAlive(attacker)) { + if(pdata[attacker].shootAtTarget == victim) return Plugin_Continue; + bool isSameTeam = GetClientTeam(attacker) == GetClientTeam(victim); + if(pdata[attacker].pendingTrollBan > 0 && isSameTeam) { + return Plugin_Stop; + } + if(Trolls[t_slotRouletteIndex].IsActive(victim) && GetURandomFloat() < 0.10) { + SetSlot(victim, -1); + } + if(victim != attacker) { + if(damage > 0.0 && Trolls[t_slipperyShoesIndex].IsActive(victim) && Trolls[t_slipperyShoesIndex].activeFlagClients[victim] & 16) { + L4D_StaggerPlayer(victim, victim, NULL_VECTOR); + } + if(isSameTeam && Trolls[t_reverseFFIndex].IsActive(attacker)) { + // Should this be applied? (as in no FF granted) + bool disableFF = false; + if(damagetype == DMG_BURN) { + disableFF = Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 32 != 0; + } else if(damagetype == DMG_BLAST) { + disableFF = Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 64 != 0; + } else { + // Does not run if DMG_BURN or DMG_BLAST + disableFF = true; + } + + if(disableFF) { + float returnDmg = damage; //default is 1:1 + if(Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 2) { + returnDmg *= 2.0; + } else if(Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 4) { + returnDmg /= 2.0; + } else if(Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 8) { + returnDmg = 0.0; + } else if(Trolls[t_reverseFFIndex].activeFlagClients[attacker] & 16) { + returnDmg *= 3.0; + } + SDKHooks_TakeDamage(attacker, attacker, attacker, returnDmg, damagetype, -1); + damage = 0.0; + return Plugin_Changed; + } + } + // Only retailate if 2 (anyone) or 1 and they aren't an admin. If we are also a bot. + if(IsFakeClient(victim) && (hBotReverseFFDefend.IntValue == 2 || GetUserAdmin(attacker) == INVALID_ADMIN_ID)) { + // If the attacker is not a bot and on our team, then retaliate + if(!IsFakeClient(attacker) && GetClientTeam(attacker) == 2 && GetClientTeam(victim) == 2) { + if(hBotDefendChance.IntValue >= GetURandomFloat()) { + if(pdata[victim].shootAtTarget == attacker) { + pdata[attacker].shootAtTargetHealth -= RoundToCeil(damage); + pdata[victim].shootAtLoops += 4; + return Plugin_Continue; + } else if(pdata[victim].shootAtTarget > 0) { + // Don't switch, wait for timer to stop + return Plugin_Continue; + } + SetBotTarget(attacker, victim, GetClientRealHealth(attacker) - RoundFloat(damage)); + } + } + } + } + // If FF is fire / blast, allow through unless its from a bot, then stop. + // Prevents players with no FF from lighting team on fire and disconnecting, making their new bot do the FF + if(damagetype & DMG_BURN || damagetype & DMG_BLAST) { + if(IsFakeClient(attacker)) return Plugin_Handled; + else return Plugin_Continue; + } + // Don't let bots do damage to the wrong targets if they are "defending" themselves + if(hBotReverseFFDefend.IntValue > 0 && IsFakeClient(attacker) && pdata[attacker].shootAtTarget == 0 && GetClientTeam(attacker) == 2 && GetClientTeam(victim) == 2) return Plugin_Stop; + } + return Plugin_Continue; +} + +public Action OnVocalizeCommand(int client, const char[] vocalize, int initiator) { + static int vocalGagID; + static int noRushingUsID; + if(vocalGagID == 0) vocalGagID = GetTrollID("Vocalize Gag"); + if(noRushingUsID == 0) noRushingUsID = GetTrollID("No Rushing Us"); + if(Trolls[noRushingUsID].IsActive(client) && (StrEqual(vocalize, "PlayerHurryUp") || StrEqual(vocalize, "PlayerYellRun") || StrEqual(vocalize, "PlayerMoveOn") || StrEqual(vocalize, "PlayerLeadOn"))) { + noRushingUsSpeed[client] -= 0.01; + if(noRushingUsSpeed[client] < 0.05) { + noRushingUsSpeed[client] = 0.05; + } + SetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue", noRushingUsSpeed[client]); + PrintToConsoleAdmins("[FTT] NoRushingUs: Dropping speed for %N (now %.1f%)", client, noRushingUsSpeed[client] * 100.0); + } + if(Trolls[t_slotRouletteIndex].IsActive(client) && GetURandomFloat() < 0.10) { + SetSlot(client, -1); + } + if(Trolls[vocalGagID].IsActive(client)) { + return Plugin_Handled; + } + return Plugin_Continue; +} + +#if defined _sceneprocessor_included +public void OnSceneStageChanged(int scene, SceneStages stage) { + if(stage == SceneStage_Spawned) { + static int vocalGagID, vocalizeSpecials; + if(vocalizeSpecials == 0) vocalizeSpecials = GetTrollID("Vocalize Specials"); + + + int activator = GetSceneInitiator(scene); + if(activator > 0 && activator <= MaxClients) { + if(Trolls[vocalizeSpecials].IsActive(activator)) { + static char sceneFile[32]; + GetSceneFile(scene, sceneFile, sizeof(sceneFile)); + if(StrContains(sceneFile, "warnboomer") > -1) { + SpawnSpecialForTarget(Special_Boomer, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } else if(StrContains(sceneFile, "warnhunter") > -1) { + SpawnSpecialForTarget(Special_Hunter, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } else if(StrContains(sceneFile, "warnsmoker") > -1) { + SpawnSpecialForTarget(Special_Smoker, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } else if(StrContains(sceneFile, "warnspitter") > -1) { + SpawnSpecialForTarget(Special_Spitter, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } else if(StrContains(sceneFile, "warnjockey") > -1) { + SpawnSpecialForTarget(Special_Jockey, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } else if(StrContains(sceneFile, "warncharger") > -1) { + SpawnSpecialForTarget(Special_Charger, activator, view_as(Special_OnTarget) | view_as(Special_AlwaysTarget)); + } + + if(Trolls[vocalizeSpecials].activeFlagClients[activator] & 1) { + CancelScene(scene); + } + } else if(Trolls[vocalGagID].IsActive(activator)) { + CancelScene(scene); + } + } + } +} +#endif + +public Action SoundHook(int clients[MAXPLAYERS], int& numClients, char sample[PLATFORM_MAX_PATH], int& entity, int& channel, float& volume, int& level, int& pitch, int& flags, char soundEntry[PLATFORM_MAX_PATH], int& seed) { + static int honkID; + static int vocalGagID; + if(honkID == 0) honkID = GetTrollID("Honk / Meow / Woof"); + if(vocalGagID == 0) vocalGagID = GetTrollID("Vocalize Gag"); + + if(lastButtonUser > 0 && IsClientConnected(lastButtonUser) && !IsFakeClient(lastButtonUser) && StrEqual(sample, "npc/mega_mob/mega_mob_incoming.wav")) { + PrintToConsoleAll("CRESCENDO STARTED BY %N", lastButtonUser); + #if defined DEBUG + PrintToChatAll("CRESCENDO STARTED BY %N", lastButtonUser); + #endif + + lastCrescendoUser = lastButtonUser; + if(IsPlayerFarDistance(lastButtonUser, AUTOPUNISH_FLOW_MIN_DISTANCE)) { + PrintChatToAdmins("Autopunishing player %N for activation of event far from team", lastButtonUser); + ShowActivityEx(0, "[FTT] ", "activated autopunish for crescendo activator %N (auto)", lastButtonUser); + LogAction(0, lastButtonUser, "\"%L\" automatic autopunish for crescendo activator \"%L\"", 0, lastButtonUser); + ActivateAutoPunish(lastButtonUser); + } + lastButtonUser = -1; + }else if(numClients > 0 && entity > 0 && entity <= MaxClients) { + if(StrContains(sample, "survivor\\voice") > -1) { + if(Trolls[honkID].IsActive(entity)) { + if(Trolls[honkID].activeFlagClients[entity] & 1) + strcopy(sample, sizeof(sample), "player/footsteps/clown/concrete1.wav"); + else if(Trolls[honkID].activeFlagClients[entity] & 2) + strcopy(sample, sizeof(sample), "custom/meow1.mp3"); + else if(Trolls[honkID].activeFlagClients[entity] & 4) + strcopy(sample, sizeof(sample), "custom/woof1.mp3"); + else + return Plugin_Continue; + return Plugin_Changed; + } else if(Trolls[vocalGagID].IsActive(entity)) { + if(Trolls[vocalGagID].activeFlagClients[entity] & 2) { + clients[0] = entity; + numClients = 1; + return Plugin_Changed; + } + return Plugin_Handled; + } + } + } + return Plugin_Continue; +} + +public void Event_WitchVictimSet(Event event, const char[] name, bool dontBroadcast) { + static int witchTrollID; + if(witchTrollID == 0) witchTrollID = GetTrollID("Witch Magnet"); + + int witch = event.GetInt("witchid"), closestClient = -1; + float closestDistance, survPos[3], witchPos[3]; + GetEntPropVector(witch, Prop_Send, "m_vecOrigin", witchPos); + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + //Ignore incapped players if hWitchIgnoreIncapp turned on: + if(IsPlayerIncapped(i) && ~hMagnetTargetMode.IntValue & 4) { + continue; + } + + if(Trolls[witchTrollID].IsActive(i)) { + GetClientAbsOrigin(i, survPos); + float dist = GetVectorDistance(survPos, witchPos, true); + if(closestClient == -1 || dist < closestDistance) { + closestDistance = dist; + closestClient = i; + } + } + } + } + + if(closestClient > 0) { + DataPack pack; + CreateDataTimer(0.1, Timer_NextWitchSet, pack); + pack.WriteCell(GetClientUserId(closestClient)); + pack.WriteCell(witch); + CreateDataTimer(0.2, Timer_NextWitchSet, pack); + pack.WriteCell(GetClientUserId(closestClient)); + pack.WriteCell(witch); + } +} + +public Action L4D2_MeleeGetDamageForVictim(int client, int weapon, int victim, float &damage) { + static int dullMeleeID; + if(!dullMeleeID) dullMeleeID = GetTrollID("Dull Melee"); + if(Trolls[dullMeleeID].IsActive(client)) { + float max = 1.0; + if(Trolls[dullMeleeID].activeFlagClients[client] & 2) max = 0.5; + else if(Trolls[dullMeleeID].activeFlagClients[client] & 4) max = 0.1; + if(GetRandomFloat() <= max) { + damage = 0.0; + return Plugin_Changed; + } + } + return Plugin_Continue; +} + +stock int FindClosestVisibleClient(int source) { + static float pos[3], ang[3]; + GetClientEyePosition(source, pos); + GetClientEyeAngles(source, ang); + TR_TraceRayFilter(pos, ang, MASK_VISIBLE, RayType_Infinite, TraceEntityFilterPlayer, source); + return TR_GetEntityIndex(); +} + +public bool TraceEntityFilterPlayer(int entity, int mask, any data) { + return data != entity && entity <= MaxClients && GetClientTeam(entity) == 2 && IsPlayerAlive(entity); +} + +// TODO: Increase the frequency of spawns the longer they are in antirush. Possibly increase int and decrease over time +public Action OnAntiRush(int client, int &type, float distance) { + if(client && client > 0 && client <= MaxClients && type == 3 && !IsFakeClient(client) && IsPlayerAlive(client) && !IsPlayerIncapped(client)) { + if(GetGameTime() - fLastAntiRushEvent[client] > hAntirushBaseFreq.FloatValue - fAntiRushFrequencyCounter[client]) { + if(fAntiRushFrequencyCounter[client] < hAntirushBaseFreq.FloatValue) { + fAntiRushFrequencyCounter[client] += hAntirushIncFreq.FloatValue; + } + SpecialType special = view_as(GetRandomInt(1,6)); + fLastAntiRushEvent[client] = GetGameTime(); + SpawnSpecialForTarget(special, client, view_as(Special_SpawnDirectOnFailure | Special_OnTarget | Special_AlwaysTarget)); + PrintToConsoleAll("[FTT] Spawning anti-rush special on %N (dist=%f) (special=%s)", client, distance, SPECIAL_NAMES[view_as(special)-1]); + } + } + return Plugin_Continue; +} + +Action Timer_DecreaseAntiRush(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(fAntiRushFrequencyCounter[i] > 1.0) { + fAntiRushFrequencyCounter[i]--; + } else { + fAntiRushFrequencyCounter[i] = 0.0; + } + } + return Plugin_Continue; +} + +public void L4D2_CInsectSwarm_CanHarm_Post(int acid, int spitter, int entity) { + if(entity <= MaxClients) + pdata[entity].lastInSpitTime = GetGameTime(); +} + +public void Event_EnteredSpit(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(Trolls[t_stickyGooIndex].IsActive(client)) { + int flags = Trolls[t_stickyGooIndex].activeFlagClients[client]; + float movement = 0.0; + if(flags & 1) movement = 0.9; + else if(flags & 2) movement = 0.8; + else if(flags & 4) movement = 0.7; + else if(flags & 8) movement = 0.5; + else if(flags & 16) movement = 0.3; + SetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue", movement); + pdata[client].lastInSpitTime = GetGameTime(); + if(~pdata[client].flags & view_as(Flag_HasSpitTimer)) { + CreateTimer(0.2, Timer_CheckIsInSpit, GetClientUserId(client), TIMER_REPEAT); + pdata[client].flags |= view_as(Flag_HasSpitTimer); + } + } + +} + +public void Event_BotPlayerSwap(Event event, const char[] name, bool dontBroadcast) { + //Player replaced their idle bot + int client = GetClientOfUserId(event.GetInt("player")); + if(client > 0) { + bool debug_hadTroll = false; + for(int i = 1; i <= MAX_TROLLS; i++) { + if(Trolls[i].IsActive(client) && Trolls[i].HasMod(TrollMod_Constant)) { //Add activeFlagClients >= 0 check possibly? + ApplyAffect(client, Trolls[i], -1, TrollMod_Constant, Trolls[i].activeFlagClients[client]); + debug_hadTroll = true; + } + } + if(debug_hadTroll) + PrintToServer("[FTT] Re-applied trolls for was-idle player %N", client); + } +} + +void Event_HealSuccess(Event event, const char[] name, bool dontBroadcast) { + int userid = event.GetInt("subject"); + int client = GetClientOfUserId(userid); + if(client > 0 && userid == healTargetPlayer) { + StopHealingBots(); + } +} + +public void L4D_OnVomitedUpon_Post(int victim, int attacker, bool boomerExplosion) { + if(Trolls[t_slotRouletteIndex].IsActive(victim) && GetURandomFloat() < 0.10) { + SetSlot(victim, -1); + } +} +void Event_Incapped(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("subject")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + if(client > 0 && attacker > 0 && attacker <= MaxClients && IsFakeClient(attacker) && GetClientTeam(attacker) == 3) { + if(pdata[attacker].specialAttackFlags & view_as(SPI_KillOnTargetIncap)) { + ForcePlayerSuicide(attacker); + } + } +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/menus.inc b/scripting/include/feedthetrolls/menus.inc new file mode 100644 index 0000000..5c62874 --- /dev/null +++ b/scripting/include/feedthetrolls/menus.inc @@ -0,0 +1,549 @@ +public int Insta_PlayerHandler(Menu menu, MenuAction action, int client, int param2) { + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) { + static char info[16]; + menu.GetItem(param2, info, sizeof(info)); + + static char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + + int userid = StringToInt(str[0]); + int instaMode = StringToInt(str[1]); + ShowInstaSpecialChooser(client, userid, instaMode); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +void ShowInstaSpecialChooser(int activator, int userid, int instaMode) { + Menu menu = new Menu(Insta_SpecialHandler); + menu.SetTitle("Choose a Insta-Special™"); + char data[16]; + for(int i = 1; i <= 8; i++) { + Format(data, sizeof(data), "%d|%d|%d", userid, instaMode, i); + menu.AddItem(data, SPECIAL_NAMES[i-1]); + } + menu.ExitButton = true; + menu.Display(activator, 0); +} + +public int Insta_SpecialHandler(Menu menu, MenuAction action, int client, int param2) { + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) { + static char info[16]; + menu.GetItem(param2, info, sizeof(info)); + static char str[3][8]; + ExplodeString(info, "|", str, 3, 8, false); + int userid = StringToInt(str[0]); + int target = GetClientOfUserId(userid); + bool inFace = StrEqual(str[1], "1"); + int specialInt = StringToInt(str[2]); + if(specialInt < 0 || specialInt > 8) { + ReplyToCommand(client, "Invalid special id"); + return 0; + } + SpecialType special = view_as(specialInt); + if(inFace) { + if(SpawnSpecialForTarget(special, target, view_as(Special_OnTarget) | view_as(Special_SpawnDirectOnFailure) | view_as(Special_AlwaysTarget))) { + LogAction(client, target, "\"%L\" spawned Insta-%s™ on \"%L\"", client, SPECIAL_NAMES[specialInt-1], target); + CShowActivityEx(client, "[FTT] ", "spawned {olive}Insta-%s™{default} on {olive}%N", SPECIAL_NAMES[specialInt-1], target); + } else { + ReplyToCommand(client, "Could not spawn special."); + } + } else { + if(SpawnSpecialForTarget(special, target, view_as(Special_AlwaysTarget))) { + CShowActivityEx(client, "[FTT] ", "spawned {green}Insta-%s™{default} near {green}%N", SPECIAL_NAMES[specialInt-1], target); + LogAction(client, target, "\"%L\" spawned Insta-%s™ near \"%L\"", client, SPECIAL_NAMES[specialInt-1], target); + } else { + ReplyToCommand(client, "Could not spawn special."); + } + } + ShowInstaSpecialChooser(client, userid, inFace); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + + +public int ChooseMarkedTroll(Menu menu, MenuAction action, int activator, int param2) { + if (action == MenuAction_Select) { + static char info[16]; + menu.GetItem(param2, info, sizeof(info)); + int target = GetClientOfUserId(StringToInt(info)); + ToggleMarkPlayer(activator, target); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChoosePlayerHandler(Menu menu, MenuAction action, int param1, int param2) { + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) { + static char info[8]; + menu.GetItem(param2, info, sizeof(info)); + int userid = StringToInt(info); + int victim = GetClientOfUserId(userid); + + if(victim == 0) { + ReplyToCommand(param1, "FTT: Could not acquire player"); + return 0; + } + + SetupCategoryMenu(param1, userid); + } else if (action == MenuAction_End) { + delete menu; + } + return 0; +} + +public int ChoosePlayerHandlerForCombos(Menu menu, MenuAction action, int client, int param2) { + if (action == MenuAction_Select) { + static char info[8]; + menu.GetItem(param2, info, sizeof(info)); + int userid = StringToInt(info); + int victim = GetClientOfUserId(userid); + + if(victim == 0) { + ReplyToCommand(victim, "FTT: Could not acquire player"); + return 0; + } + + ShowTrollCombosMenu(client, userid); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChooseComboHandler(Menu menu, MenuAction action, int client, int param2) { + if (action == MenuAction_Select) { + static char info[16]; + menu.GetItem(param2, info, sizeof(info)); + static char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + int userid = StringToInt(str[0]); + int victim = GetClientOfUserId(userid); + int comboID = StringToInt(str[1]); + + if(victim == 0) { + ReplyToCommand(client, "FTT: Could not acquire player"); + return 0; + } + + static TrollCombo combo; + combos.GetArray(comboID, combo, sizeof(combo)); + combo.Activate(client, victim); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +static int iMenuVictimID[MAXPLAYERS+1]; +public int ChooseCategoryHandler(Menu menu, MenuAction action, int param1, int param2) { + if (action == MenuAction_Cancel && param2 == MenuCancel_ExitBack) + ShowTrollMenu(param1, false); + else if (action == MenuAction_Select) { + static char info[32]; + menu.GetItem(param2, info, sizeof(info)); + static char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + int userid = StringToInt(str[0]); + int victim = GetClientOfUserId(userid); + if(victim == 0) { + ReplyToCommand(param1, "FTT/ChooseCategoryHandler: Could not acquire player"); + return 0; + } + + iMenuVictimID[param1] = userid; + int category = StringToInt(str[1]); + + // Reset troll: + if(category == -1) { + ApplyTroll(GetClientOfUserId(userid), "Reset User", param1, TrollMod_Instant); + return 0; + } + + ShowTrollsForCategory(param1, userid, category); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChooseModeMenuHandler(Menu menu, MenuAction action, int param1, int param2) { + if (action == MenuAction_Cancel) { + if(param2 == MenuCancel_ExitBack) { + if(iMenuVictimID[param1] == 0) { + ReplyToCommand(param1, "FTT/ChooseModeMenuHandler: Could not acquire player"); + } + SetupCategoryMenu(param1, iMenuVictimID[param1]); + } + } else if (action == MenuAction_Select) { + static char info[32]; + menu.GetItem(param2, info, sizeof(info)); + static char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + int userid = StringToInt(str[0]); + int client = GetClientOfUserId(userid); + if(client == 0) { + ReplyToCommand(param1, "FTT: Could not acquire player"); + return 0; + } + + int keyIndex = StringToInt(str[1]); + static Troll troll; + GetTrollByKeyIndex(keyIndex, troll); + //If troll has multiple flags, prompt: + if(StrEqual(troll.name, "Throw It All")) { + // Setup menu to call itself, but with an extra data point + ShowThrowItAllMenu(param1, userid); + } else if(!troll.IsActive(client) && troll.HasMod(TrollMod_Instant) && troll.HasMod(TrollMod_Constant)) { + Menu modiferMenu = new Menu(ChooseTrollModiferHandler); + Format(info, sizeof(info), "%s: Choose Modifier", troll.name); + modiferMenu.SetTitle(info); + + Format(info, sizeof(info), "%d|%d|1", userid, keyIndex); + modiferMenu.AddItem(info, "Activate Once"); + Format(info, sizeof(info), "%d|%d|2", userid, keyIndex); + modiferMenu.AddItem(info, "Activate Periodically"); + Format(info, sizeof(info), "%d|%d|3", userid, keyIndex); + modiferMenu.AddItem(info, "Activate Periodically & Instantly"); + + modiferMenu.ExitButton = true; + modiferMenu.Display(param1, 0); + } else if(!troll.IsActive(client) && troll.HasFlags()) { + ShowSelectFlagMenu(param1, userid, -1, troll); + } else { + TrollEffectResponse response = troll.Activate(client, param1); + // Only show menu if success or error, not TE_Menu + if(response != TE_Menu) + ShowTrollsForCategory(param1, userid, troll.categoryID); + } + + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChooseClumsySlotHandler(Menu menu, MenuAction action, int param1, int param2) { + if (action == MenuAction_Select) { + char info[32]; + menu.GetItem(param2, info, sizeof(info)); + static char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + int userid = StringToInt(str[0]); + int client = GetClientOfUserId(userid); + int slot = StringToInt(str[1]); + if(client == 0) { + ReplyToCommand(param1, "FTT: Could not acquire player"); + return 0; + }else if(slot == -1) { + for(int i = 0; i <= 4; i++) { + ThrowItemToPlayer(client, param1, i); + } + } else if(slot == -2) { + ShowThrowItAllMenu(param1, userid); + } else { + if(!GetClientWeaponNameSmart(client, slot, info, sizeof(info))) { + strcopy(info, sizeof(info), "-unk-"); + } + CShowActivityEx(param1, "[FTT] ", "activated troll {yellow}Throw It All{default} ({olive}%s|%d{default}) for \"%N\"", info, slot, client); + LogAction(param1, client, "\"%L\" activated troll \"Throw It All\" (%s) for \"%L\". ", param1, info, client); + ThrowItemToPlayer(client, param1, slot); + } + + ShowThrowItAllMenu(param1, userid); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChooseTrollModiferHandler(Menu menu, MenuAction action, int param1, int param2) { + if (action == MenuAction_Select) { + static char info[16]; + menu.GetItem(param2, info, sizeof(info)); + static char str[3][8]; + ExplodeString(info, "|", str, 3, 8, false); + int userid = StringToInt(str[0]); + int client = GetClientOfUserId(userid); + int keyIndex = StringToInt(str[1]); + int modifiers = StringToInt(str[2]); + + if(client == 0) { + ReplyToCommand(param1, "FTT: Could not acquire player"); + return 0; + } + + static Troll troll; + GetTrollByKeyIndex(keyIndex, troll); + + if(!troll.IsActive(client) && troll.HasFlags()) { + // Show flag selection if troll is not enabled already + ShowSelectFlagMenu(param1, userid, modifiers, troll); + } else { + TrollEffectResponse response; + if(modifiers == 1 || modifiers == 3) + response = troll.Activate(client, param1, TrollMod_Instant); + if(modifiers == 2 || modifiers == 3) + response = troll.Activate(client, param1, TrollMod_Constant); + if(response != TE_Menu) + ShowTrollsForCategory(param1, userid, troll.categoryID); + } + + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public int ChooseTrollFlagHandler(Menu menu, MenuAction action, int param1, int param2) { + if (action == MenuAction_Select) { + static char info[32]; + menu.GetItem(param2, info, sizeof(info)); + static char str[6][8]; + ExplodeString(info, "|", str, 6, 8, false); + int userid = StringToInt(str[0]); + int client = GetClientOfUserId(userid); + int keyIndex = StringToInt(str[1]); + int modifiers = StringToInt(str[2]); + int flags = StringToInt(str[3]); + int index = StringToInt(str[4]); + bool isDone = StringToInt(str[5]) == 1; // 0 = cont, 1 = done + + if(client == 0) { + ReplyToCommand(param1, "FTT: Could not acquire player"); + return 0; + } + + static Troll troll; + GetTrollByKeyIndex(keyIndex, troll); + + // If told to go to next prompt, find the next VALID prompt + // Valid prompt is one where the required flags for it, are active + + if(isDone || index == -1) { + int nextIndex = GetNextPrompt(troll, flags, index); + // If there is a prompt available, show it, else fall down + if(nextIndex != -1) { + ShowSelectFlagMenu(param1, userid, modifiers, troll, flags, nextIndex); + return 0; + } + // else fall through & apply + } else { + ShowSelectFlagMenu(param1, userid, modifiers, troll, flags, index); + return 0; + } + + TrollEffectResponse response; + // Done with prompts, apply flags & modifiers + if(modifiers > 0) { + if(modifiers & view_as(TrollMod_Instant)) + response = troll.Activate(client, param1, TrollMod_Instant, flags); + if(modifiers & view_as(TrollMod_Constant)) + response = troll.Activate(client, param1, TrollMod_Constant, flags); + } else { + response = troll.Activate(client, param1, TrollMod_Invalid, flags); + } + // Jump back to selection screen + if(response != TE_Menu) + ShowTrollsForCategory(param1, userid, troll.categoryID); + } else if (action == MenuAction_End) + delete menu; + return 0; +} + + +public void StopItemGive(int client) { + pdata[client].flags &= ~view_as(Flag_PendingItemGive); +} + +void SetupCategoryMenu(int client, int victimUserID) { + iMenuVictimID[client] = victimUserID; + Menu categoryMenu = new Menu(ChooseCategoryHandler); + static char category[64], id[16]; + // Title with [ in name cause failure + Format(category, sizeof(category), "Choose troll category"); + categoryMenu.SetTitle(category); + + Format(id, sizeof(id), "%d|-1", victimUserID); + categoryMenu.AddItem(id, "Reset User"); + for(int i = 0; i < categories.Length; i++) { + categories.GetString(i, category, sizeof(category)); + Format(id, sizeof(id), "%d|%d", victimUserID, i); + categoryMenu.AddItem(id, category); + } + categoryMenu.ExitButton = true; + categoryMenu.ExitBackButton = true; + categoryMenu.Display(client, 0); +} + +void ShowTrollCombosMenu(int client, int victimUserID) { + Menu comboMenu = new Menu(ChooseComboHandler); + static char id[32]; + Format(id, sizeof(id), "Choose troll combo"); + comboMenu.SetTitle(id); + + static TrollCombo combo; + + if(combos.Length == 0) { + ReplyToCommand(client, "FTT: No troll combos available"); + return; + } + + for(int i = 0; i < combos.Length; i++) { + combos.GetArray(i, combo, sizeof(combo)); + Format(id, sizeof(id), "%d|%d", victimUserID, i); + comboMenu.AddItem(id, combo.name); + } + + comboMenu.ExitButton = true; + comboMenu.ExitBackButton = true; + comboMenu.Display(client, 0); +} + +void ShowTrollMenu(int client, bool isComboList) { + Menu menu = isComboList ? new Menu(ChoosePlayerHandlerForCombos) : new Menu(ChoosePlayerHandler); + menu.SetTitle("Choose a player to troll"); + // If player idle, say they are survivor + int clientTeam = GetClientTeam(client); + if(clientTeam < 2) { + if(L4D_IsPlayerIdle(client)) clientTeam = 2; + } + + static char userid[8], display[64]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && (hAllowEnemyTeam.BoolValue || GetClientTeam(i) == clientTeam)) { + IntToString(GetClientUserId(i), userid, sizeof(userid)); + GetMenuDisplayName(i, display, sizeof(display)); + menu.AddItem(userid, display); + } + } + menu.ExitButton = true; + menu.Display(client, 0); +} + +void ShowTrollsForCategory(int client, int userid, int category) { + static char info[32]; + Menu trollMenu = new Menu(ChooseModeMenuHandler); + GetCategory(category, info, sizeof(info)); + Format(info, sizeof(info), "Category: %s", info); + trollMenu.SetTitle(info); + + static Troll troll; + + int victim = GetClientOfUserId(userid); + + // Add all menus that have same category ID to list + static char name[MAX_TROLL_NAME_LENGTH+8]; + for(int i = 0; i < trollKV.Size; i++) { + GetTrollByKeyIndex(i, troll); + // If troll is hidden and using normal menu, do not show + if(troll.hidden && !SilentMenuSelected[client]) continue; + if(troll.categoryID == category) { + Format(info, sizeof(info), "%d|%d", userid, i); + if(troll.IsActive(victim)) { + Format(name, sizeof(name), "%s (Active)", troll.name); + trollMenu.AddItem(info, name); + } else + trollMenu.AddItem(info, troll.name); + } + } + trollMenu.ExitButton = true; + trollMenu.ExitBackButton = true; + trollMenu.Display(client, 0); +} + +// Called with defaults on start, then recalled by ChooseTrollFlagHandler until prompt selection finished +void ShowSelectFlagMenu(int activator, int victimUserID, int modifiers, Troll troll, int prevFlags = -1, int promptIndex = 0) { + static char info[MAX_TROLL_NAME_LENGTH+16]; //victimUSERID|trollID|modifiers|flags||flagIndex + static char name[32]; + + Menu flagMenu = new Menu(ChooseTrollFlagHandler); + + TrollFlagPrompt prompt; + troll.GetFlagPrompt(promptIndex, prompt); + prompt.GetPromptText(info, sizeof(info)); + + Format(info, sizeof(info), "%s: %s", troll.name, info); + flagMenu.SetTitle(info); + + if(prompt.multiselect) { + if(prevFlags == -1) prevFlags = prompt.defaults; + + Format(info, sizeof(info), "%d|%d|%d|%d|%d|1", victimUserID, troll.id, modifiers, prevFlags, promptIndex); + flagMenu.AddItem(info, "Apply / Next Prompt"); + + for(int i = 0; i < troll.flagNames.Length; i++) { + int a = 1 << i; + if(prompt.flags & a) { + troll.flagNames.GetString(i, name, sizeof(name)); + // If flag is enabled, show indication (On) + if(prevFlags > 0 && prevFlags & a) + Format(name, sizeof(name), "%s ✓", name); + int newFlags = prevFlags ^ a; //Toggle the flag instead of setting like below, as it's toggleable here + Format(info, sizeof(info), "%d|%d|%d|%d|%d|0", victimUserID, troll.id, modifiers, newFlags, promptIndex); + flagMenu.AddItem(info, name); + } + } + } else { + // Single choice only + if(prevFlags == -1) prevFlags = 0; + for(int i = 0; i < troll.flagNames.Length; i++) { + int a = 1 << i; + if(prompt.flags & a) { + troll.flagNames.GetString(i, name, sizeof(name)); + // Add (default) indicator + + if(prompt.defaults & a) + Format(name, sizeof(name), "%s (default)", name); + int newFlags = prevFlags | a; //Set flag with any from previous prompts + Format(info, sizeof(info), "%d|%d|%d|%d|%d|1", victimUserID, troll.id, modifiers, newFlags, promptIndex); + flagMenu.AddItem(info, name); + } + } + } + flagMenu.ExitButton = true; + flagMenu.Display(activator, 0); +} + +void ShowThrowItAllMenu(int client, int userid) { + static char info[32]; + Menu itmMenu = new Menu(ChooseClumsySlotHandler); + itmMenu.SetTitle("Choose Item To Throw"); + + static char itmName[32]; + Format(info, sizeof(info), "%d|-2", userid); + itmMenu.AddItem(info, "Refresh"); + + Format(info, sizeof(info), "%d|-1", userid); + itmMenu.AddItem(info, "All Items"); + + int victim = GetClientOfUserId(userid); + if(victim == 0) { + ReplyToCommand(client, "FTT: Could not acquire player"); + return; + } + + // Grab all the items the player has, add to menu + for(int slot = 0; slot <= 5; slot++) { + int item = GetClientWeaponNameSmart2(victim, slot, itmName, sizeof(itmName)); + if(item > -1) { + Format(info, sizeof(info), "%d|%d", userid, slot); + itmMenu.AddItem(info, itmName); + } + } + + itmMenu.ExitButton = true; + itmMenu.Display(client, 0); +} + +int GetNextPrompt(Troll troll, int flags, int currentPrompt = 0) { + static TrollFlagPrompt prompt; + //If this prompt requires flags but they don't exist, skip to next that is valid or be done: + if(currentPrompt + 1 == troll.flagPrompts.Length) return -1; + for(int i = currentPrompt + 1; i < troll.flagPrompts.Length; i++) { + troll.GetFlagPrompt(i, prompt); + if(flags & prompt.requireFlags == prompt.requireFlags) { + return i; + } + } + // No suitable prompts found, mark it as done: + return -1; +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/misc.inc b/scripting/include/feedthetrolls/misc.inc new file mode 100644 index 0000000..d3336c3 --- /dev/null +++ b/scripting/include/feedthetrolls/misc.inc @@ -0,0 +1,580 @@ +#define AUTOPUNISH_FLOW_MIN_DISTANCE 5000.0 +#define AUTOPUNISH_MODE_COUNT 3 +// #define DEBUG_PHRASE_LOAD 1 + +void ActivateAutoPunish(int client) { + if(hAutoPunish.IntValue & 2 == 2) + ApplyTroll(client, "Special Magnet", 0, TrollMod_Constant); + if(hAutoPunish.IntValue & 1 == 1) + ApplyTroll(client, "Tank Magnet", 0, TrollMod_Constant); + if(hAutoPunish.IntValue & 8 == 8) + ApplyTroll(client, "Vomit Player", 0, TrollMod_Instant); + else if(hAutoPunish.IntValue & 4 == 4) + ApplyTroll(client, "Swarm", 0, TrollMod_Instant); + if(hAutoPunishExpire.IntValue > 0) { + CreateTimer(60.0 * hAutoPunishExpire.FloatValue, Timer_ResetAutoPunish, GetClientOfUserId(client)); + } +} + +// NOTE: Only supports one target at a time, stored globally +bool SetWitchTarget(int witch, int target) { + #if defined _actions_included + g_iWitchAttackVictim = target; + BehaviorAction action = ActionsManager.GetAction(witch, "WitchBehavior"); + if(action == INVALID_ACTION || action.Child == INVALID_ACTION) { + return false; + } + action = action.Child; + action.OnUpdate = OnWitchActionUpdate; + return true; + #else + PrintToServer("[FTT] SetWitchTarget() called when behaviors plugin not found"); + return false; + #endif +} + +bool ToggleMarkPlayer(int client, int target) { + if(pdata[target].pendingTrollBan > 0) { + pdata[target].pendingTrollBan = 0; + LogAction(client, target, "\"%L\" unmarked \"%L\" as troll", client, target); + ShowActivityEx(client, "[FTT] ", "unmarked %N as troll", target); + return true; + }else{ + bool isClientAdmin = GetUserAdmin(client) != INVALID_ADMIN_ID; + if(!isClientAdmin) { + ReplyToCommand(client, "cannot mark %N as troll as you are not an admin.", target); + return false; + } + bool isTargetAdmin = GetUserAdmin(target) != INVALID_ADMIN_ID; + if(isTargetAdmin) { + ReplyToCommand(client, "cannot mark %N as troll as they are an admin.", target); + return false; + } + + Call_StartForward(g_PlayerMarkedForward); + Call_PushCell(client); + Call_PushCell(target); + Call_Finish(); + pdata[target].pendingTrollBan = GetClientUserId(client); + EnableTroll(target, "No Profanity"); + LogAction(client, target, "\"%L\" marked \"%L\" as troll", client, target); + ShowActivityEx(client, "[FTT] ", "marked %N as troll", target); + return true; + } +} + +// Finds the survivor bot that took over an idle player +int GetSpectatorClient(int bot) { + if(!IsFakeClient(bot)) return -1; + static char netclass[16]; + GetEntityNetClass(bot, netclass, sizeof(netclass)); + if(strcmp(netclass, "SurvivorBot") == 0 ) { + int user = GetEntProp(bot, Prop_Send, "m_humanSpectatorUserID"); + if(user > 0) return GetClientOfUserId(user); + } + return -1; +} + +stock bool IsPlayerIncapped(int client) { + return GetEntProp(client, Prop_Send, "m_isIncapacitated") == 1; +} + +#define MAX_TYPOS_LENGTH 16 +StringMap TYPOS_DICT; +void LoadTypos() { + TYPOS_DICT.Clear(); + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/ftt_typos.txt"); + + if(!FileExists(sPath)) { + PrintToServer("[FTT] Missing typos list: data/ftt_typos.txt"); + return; + } + File file = OpenFile(sPath, "r", false, NULL_STRING); + if(file == null) { + PrintToServer("[FTT] Cannot open: data/ftt_typos.txt"); + return; + } + + + char buffer[140], key[32]; + while(file.ReadLine(buffer, sizeof(buffer))) { + int index = SplitString(buffer, " ", key, sizeof(key)); + TYPOS_DICT.SetString(key, buffer[index]); + } + + file.Close(); +} + +#define MAX_PHRASES_PER_WORD 8 +#define MAX_PHRASE_LENGTH 191 +StringMap REPLACEMENT_PHRASES; +ArrayList fullMessagePhraseList; + +/* Example: +exWord +{ + "1" "phrase1" + "2" "phrase2" +} +*/ +void LoadPhrases() { + KeyValues kv = new KeyValues("Phrases"); + ArrayList phrases = new ArrayList(ByteCountToCells(MAX_PHRASE_LENGTH)); + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/ftt_phrases.cfg"); + + if(!FileExists(sPath) || !kv.ImportFromFile(sPath)) { + delete kv; + PrintToServer("[FTT] Could not load phrase list from data/ftt_phrases.cfg"); + return; + } + char word[32]; + char phrase[MAX_PHRASE_LENGTH]; + // Go through all the words: + kv.GotoFirstSubKey(); + int i = 0; + char buffer[4]; + do { + kv.GetSectionName(word, sizeof(word)); + StringToLower(word); + phrases.Clear(); + for(;;) { + IntToString(++i, buffer, sizeof(buffer)); + kv.GetString(buffer, phrase, MAX_PHRASE_LENGTH, "_null"); + if(strcmp(phrase, "_null") == 0) break; + phrases.PushString(phrase); + } + i = 0; + if(StrEqual(word, "_full message phrases")) { + fullMessagePhraseList = phrases.Clone(); + continue; + } + #if defined DEBUG_PHRASE_LOAD + PrintToServer("Loaded %d phrases for word \"%s\"", phrases.Length, word); + #endif + REPLACEMENT_PHRASES.SetValue(word, phrases.Clone(), true); + } while (kv.GotoNextKey(false)); + delete kv; +} + +ArrayList GetPhrasesArray(const char[] key) { + int len = strlen(key); + char[] keyLower = new char[len]; + for(int i = 0; i < len; i++) { + keyLower[i] = CharToLower(key[i]); + } + ArrayList phrases; + if(REPLACEMENT_PHRASES.GetValue(keyLower, phrases)) { + return phrases; + } else { + return null; + } +} + + +stock int FindClosestClientAdminPriority(int source, float pos[3]) { + int c = FindClosestAdmin(source, pos); + if(c == -1) return FindClosestClient(source, true,pos); + else return c; +} + +stock int FindClosestClient(int source, bool ignoreBots, float pos[3]) { + int closest = -1; + float minDist = -1.0; + static float pos1[3]; + static float pos2[3]; + GetClientAbsOrigin(source, pos1); + for(int i = 1; i <= MaxClients; i++) { + if(i != source && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && (!ignoreBots || !IsFakeClient(i)) ) { + GetClientAbsOrigin(i, pos2); + float dist = GetVectorDistance(pos1, pos2); + if(minDist == -1.0 || dist <= minDist) { + closest = i; + minDist = dist; + } + } + } + GetClientEyePosition(closest, pos); + return closest; +} + +stock int FindClosestAdmin(int source, float pos[3]) { + int closest = -1; + float minDist = -1.0; + static float pos1[3]; + static float pos2[3]; + GetClientAbsOrigin(source, pos); + for(int i = 1; i <= MaxClients; i++) { + if(i != source && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && !IsFakeClient(i) && GetUserAdmin(i) != INVALID_ADMIN_ID) { + GetClientAbsOrigin(i, pos2); + float dist = GetVectorDistance(pos1, pos2, true); + if(minDist == -1.0 || dist <= minDist) { + closest = i; + minDist = dist; + } + } + } + GetClientEyePosition(closest, pos); + return closest; +} + +int SpawnItem(const char[] itemName, float pos[3], float ang[3] = NULL_VECTOR) { + static char classname[32]; + Format(classname, sizeof(classname), "weapon_%s", itemName); + int spawner = CreateEntityByName(classname); + if(spawner == -1) return -1; + DispatchKeyValue(spawner, "solid", "6"); + // DispatchKeyValue(entity_weapon, "model", g_bLeft4Dead2 ? g_sWeaponModels2[model] : g_sWeaponModels[model]); + DispatchKeyValue(spawner, "rendermode", "3"); + DispatchKeyValue(spawner, "disableshadows", "1"); + TeleportEntity(spawner, pos, ang, NULL_VECTOR); + DispatchSpawn(spawner); + TeleportEntity(spawner, pos, ang, NULL_VECTOR); + return spawner; +} + +bool IsAnyPlayerNear(int source, float range) { + static float pos1[3]; + static float pos2[3]; + GetClientAbsOrigin(source, pos1); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && i != source) { + GetClientAbsOrigin(i, pos2); + float dist = GetVectorDistance(pos1, pos2); + if(dist <= range) return true; + } + } + return false; +} + +void ThrowItemToPlayer(int victim, int target, int slot) { + int wpn = GetPlayerWeaponSlot(victim, slot); + if(wpn > 0 && (slot != 1 || DoesClientHaveMelee(victim))) { + static float pos[3]; + GetClientAbsOrigin(target, pos); + SDKHooks_DropWeapon(victim, wpn, pos); + } +} + + +stock void AddInFrontOf(float fVecOrigin[3], float fVecAngle[3], float fUnits, float fOutPut[3]) { + float fVecView[3]; GetViewVector(fVecAngle, fVecView); + + fOutPut[0] = fVecView[0] * fUnits + fVecOrigin[0]; + fOutPut[1] = fVecView[1] * fUnits + fVecOrigin[1]; + fOutPut[2] = fVecView[2] * fUnits + fVecOrigin[2]; +} +stock void GetViewVector(float fVecAngle[3], float fOutPut[3]) { + fOutPut[0] = Cosine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[1] = Sine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[2] = -Sine(fVecAngle[0] / (180 / FLOAT_PI)); +} +stock void LookAtClient(int iClient, int iTarget) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + static float fFinalPos[3]; + + GetClientEyePosition(iClient, fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} + + +stock int GetClientRealHealth(int client) { + if(!client || !IsValidEntity(client) || !IsClientInGame(client) || !IsPlayerAlive(client) || IsClientObserver(client)) { + return -1; + } else if(GetClientTeam(client) != 2) { + return GetClientHealth(client); + } + float buffer = GetEntPropFloat(client, Prop_Send, "m_healthBuffer"); + float tempHealth = 0.0; + if(buffer > 0.0) { + float difference = GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime"); + float decay = FindConVar("pain_pills_decay_rate").FloatValue; + float constant = 1.0 / decay; + tempHealth = buffer - (difference / constant); + if(tempHealth < 0.0) { + tempHealth = 0.0; + } + } + return RoundToFloor(GetClientHealth(client) + tempHealth); +} + + +/// Returns TRUE if set, FALSE if not (if no weapon to shoot) +bool SetBotTarget(int bot, int target, int targetHP, int loops = 15) { + if(pdata[target].shootAtTarget == bot) { + return false; + } else if(pdata[target].shootAtTarget > 0) { + return false; + } + LookAtClient(target, bot); + int weapon = GetPlayerWeaponSlot(target, 0); + if(weapon > -1) { + pdata[target].shootAtTarget = bot; + pdata[target].shootAtLoops = loops; + pdata[bot].shootAtTargetHealth = targetHP; + int ammo = GetEntProp(weapon, Prop_Send, "m_iClip1"); + DataPack pack = new DataPack(); + // Reverse target and bot: + pack.WriteCell(target); + pack.WriteCell(bot); + pack.WriteCell(weapon); + pack.WriteCell(ammo); + CreateTimer(0.1, Timer_ShootReverse, pack, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + return true; + } else { + return false; + } +} + +// Taken from https://forums.alliedmods.net/showthread.php?t=220132&page=2 +stock void ExplodeProjectile(int entity, bool smoke = true) { + SetEntProp(entity, Prop_Data, "m_takedamage", 2); + SetEntProp(entity, Prop_Data, "m_iHealth", 1); + SDKHooks_TakeDamage(entity, 0, 0, 1.0); + if(smoke) + SetEntProp(entity, Prop_Data, "m_nNextThinkTick", 1); //for smoke +} + +stock int CreateProp(const char[] entClass, const char[] model, const float pos[3], const float ang[3] = { 0.0, 0.0, 0.0 }, const float vel[3] = {0.0, 0.0, 0.0}) { + int entity = CreateEntityByName(entClass); + DispatchKeyValue(entity, "model", model); + DispatchKeyValue(entity, "solid", "6"); + DispatchKeyValue(entity, "targetname", "hsprop"); + DispatchKeyValue(entity, "disableshadows", "1"); + TeleportEntity(entity, pos, ang, vel); + DispatchSpawn(entity); + TeleportEntity(entity, pos, ang, vel); + #if defined DEBUG_LOG_MAPSTART + PrintToServer("spawn prop %.1f %.1f %.1f model %s", pos[0], pos[1], pos[2], model[7]); + #endif + return entity; +} + + +public bool Filter_Solid(int entity, int contentsMask, any data) { + return entity <= 0; +} + + +float VEH_MIN[3] = { -30.0, -30.0, 2.0}; +float VEH_MAX[3] = { 30.0, 30.0, 20.0 }; + +bool SpawnCarToPlayer(int target, float distance) { + float pos[3], ang[3]; + GetClientAbsOrigin(target, pos); + pos[2] += 40.0; + GetClientEyeAngles(target, ang); + ang[2] = ang[0] = 0.0; + + float endPos[3]; + GetHorizontalPositionFromOrigin(pos, ang, distance, endPos); + + TR_TraceHullFilter(endPos, pos, VEH_MIN, VEH_MAX, MASK_SOLID, Filter_Solid); + if(TR_DidHit()) { + return false; + } + if(distance > 0.0) + ang[1] -= 180; + float vel[3]; + vel[0] = Cosine(DegToRad(ang[1])) * 1500.0; + vel[1] = Sine(DegToRad(ang[1])) * 1500.0; + int id = CreateProp("prop_physics", MODEL_CAR, endPos, ang, vel); + CreateTimer(6.0, Timer_Delete, id); + return true; +} + +bool SpawnCarOnPlayer(int target) { + float min[3] = { -30.0, -30.0, -2.0}; + float max[3] = { 30.0, 30.0, 50.0 }; + float pos[3]; + float ang[3]; + GetClientEyePosition(target, pos); + GetClientEyeAngles(target, ang); + if(IsAreaClear(pos, ang, min, max)) { + pos[2] += 40.0; + int id = CreateProp("prop_physics", MODEL_CAR, pos, ang); + CreateTimer(4.0, Timer_Delete, id); + return true; + } + return false; +} + +bool g_iPendingSurvivorAdd; +int isCustomSurvivor[MAXPLAYERS+1]; + +bool AddSurvivor() { + if (GetClientCount(false) >= MaxClients - 1) { + return false; + } + + int i = CreateFakeClient("FTTSurvivorBot"); + bool result; + if (i > 0) { + if (DispatchKeyValue(i, "classname", "SurvivorBot")) { + ChangeClientTeam(i, 2); + + if (DispatchSpawn(i)) { + result = true; + } + } + + g_iPendingSurvivorAdd = true; + CreateTimer(0.2, Timer_KickBot, i); + } + return result; +} + +void ClearInventory(int client) { + for(int i = 0; i <= 5; i++) { + int item = GetPlayerWeaponSlot(client, i); + if(item > 0) { + AcceptEntityInput(item, "Kill"); + } + } +} + +void StopHealingBots() { + healTargetPlayer = 0; + for(int i = 1; i <= MaxClients; i++) { + pdata[i].flags &= ~view_as(Flag_IsTargettingHealer); + if(isCustomSurvivor[i]) { + ClearInventory(i); + KickClient(i); + } + } + delete stopHealingTimer; + if(hAbmAutoHard != null) hAbmAutoHard.IntValue = wasAbmAutoHard; + if(hSbFixEnabled != null) hSbFixEnabled.BoolValue = wasSbFixEnabled; +} + + +bool IsAnySurvivorInRange(const float origin[3], float range, int ignorePlayer = 0) { + float pos[3]; + range = range * range; + for(int i = 1; i <= MaxClients; i++) { + if(i != ignorePlayer && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + GetClientAbsOrigin(i, pos); + if(GetVectorDistance(origin, pos, true) <= range) { + return true; + } + } + } + return false; +} + +int GetRandomThrowableMagnetTarget(ProjectileMagnetType type, int owner = -1) { + static int throwMagnetIndex; + if(throwMagnetIndex == 0) throwMagnetIndex = GetTrollID("Projectile Magnet"); + ArrayList checkList = new ArrayList(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && Trolls[throwMagnetIndex].IsActive(i)) { + if(type == ProjType_Survivors) { + // If the projectile is not owned by player, check if troll flag not enabled + if(owner != i && ~Trolls[throwMagnetIndex].activeFlagClients[i] & view_as(ProjType_Survivors)) continue; + } else if(~Trolls[throwMagnetIndex].activeFlagClients[i] & view_as(type)) { + // Skip if client does not have flag + continue; + } + checkList.Push(i); + } + } + int target = -1; + if(checkList.Length > 0) { + target = checkList.Get(0, checkList.Length - 1); + } + delete checkList; + return target; +} + +stock bool CanSeePoint(const float origin[3], const float point[3]) { + TR_TraceRay(origin, point, MASK_ALL, RayType_EndPoint); + + return !TR_DidHit(); // Can see point if no collisions +} + +stock LookAtPoint(int entity, const float destination[3]){ + float angles[3], pos[3], result[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + MakeVectorFromPoints(destination, pos, result); + GetVectorAngles(result, angles); + if(angles[0] >= 270){ + angles[0] -= 270; + angles[0] = (90-angles[0]); + }else{ + if(angles[0] <= 90){ + angles[0] *= -1; + } + } + angles[1] -= 180; + TeleportEntity(entity, NULL_VECTOR, angles, NULL_VECTOR); +} +stock void PrintToConsoleAdmins(const char[] format, any ...) { + char buffer[254]; + + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToConsole(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} + +/** + * Shakes a client's screen with the specified amptitude, + * frequency & duration. + * + * @param client Client Index. + * @param amplitude Shake magnitude/amplitude. + * @param frequency Shake noise frequency. + * @param duration Shake lasts this long. + * @return True on success, false otherwise. + */ +stock bool ShakePlayer(int client, float amplitude=50.0, float frequency=150.0, float duration=3.0) { + if (amplitude <= 0.0) { + return false; + } + Handle userMessage = StartMessageOne("Shake", client); + if (userMessage == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + PbSetInt(userMessage, "command", 0); + PbSetFloat(userMessage, "local_amplitude", amplitude); + PbSetFloat(userMessage, "frequency", frequency); + PbSetFloat(userMessage, "duration", duration); + } else { + BfWriteByte(userMessage, 0); // Shake Command + BfWriteFloat(userMessage, amplitude); // shake magnitude/amplitude + BfWriteFloat(userMessage, frequency); // shake noise frequency + BfWriteFloat(userMessage, duration); // shake lasts this long + } + EndMessage(); + return true; +} + +void SetSlot(int client, int slot) { + if(slot == -1) + slot = GetRandomInt(0, 4); + static char slotStr[8]; + Format(slotStr, sizeof(slotStr), "slot%d", slot); + ClientCommand(client, slotStr); +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/specials.inc b/scripting/include/feedthetrolls/specials.inc new file mode 100644 index 0000000..e7e7e0b --- /dev/null +++ b/scripting/include/feedthetrolls/specials.inc @@ -0,0 +1,222 @@ + +enum SpecialType { + Special_Invalid = -1, + Special_Smoker = 1, + Special_Boomer, + Special_Hunter, + Special_Spitter, + Special_Jockey, + Special_Charger, + Special_Witch, + Special_Tank +} + + +enum struct SpecialSpawnRequest { + SpecialType type; + int targetUserId; + float position[3]; + float angle[3]; + int flags; +} + +ArrayList g_spSpawnQueue; + +// Finds position, sends to SpawnSpecialAtPosition +// target client index +stock bool SpawnSpecialForTarget(SpecialType specialType, int target, int spawnFlags = view_as(Special_Anywhere)) { + static float pos[3]; + + if(spawnFlags & view_as(Special_OnTarget)) { + static float ang[3]; + static float testPos[3]; + testPos = pos; + + GetClientAbsOrigin(target, pos); + GetClientEyeAngles(target, ang); + + if(specialType == Special_Jockey || specialType == Special_Boomer || specialType == Special_Spitter) { // Else spawn a little bit off, and above (above for jockeys) + pos[2] += 25.0; + pos[0] += 5.0; + } else { //If not jockey/hunter find a suitable area that is at least 5 m away + float minDistance = GetIdealMinDistance(specialType); + GetHorizontalPositionFromOrigin(pos, ang, minDistance, testPos); + if(!FindSuitablePosition(pos, testPos, minDistance, 100)) { + PrintToServer("[FTT] Could not find suitable position, trying in front"); + GetHorizontalPositionFromOrigin(pos, ang, -minDistance, testPos); + if(!FindSuitablePosition(pos, testPos, minDistance, 50)) { + PrintToServer("[FTT] Could not find suitable position, falling back"); + if(spawnFlags & view_as(Special_SpawnDirectOnFailure)) + GetClientAbsOrigin(target, testPos); + else + L4D_GetRandomPZSpawnPosition(target, view_as(specialType), 10, testPos); + } + } + pos = testPos; + } + pos[2] += 1.0; + return SpawnSpecialAtPosition(specialType, pos, ang, target, spawnFlags); + } + // Spawn via director, or fail + if(!L4D_GetRandomPZSpawnPosition(target, view_as(specialType), 10, pos)) { + if(spawnFlags & view_as(Special_SpawnDirectOnFailure)) + GetClientAbsOrigin(target, pos); + else + return false; + } + return SpawnSpecialAtPosition(specialType, pos, NULL_VECTOR, target, spawnFlags); +} + +// Target is optional +stock bool SpawnSpecialAtPosition(SpecialType specialType, const float destination[3], const float angle[3], int target = 0, int spawnFlags = 0) { + int internalFlags = 0; + if(spawnFlags & view_as(Special_AlwaysTarget)) { + internalFlags |= view_as(SPI_AlwaysTarget); + } + if(spawnFlags & view_as(Special_KillOnIncap)) { + internalFlags |= view_as(SPI_KillOnTargetIncap); + } + if(spawnFlags & view_as(Special_OnTarget)) { + if(specialType == Special_Boomer || specialType == Special_Spitter) + internalFlags |= view_as(SPI_KillOnSpawn); + } + SpecialSpawnRequest request; + request.type = specialType; + if(target) + request.targetUserId = GetClientUserId(target); + request.flags = internalFlags; + request.position = destination; + request.angle = angle; + g_spSpawnQueue.PushArray(request); + if(!spIsActive) ProcessSpecialQueue(); + return true; +} + +SpecialSpawnRequest spActiveRequest; + +// On spawn, keep id +// timer checks if passed id still == kept id, if so, it failed. +int g_iSpId; + +bool ProcessSpecialQueue() { + if(g_spSpawnQueue.Length > 0) { + if(g_spSpawnQueue.GetArray(0, spActiveRequest, sizeof(spActiveRequest))) { + spIsActive = true; + CreateTimer(2.0, Timer_CheckSpecialSpawned, g_iSpId); + } + g_spSpawnQueue.Erase(0); + + int target = GetClientOfUserId(spActiveRequest.targetUserId); + if(view_as(spActiveRequest.type) <= 6) { + // CreateTimer(2.0, Timer_CheckSpecialSpawn, spCurrentId); + int bot = CreateFakeClient("FTTSpecialBot"); + if (bot != 0) { + ChangeClientTeam(bot, 3); + CreateTimer(0.1, Timer_KickBot, bot); + } + CheatCommand(target, "z_spawn_old", SPECIAL_NAMES[view_as(spActiveRequest.type) - 1], "auto"); + return true; + } else if(spActiveRequest.type == Special_Witch) { + int witch = L4D2_SpawnWitch(spActiveRequest.position, spActiveRequest.angle); + DataPack pack; + CreateDataTimer(0.2, Timer_SetWitchTarget, pack); + pack.WriteCell(witch); + pack.WriteCell(spActiveRequest.targetUserId); + if(witch != -1) + SetWitchTarget(witch, target); + spIsActive = false; + return ProcessSpecialQueue(); + } else if(spActiveRequest.type == Special_Tank) { + // BypassLimit(); + int tank = L4D2_SpawnTank(spActiveRequest.position, spActiveRequest.angle); + if(tank > 0 && IsClientConnected(tank)) { + TeleportEntity(tank, spActiveRequest.position, spActiveRequest.angle, NULL_VECTOR); + pdata[tank].attackerTargetUid = spActiveRequest.targetUserId; + pdata[tank].specialAttackFlags = view_as(SPI_AlwaysTarget); + } + spIsActive = false; + return ProcessSpecialQueue(); + } + return false; + } + spIsActive = false; + return false; +} + +Action Timer_SetWitchTarget(Handle h, DataPack pack) { + pack.Reset(); + int witch = pack.ReadCell(); + int target = GetClientOfUserId(pack.ReadCell()); + if(IsValidEntity(witch) && target > 0) { + SetWitchTarget(witch, target); + } + return Plugin_Handled; +} + +stock SpecialType GetSpecialType(const char[] input) { + for(int i = 0; i < 8; i++) { + if(strcmp(SPECIAL_NAMES[i], input, false) == 0) return view_as(i + 1); + } + return Special_Invalid; +} + +stock bool FindSuitablePosition(const float pos[3], float outputPos[3], float minDistance = 19000.0, int tries = 100) { + outputPos = pos; + for(int i = tries; i > 0; i--) { + // Shift position aroudn randomly + outputPos[1] += GetRandomFloat(-35.0, 35.0); + float dist = GetVectorDistance(outputPos, pos, true); + if(dist >= minDistance && L4D2Direct_GetTerrorNavArea(outputPos) != Address_Null) { //5m^2 + return true; + } + } + return false; +} + +float GetIdealMinDistance(SpecialType specialType) { + switch(specialType) { + // /*Boomer*/ case 2: return 1200.0; + case Special_Charger: return 19510.0; + case Special_Smoker: return 20000.0; + case Special_Tank: return 20000.0; + case Special_Spitter: return 15000.0; + default: + return 12000.0; + } +} + +static float TARGET_GROUND_BOUNDS[3] = { 35.0, 35.0, 32.0 }; + +stock bool GetGroundBehind(int client, float vPos[3], float vAng[3]) { + GetClientEyePosition(client, vPos); + GetClientEyeAngles(client, vAng); + vAng[1] -= 180.0; //Flip to behind + vAng[2] = 35.0; //Angle downwards + // vPos[2] -= 500.0; + Handle trace = TR_TraceHullFilterEx(vPos, vAng, TARGET_GROUND_BOUNDS, TARGET_GROUND_BOUNDS, MASK_SOLID, RayFilter_NonClient); + if(!TR_DidHit(trace)) { + delete trace; + return false; + } + TR_GetEndPosition(vPos, trace); + vPos[2] += 32.0; + // FindSuitablePosition(vPos, vPos, 100.0, 100); + delete trace; + + GetClientAbsAngles(client, vAng); + return true; +} + +stock bool RayFilter_NonClient(int entity, int contentsMask) { + if (entity <= 0 || entity > MaxClients) { + if (IsValidEntity(entity)) { + static char eClass[128]; + if (GetEntityClassname(entity, eClass, sizeof(eClass))) { + if (strcmp(eClass, "prop_physics") >= 0) + return false; + } + return true; + } + } + return false; +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/timers.inc b/scripting/include/feedthetrolls/timers.inc new file mode 100644 index 0000000..cb0712e --- /dev/null +++ b/scripting/include/feedthetrolls/timers.inc @@ -0,0 +1,484 @@ + +Action Timer_ThrowTimer(Handle timer, int client) { + if(!IsClientInGame(client)) { + Trolls[t_throwItAllIndex].timerHandles[client] = null; + return Plugin_Stop; + } + ThrowAllItems(client); + return Plugin_Continue; +} +int instantCommonRef[MAXPLAYERS+1]; + +Action Timer_RandomVelocity(Handle h, int client) { + if(!IsClientInGame(client)) { + Trolls[t_randomizeVelocityIndex].timerHandles[client] = null; + return Plugin_Stop; + } + float bounds = 50.0; + if(Trolls[t_randomizeVelocityIndex].activeFlagClients[client] & 2) bounds = 100.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[client] & 4) bounds = 200.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[client] & 8) bounds = 500.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[client] & 16) bounds = 1000.0; + float vel[3]; + GetEntPropVector(client, Prop_Data, "m_vecVelocity", vel); + vel[0] += GetRandomFloat(-bounds, bounds); + vel[1] += GetRandomFloat(-bounds, bounds); + vel[2] += GetRandomFloat(-20.0, 100.0); + SetAbsVelocity(client, vel); + return Plugin_Continue; +} + +Action Timer_Main(Handle timer) { + static int loopTick; + + static int slowDrainIndex; + if(!slowDrainIndex) slowDrainIndex = GetTrollID("Slow Drain"); + static int tempHealthQuickDrainIndex; + if(!tempHealthQuickDrainIndex) tempHealthQuickDrainIndex = GetTrollID("Temp Health Quick Drain"); + static int swarmIndex; + if(!swarmIndex) swarmIndex = GetTrollID("Swarm"); + static int instantCommonIndex; + if(!instantCommonIndex) instantCommonIndex = GetTrollID("Instant Commons"); + static int randomizeAmmoIndex; + if(!randomizeAmmoIndex) randomizeAmmoIndex = GetTrollID("Randomize Clip Ammo"); + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + if(Trolls[t_randomizeAnglesIndex].IsActive(i)) { + float chance = 0.10; + if(Trolls[t_randomizeAnglesIndex].activeFlagClients[i] & 2) chance = 0.35; + else if(Trolls[t_randomizeAnglesIndex].activeFlagClients[i] & 4) chance = 0.58; + else if(Trolls[t_randomizeAnglesIndex].activeFlagClients[i] & 8) chance = 0.90; + else if(Trolls[t_randomizeAnglesIndex].activeFlagClients[i] & 16) chance = 1.00; + if(GetURandomFloat() < chance) { + float ang[3]; + ang[0] = GetRandomFloat(-180.0, 180.0); + ang[1] = GetRandomFloat(-180.0, 180.0); + TeleportEntity(i, NULL_VECTOR, ang, NULL_VECTOR); + } + } + if(Trolls[t_randomizeVelocityIndex].IsActive(i)) { + float bounds = 50.0; + if(Trolls[t_randomizeVelocityIndex].activeFlagClients[i] & 2) bounds = 100.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[i] & 4) bounds = 200.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[i] & 8) bounds = 500.0; + else if(Trolls[t_randomizeVelocityIndex].activeFlagClients[i] & 16) bounds = 1000.0; + float vel[3]; + GetEntPropVector(i, Prop_Data, "m_vecVelocity", vel); + vel[0] += GetRandomFloat(-bounds, bounds); + vel[1] += GetRandomFloat(-bounds, bounds); + vel[2] += GetRandomFloat(-100.0, 150.0); + SetAbsVelocity(i, vel); + } + if(Trolls[slowDrainIndex].IsActive(i)) { + if(loopTick % 4 == 0) { + int hp = GetClientHealth(i); + if(hp > 50) { + SetEntProp(i, Prop_Send, "m_iHealth", hp - 1); + } + } + } + if(Trolls[tempHealthQuickDrainIndex].IsActive(i)) { + if(loopTick % 3 == 0) { + float bufferTime = GetEntPropFloat(i, Prop_Send, "m_healthBufferTime"); + float tempHealth = L4D_GetTempHealth(i); + if(tempHealth > 0.0) { + SetEntPropFloat(i, Prop_Send, "m_healthBufferTime", bufferTime - 7.0); + } + } + } + if(Trolls[swarmIndex].IsActive(i)) { + L4D2_RunScript("RushVictim(GetPlayerFromUserID(%d), %d)", GetClientUserId(i), 15000); + } + if(Trolls[t_slipperyShoesIndex].IsActive(i) && Trolls[t_slipperyShoesIndex].activeFlagClients[i] & 1) { + if(GetRandomFloat() <= 0.4) { + L4D_StaggerPlayer(i, i, NULL_VECTOR); + } + } + if(Trolls[instantCommonIndex].IsActive(i)) { + int common = EntRefToEntIndex(instantCommonRef[i]); + if(common <= 0 || !IsValidEntity(common)) { + static float pos[3]; + GetHorizontalPositionFromClient(i, Trolls[instantCommonIndex].activeFlagClients[i] & 1 ? -40.0 : 40.0, pos); + common = L4D_SpawnCommonInfected(pos); + instantCommonRef[i] = EntIndexToEntRef(common); + } + SetEntPropEnt(common, Prop_Send, "m_clientLookatTarget", i); + SetEntProp(common, Prop_Send, "m_nSequence", 96); + } + if(loopTick % 60 && Trolls[randomizeAmmoIndex].IsActive(i)) { + int primaryWpn = GetPlayerWeaponSlot(i, 0); + if(primaryWpn > 0) { + int maxCap = GetEntProp(primaryWpn, Prop_Send, "m_iClip1"); + SetEntProp(primaryWpn, Prop_Send, "m_iClip1", GetRandomInt(0, maxCap)); + } + } + if(Trolls[t_vomitPlayerIndex].IsActive(i)) { + if(loopTick % 4 == 0) { + L4D_CTerrorPlayer_OnVomitedUpon(i, i); + } + } + if(Trolls[t_shakeyCameraIndex].IsActive(i)) { + float amplitude = 1.0; + float freq = 1.0; + if(Trolls[t_shakeyCameraIndex].activeFlagClients[i] & 1) { + amplitude = 1.0; + freq = 1.0; + } else if(Trolls[t_shakeyCameraIndex].activeFlagClients[i] & 2) { + amplitude = 5.0; + freq = 5.0; + } else if(Trolls[t_shakeyCameraIndex].activeFlagClients[i] & 4) { + amplitude = 20.0; + freq = 20.0; + } else if(Trolls[t_shakeyCameraIndex].activeFlagClients[i] & 8) { + amplitude = 50.0; + freq = 50.0; + } else if(Trolls[t_shakeyCameraIndex].activeFlagClients[i] & 16) { + amplitude = 100.0; + freq = 200.0; + } + ShakePlayer(i, amplitude, freq, MAIN_TIMER_INTERVAL_S + 2.0); + } + if(Trolls[t_slotRouletteIndex].IsActive(i) && Trolls[t_slotRouletteIndex].activeFlagClients[i] & 8) { + float chance = 1.0; + if(Trolls[t_slotRouletteIndex].activeFlagClients[i] & 16) { + chance = 0.05; + } else if(Trolls[t_slotRouletteIndex].activeFlagClients[i] & 32) { + chance = 0.2; + } else if(Trolls[t_slotRouletteIndex].activeFlagClients[i] & 64) { + chance = 0.4; + } + + if(GetURandomFloat() < chance) { + SetSlot(i, -1); + } + } + if(Trolls[t_hideHUDIndex].IsActive(i)) { + HideHUDRandom(i); + } + } + } + if(++loopTick >= 60) { + loopTick = 0; + } + return Plugin_Continue; +} +Action Timer_SlotRoulette(Handle h, int client) { + if(!IsClientInGame(client)) { + Trolls[t_slotRouletteIndex].timerHandles[client] = null; + return Plugin_Stop; + } + if(Trolls[t_slotRouletteIndex].activeFlagClients[client] & 8) { + float chance = 1.0; + if(Trolls[t_slotRouletteIndex].activeFlagClients[client] & 16) { + chance = 0.1; + } else if(Trolls[t_slotRouletteIndex].activeFlagClients[client] & 32) { + chance = 0.3; + } else if(Trolls[t_slotRouletteIndex].activeFlagClients[client] & 64) { + chance = 0.5; + } + + if(GetURandomFloat() < chance) { + SetSlot(client, -1); + } + } + return Plugin_Continue; +} +Action Timer_GivePistol(Handle timer, int user) { + int client = GetClientOfUserId(user); + if(client > 0) { + int flags = GetCommandFlags("give"); + SetCommandFlags("give", flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "give pistol"); + SetCommandFlags("give", flags); + } + return Plugin_Handled; +} + +Action Timer_ThrowWeapon(Handle timer, Handle pack) { + ResetPack(pack); + float dest[3]; + dest[0] = ReadPackFloat(pack); + dest[1] = ReadPackFloat(pack); + dest[2] = ReadPackFloat(pack); + int slot = ReadPackCell(pack); + int victim = ReadPackCell(pack); + + int wpnRef = GetPlayerWeaponSlot(victim, slot); + if(wpnRef != -1) { + int wpn = EntRefToEntIndex(wpnRef); + if(wpn != INVALID_ENT_REFERENCE) { + if(slot == 1) { + static char name[16]; + GetEdictClassname(wpn, name, sizeof(name)); + if(!StrEqual(name, "weapon_pistol", false)) { + SDKHooks_DropWeapon(victim, wpn, dest); + CreateTimer(0.2, Timer_GivePistol, GetClientUserId(victim)); + } + }else + SDKHooks_DropWeapon(victim, wpn, dest); + } + } + return Plugin_Handled; +} + +Action Timer_ResetAutoPunish(Handle timer, int user) { + int client = GetClientOfUserId(user); + if(client) { + if(hAutoPunish.IntValue & 2 == 2) + DisableTroll(client, "Special Magnet"); + if(hAutoPunish.IntValue & 1 == 1) + DisableTroll(client, "Tank Magnet"); + } + return Plugin_Handled; +} + +Action Timer_NextWitchSet(Handle timer, DataPack pack) { + pack.Reset(); + int client = GetClientOfUserId(pack.ReadCell()); + int witch = pack.ReadCell(); + SetWitchTarget(witch, client); + return Plugin_Handled; +} + +Action Timer_KickBot(Handle timer, int client) { + if(IsClientInGame(client) && !IsClientInKickQueue(client) && IsFakeClient(client)) { + KickClient(client); + } + return Plugin_Handled; +} + +Action Timer_Delete(Handle h, int id) { + if(IsValidEntity(id)) + AcceptEntityInput(id, "Kill"); + return Plugin_Handled; +} + +Action Timer_ShootReverse(Handle h, DataPack pack) { + pack.Reset(); + int attacker = pack.ReadCell(); + int target = pack.ReadCell(); + int weapon = pack.ReadCell(); + int ammo = pack.ReadCell(); + + + if(!IsClientConnected(target) || !IsClientConnected(attacker) || attacker > MaxClients || target > MaxClients) return Plugin_Stop; + static float targetPos[3], botAngles[3], botPosition[3]; + GetClientAbsOrigin(attacker, targetPos); + GetClientAbsAngles(attacker, botAngles); + GetClientAbsOrigin(attacker, botPosition); + + botAngles[1] = RadToDeg(ArcTangent2( botPosition[1] - targetPos[1], botPosition[0] - targetPos[0])) + 180.0; + TeleportEntity(attacker, NULL_VECTOR, botAngles, NULL_VECTOR); + pdata[attacker].shootAtLoops--; + if(IsValidEntity(weapon)) + SetEntProp(weapon, Prop_Send, "m_iClip1", ammo); + if(pdata[attacker].shootAtLoops > 0 && GetClientRealHealth(target) > pdata[target].shootAtTargetHealth) { + return Plugin_Continue; + } else { + pdata[attacker].shootAtTarget = 0; + pdata[attacker].shootAtLoops = 0; + pdata[attacker].shootAtTargetHealth = 0; + return Plugin_Stop; + } +} +// We check if the special never spawned (g_iSpId never advances, and run the next in queue) +// Prevents the queue from stalling +Action Timer_CheckSpecialSpawned(Handle h, int id) { + if(g_iSpId == id) { + PrintToServer("[FTT] Special did not spawn in time, continuing."); + g_iSpId++; + ProcessSpecialQueue(); + } + return Plugin_Handled; +} + +Action Timer_CheckIsInSpit(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client && GetGameTime() - pdata[userid].lastInSpitTime > 3.0) { + SetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue", 1.0); + pdata[client].flags &= ~view_as(Flag_HasSpitTimer); + return Plugin_Stop; + } + return Plugin_Continue; +} + +float CHARGER_CHECK_MIN[3] = { -15.0, -15.0, 2.0}; +float CHARGER_CHECK_MAX[3] = { 15.0, 15.0, 20.0 }; + +Action Timer_CheckForChargerOpportunity(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client) { + int activator = GetClientOfUserId(pdata[client].smartChargeActivator); + if(!activator) { + pdata[client].smartChargeActivator = 0; + } + float pos[3], ang[3], endPos[3], spawnPos[3]; + GetClientAbsOrigin(client, pos); + GetClientEyeAngles(client, ang); + + GetHorizontalPositionFromOrigin(pos, ang, -150.0, endPos); + TR_TraceHullFilter(endPos, pos, CHARGER_CHECK_MIN, CHARGER_CHECK_MAX, MASK_SOLID, Filter_CheckChargerValid, client); + if(!TR_DidHit()) { + spawnPos = endPos; + GetHorizontalPositionFromOrigin(pos, ang, 500.0, endPos); + TR_TraceHullFilter(endPos, pos, CHARGER_CHECK_MIN, CHARGER_CHECK_MAX, MASK_SOLID, Filter_CheckChargerValid, client); + if(!TR_DidHit()) { + SpawnSpecialAtPosition(Special_Charger, spawnPos, ang, client, view_as(Special_AlwaysTarget)); + if(activator) PrintToChat(activator, "Auto charge %N successfully after %d tries", client, pdata[client].smartChargeAttempts); + pdata[client].smartChargeAttempts = 0; + pdata[client].smartChargeActivator = 0; + return Plugin_Stop; + } + } + if(++pdata[client].smartChargeAttempts > pdata[client].smartChargeMaxAttempts) { + if(activator) PrintToChat(activator, "Auto charge timed out after %d attempts", pdata[client].smartChargeAttempts); + pdata[client].smartChargeAttempts = 0; + pdata[client].smartChargeActivator = 0; + DisableTroll(client, "Smart Charge"); + return Plugin_Stop; + } + return Plugin_Continue; + } + return Plugin_Stop; +} + +public bool Filter_CheckChargerValid(int entity, int contentsMask, any data) { + return entity <= 0 || entity >= MaxClients || (entity != data && GetClientTeam(entity) == 2); +} + +public Action Timer_UpdateHealTargetPos(Handle h) { + int healTarget = GetClientOfUserId(healTargetPlayer); + if(healTarget == 0) { + PrintToServer("[FTT] Dep Bots: Lost heal target, stopping"); + return Plugin_Stop; + } + GetAbsOrigin(healTarget, healTargetPos); + int bots = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsFakeClient(i) && pdata[i].flags & view_as(Flag_IsTargettingHealer)) { + bots++; + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%d),pos=Vector(%f,%f,%f)})", GetClientUserId(i), healTargetPos[0], healTargetPos[1], healTargetPos[2]); + int kit = GetPlayerWeaponSlot(i, 3); + if(kit > -1) { + SetEntPropEnt(i, Prop_Send, "m_hActiveWeapon", kit); + } + } + } + return bots > 0 ? Plugin_Continue : Plugin_Stop; +} + +Action Timer_SpawnHealBots(Handle h, int max) { + static int count; + if(count < max) { + if(!AddSurvivor()) { + count = 0; + CreateTimer(0.5, Timer_SpawnHealBotsPost); + return Plugin_Stop; + } + count++; + return Plugin_Continue; + } + count = 0; + CreateTimer(0.5, Timer_SpawnHealBotsPost); + return Plugin_Stop; +} + +Action Timer_SpawnHealBotsPost(Handle h) { + PrintToServer("bots post"); + char classname[32]; + for(int i = 1; i <= MaxClients; i++) { + if(isCustomSurvivor[i]) { + int kit = GetPlayerWeaponSlot(i, 3); + if(kit > 0) { + GetEntityClassname(kit, classname, sizeof(classname)); + if(StrEqual(classname, "weapon_first_aid_kit")) { + continue; + } + } + GiveClientWeapon(i, "weapon_first_aid_kit"); + pdata[i].flags &= view_as(Flag_IsTargettingHealer); + } + } + return Plugin_Handled; +} +Action Timer_StopHealBots(Handle h, DataPack pack) { + pack.Reset(); + int activator = GetClientOfUserId(pack.ReadCell()); + int victim = GetClientOfUserId(pack.ReadCell()); + if(activator) { + PrintToChat(activator, "Dep bots has expired"); + } + if(victim) { + DisableTroll(victim, "Dep Bots"); + } + StopHealingBots(); + return Plugin_Stop; +} + + +#define NO_ATTEMPT_MAX_DIST 1000.0 +#define NO_ATTEMPT_MAX_DIST_OPT NO_ATTEMPT_MAX_DIST * NO_ATTEMPT_MAX_DIST + + +Action Timer_WaitForApex(Handle h, int entref) { + if(!IsValidEntity(entref)) return Plugin_Stop; + int entity = EntRefToEntIndex(entref); + + static float pos[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + + if(entLastHeight[entity] > pos[2]) { + char classname[32]; + GetEntityClassname(entity, classname, sizeof(classname)); + + int target; + if(StrEqual(classname, "tank_rock") || StrEqual(classname, "spitter_projectile")) + target = GetRandomThrowableMagnetTarget(ProjType_Specials); + else if(StrEqual(classname, "prop_physics") || StrEqual(classname, "prop_car_alarm")) + target = GetRandomThrowableMagnetTarget(ProjType_Cars) + else { + int entOwner = GetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity"); + target = GetRandomThrowableMagnetTarget(ProjType_Survivors, entOwner); + } + + if(target > 0) { + float targetPos[3], vel[3]; + GetClientAbsOrigin(target, targetPos); + TR_TraceRay(pos, targetPos, MASK_SHOT, RayType_EndPoint); + if(TR_DidHit()) { + TR_GetEndPosition(pos); + if(GetVectorDistance(pos, targetPos, true) > NO_ATTEMPT_MAX_DIST_OPT) { + return Plugin_Stop; + } + } + + // SetEntityMoveType(entity, MOVETYPE_FLY); + SetEntityGravity(entity, 0.001); + float distance = GetVectorDistance(pos, targetPos); + SubtractVectors(targetPos, pos, vel); + ScaleVector(vel, 1000.0 / distance); + TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, vel); + + CreateTimer(3.0, Timer_ResetGravity, entref); + } + return Plugin_Stop; + } + entLastHeight[entity] = pos[2]; + return Plugin_Continue; +} + +Action Timer_ResetGravity(Handle h, int entref) { + if(IsValidEntity(entref)) { + int entity = EntRefToEntIndex(entref); + SetEntityGravity(entity, 800.0); // could pull from sv_gravity but no ones gonna notice + } + return Plugin_Handled; +} +Action Timer_RestoreHud(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0) { + SetEntProp(client, Prop_Send, "m_iHideHUD", 0); + } + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/include/feedthetrolls/trolls.inc b/scripting/include/feedthetrolls/trolls.inc new file mode 100644 index 0000000..feca0cb --- /dev/null +++ b/scripting/include/feedthetrolls/trolls.inc @@ -0,0 +1,560 @@ +// UP THE VALUE 'MAX_TROLLS' in base.inc before adding new ones! + +int t_slipperyShoesIndex = 0; +int t_stickyGooIndex = 0; +int t_invertedTrollIndex; +int t_randomizeAnglesIndex; +int t_randomizeVelocityIndex; +int t_vomitPlayerIndex; +int t_shakeyCameraIndex; +int t_slotRouletteIndex; +int t_damageBoostIndex; +int t_reverseFFIndex; +int t_throwItAllIndex; +int t_hideHUDIndex; + +void SetupTrolls() { + trollKV = new StringMap(); + categories = new ArrayList(ByteCountToCells(16)); + gRandomClients = new ArrayList(); + int index; + SetupTroll("Reset User", "Resets the user, removes all troll effects", TrollMod_Instant); + + /// CATEGORY: Magnets + SetCategory("Magnets"); + index = SetupTroll("Special Magnet", "Attracts ALL specials to any alive target with this troll enabled", TrollMod_Constant); + AddMagnetFlags(index); + index = SetupTroll("Tank Magnet", "Attracts ALL tanks to any alive target with this troll enabled", TrollMod_Constant); + AddMagnetFlags(index); + #if defined _actions_included + index = SetupTroll("Witch Magnet", "All witches when startled will target any player with this troll", TrollMod_Constant); + #endif + index = SetupTroll("Projectile Magnet", "Makes all projectiles (biles, molotovs, pipes, tank rocks) go to player", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Target Sources", true); + // Tied to: ProjectileMagnetType + Trolls[index].AddFlag("Infected (rocks/goo)", true); + Trolls[index].AddFlag("Teammates (grenades)", false); + Trolls[index].AddFlag("Thrown Tank Objects", false); + + /// CATEGORY: Infected + SetCategory("Infected"); + SetupTroll("Swarm", "Swarms a player with zombies. Requires swarm plugin", TrollMod_Instant | TrollMod_Constant); + t_vomitPlayerIndex = SetupTroll("Vomit Player", "Shortcut to sm_vomitplayer. vomits the player.", TrollMod_Instant | TrollMod_Constant); + index = SetupTroll("Insta Special", "Shortcut to sm_insta", TrollMod_Instant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Around them (Director)", true); + Trolls[index].AddFlag("On top / in-face", false); + SetupTroll("Goo", "Spawns a spitter puddle underneath them", TrollMod_Instant); + index = SetupTroll("Sticky Goo", "Slows player down in goo", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("90% Movement Speed", true); + Trolls[index].AddFlag("80% Movement Speed", false); + Trolls[index].AddFlag("70% Movement Speed", false); + Trolls[index].AddFlag("50% Movement Speed", false); + Trolls[index].AddFlag("30% Movement Speed", false); + Trolls[index].AddFlag("0% Movement Speed", false); + t_stickyGooIndex = index; + index = SetupTroll("Vocalize Specials", "Spawn commons on special vocals", TrollMod_Constant) + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Mute Vocalization", true); + Trolls[index].AddFlag("Do not mute", false); + index = SetupTroll("Instant Commons", "Spawns commons behind or infront", TrollMod_Instant | TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("In Back", true); + Trolls[index].AddFlag("In Front", false); + index = SetupTroll("Smart Charge", "Waits until coast is clear to charge", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Attempt Timeout", false); + Trolls[index].AddFlag("15 Seconds", true); + Trolls[index].AddFlag("30 Seconds", false); + Trolls[index].AddFlag("1 minute", false); + Trolls[index].AddFlag("5 minutes", false); + + // CATEGORY: Projectiles + SetCategory("Projectiles"); + index = SetupTroll("Rock Dropper", "Drops on a rock. On their head.", TrollMod_Instant); + // Trolls[index].AddFlagPrompt(false); + // Trolls[index].AddFlag("Drop From Above", true); + // Trolls[index].AddFlag("From behind", false); + index = SetupTroll("Car Splat", "Car. splats.", TrollMod_Instant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("On Top", true); + Trolls[index].AddFlag("Into (Infront)", false); + Trolls[index].AddFlag("Into (Behind)", false); + index = SetupTroll("Bad Throw", "Player drops throwables on throw, and biles/molotovs themselves", TrollMod_Constant); + Trolls[index].AddFlagPrompt(true); + Trolls[index].AddFlag("Biles", true); + Trolls[index].AddFlag("Molotovs", true); + Trolls[index].AddFlag("Pipebombs", true); + index = SetupTroll("Molotov Bath", "Throws a molotov on their feet", TrollMod_Instant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Normal", true); + Trolls[index].AddFlag("Set the town ablaze", false); + + // CATEGORY: Items + SetCategory("Items"); + index = SetupTroll("Throw It All", "Player throws their item(s) periodically to a nearby player", TrollMod_Instant); + Trolls[index].SetTimer(THROWITALL_INTERVAL, Timer_ThrowTimer); + index = SetupTroll("Spicy Gas", "Gascans player picks up just ignite. Magic.", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Always (100%)", false); + Trolls[index].AddFlag("Half Time (50%)", true); + Trolls[index].AddFlag("Rare (10%)", false); + index = SetupTroll("No Pickup", "Prevents a player from picking up ANY (new) item. Use ThrowItAll to make them drop", TrollMod_Constant); + Trolls[index].AddFlagPrompt(true); + Trolls[index].AddFlag("No Primary", false); + Trolls[index].AddFlag("No Melee", false); + Trolls[index].AddFlag("No Throwables", true); + Trolls[index].AddFlag("No Kits", true); + Trolls[index].AddFlag("No Pills / Adr", true); + Trolls[index].AddFlag("No GASCANS", true); + index = SetupTroll("UziRules / AwpSmells", "Picking up a weapon gives them a UZI or AWP instead", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("UZI Only", true); + Trolls[index].AddFlag("AWP Only", false); + SetupTroll("Primary Disable", "Player cannot pickup any weapons, only melee/pistols", TrollMod_Constant); + index = SetupTroll("Dull Melee", "Player's melee weapon does 0 damage (based on %). Headshots still work", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Always (100%)", false); + Trolls[index].AddFlag("Half Time (50%)", true); + Trolls[index].AddFlag("Rare (10%)", false); + SetupTroll("Nerf Gun", "When they shoot it does no damage.", TrollMod_Constant); + SetupTroll("Randomize Clip Ammo", "Randomly changes their clip ammo downwards", TrollMod_Constant | TrollMod_Instant); + SetupTroll("CameTooEarly", "When they shoot, random chance they empty whole clip", TrollMod_Constant); + index = SetupTroll("Slot Roulette", "Randomize their slots", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Activations:", true); + Trolls[index].AddFlag("On Vomitted", false); // 1 + Trolls[index].AddFlag("On Damage", false); // 2 + Trolls[index].AddFlag("On Vocalize", false); // 4 + Trolls[index].AddFlag("Periodically", true); //8 + Trolls[index].AddCustomFlagPrompt("Frequency:", false, 8); + Trolls[index].AddFlag("Subtle", false); // 16 + Trolls[index].AddFlag("Confusing", false); // 32 + Trolls[index].AddFlag("Annoying", false); // 64 + Trolls[index].AddFlag("Unusable", false); // 128 + Trolls[index].SetTimer(0.2, Timer_SlotRoulette, 8); + t_slotRouletteIndex = index; + + + /// CATEGORY: Chat + SetCategory("Chat"); + SetupTroll("Typoos", "", TrollMod_Constant); + SetupTroll("iCantSpellNoMore", "Chat messages letter will randomly changed with wrong letters", TrollMod_Constant); + index = SetupTroll("No Profanity", "Replaces some words with random phrases", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Only Replace Swears", false); + Trolls[index].AddFlag("Replace Full Messages", true); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Show Modified to Them", true); + Trolls[index].AddFlag("Show Original to Them", false); + index = SetupTroll("Vocalize Gag", "Prevents player from sending any vocalizations (even automatic)", TrollMod_Constant); + // Trolls[index].AddFlagPrompt(false); + // Trolls[index].AddFlag("Mute for All", true); + // Trolls[index].AddFlag("Mute For All But Them", false); + index = SetupTroll("Honk / Meow / Woof", "Custom sounds", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Choose Sound:"); + Trolls[index].AddFlag("Honk", true); + Trolls[index].AddFlag("Meow", false); + Trolls[index].AddFlag("Woof", false); + Trolls[index].AddCustomFlagPrompt("Choose Chat modifier:", false, 1); + Trolls[index].AddFlag("Show Modified to Them", true); + Trolls[index].AddFlag("Show Original to Them", false); + Trolls[index].AddFlag("Show Modified Only To Them", false); + SetupTroll("Reversed", "Reserves their message", TrollMod_Constant); + SetupTroll("Voice Mute", "Mutes from voice", TrollMod_Constant); + SetupTroll("No Rushing Us", "Decreases player speed everytime they yell hurry up", TrollMod_Constant); + + /// CATEGORY: Health + SetCategory("Health"); + t_damageBoostIndex = SetupTroll("Damage Boost", "Makes a player take more damage than normal", TrollMod_Constant); + SetupTroll("Temp Health Quick Drain", "Makes a player's temporarily health drain very quickly", TrollMod_Constant); + SetupTroll("Slow Drain", "Will make the player slowly lose health over time", TrollMod_Constant); + SetupTroll("KillMeSoftly", "Make player eat or waste pills whenever possible", TrollMod_Instant | TrollMod_Constant); + index = SetupTroll("Reverse FF", "All damage dealt to a player is reversed", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Choose Reverse FF", false); + Trolls[index].AddFlag("1:1 Ratio", true); //1 + Trolls[index].AddFlag("2x Ratio", false); //2 + Trolls[index].AddFlag("0.5x Ratio", false); //4 + Trolls[index].AddFlag("0.0x Ratio (None)", false); //8 + Trolls[index].AddFlag("3x Ratio", false); //16 + Trolls[index].AddCustomFlagPrompt("Modes", true); + Trolls[index].AddFlag("Reverse Fire Damage", false); //32 + Trolls[index].AddFlag("Reverse Explosions", false); //64 + t_reverseFFIndex = index; + + + index = SetupTroll("Dep Bots", "Makes bots heal a player. At any cost", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Do not spawn extra", true); // 1 + Trolls[index].AddFlag("Spawn extra bots (broke)", false); // 2 + Trolls[index].AddCustomFlagPrompt("# Of Bots", false); + Trolls[index].AddFlag("1", false); // 4 + Trolls[index].AddFlag("2", false); // 8 + Trolls[index].AddFlag("3", false); // 16 + Trolls[index].AddFlag("4", true); // 32 + Trolls[index].AddFlag("5", false); // 64 + Trolls[index].AddCustomFlagPrompt("Auto Timeout", false, 0); + Trolls[index].AddFlag("Until Healed / Map Change", false); // 128 + Trolls[index].AddFlag("15 seconds", true); // 255 + Trolls[index].AddFlag("30 seconds", false); // 512 + Trolls[index].AddFlag("1 minute", false); //1024 + Trolls[index].AddFlag("5 minutes", false); //2048 + + /// CATEGORY: Movement + SetCategory("Movement"); + index = SetupTroll("Slow Speed", "Sets player speed to 0.8x of normal speed", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("90% Movement Speed", true); + Trolls[index].AddFlag("80% Movement Speed", false); + Trolls[index].AddFlag("70% Movement Speed", false); + Trolls[index].AddFlag("50% Movement Speed", false); + Trolls[index].AddFlag("30% Movement Speed", false); + Trolls[index].AddFlag("0% Movement Speed", false); + SetupTroll("Higher Gravity", "Sets player gravity to 1.3x of normal gravity", TrollMod_Constant); + t_invertedTrollIndex = SetupTroll("Inverted Controls", "Well, aint it obvious", TrollMod_Constant); + SetupTroll("Stagger", "Like a slap, but different", TrollMod_Instant); + index = SetupTroll("Slippery Shoes", "Periodically stumbles around.", TrollMod_Constant); + Trolls[index].AddFlagPrompt(true); + Trolls[index].AddFlag("Periodically", true); + Trolls[index].AddFlag("When using doors", false); + Trolls[index].AddFlag("On throwable use", false); + Trolls[index].AddFlag("On pills/adrenaline use", false); + Trolls[index].AddFlag("On zombie bite", false); + t_slipperyShoesIndex = index; + index = SetupTroll("Randomize Angles", "Randomly change their angles", TrollMod_Constant); + Trolls[index].AddCustomFlagPrompt("Frequency:", false); + Trolls[index].AddFlag("Once in a while", true); //1 + Trolls[index].AddFlag("Periodically", false); //2 + Trolls[index].AddFlag("A lot", false); //4 + Trolls[index].AddFlag("Painful", false); //8 + Trolls[index].AddFlag("Seizure", false); //16 + t_randomizeAnglesIndex = index; + index = SetupTroll("Randomize Velocity", "Randomly change their velocity", TrollMod_Constant); + Trolls[index].SetTimer(0.1, Timer_RandomVelocity); + Trolls[index].AddCustomFlagPrompt("Frequency:", false); + Trolls[index].AddFlag("Loose", true); //1 + Trolls[index].AddFlag("Slippery", false); //2 + Trolls[index].AddFlag("Earthquake", false); //4 + Trolls[index].AddFlag("Severe Earthquake", false); //8 + Trolls[index].AddFlag("Bouncy Castle", false); //16 + t_randomizeVelocityIndex = index; + + /// CATEGORY: MISC + SetCategory("Misc"); + SetupTroll("Gun Jam", "On reload, small chance their gun gets jammed - Can't reload.", TrollMod_Constant); + SetupTroll("No Shove", "Prevents a player from shoving", TrollMod_Constant); + index = SetupTroll("No Button Touchie", "Stops people from pressing buttons", TrollMod_Constant); + Trolls[index].AddFlagPrompt(true); + Trolls[index].AddFlag("Prevent Use", true); + Trolls[index].AddFlag("Vomit On Touch", false); + Trolls[index].AddFlag("Incap On Touch", false); + Trolls[index].AddFlag("Slay On Touch", false); + Trolls[index].AddFlag("0.8x Speed", false); + // TODO: setup instant + index = SetupTroll("Shakey Camera", "Horrible", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + // add flag: vomit on touch + Trolls[index].AddFlag("Annoying but playable", false); + Trolls[index].AddFlag("Bad", true); + Trolls[index].AddFlag("Sickness", false); + Trolls[index].AddFlag("Violent", false); + Trolls[index].AddFlag("Violent XX", false); + t_shakeyCameraIndex = index; + index = SetupTroll("Hide HUD", "Horrible", TrollMod_Constant); + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("Rare & Short", false); + Trolls[index].AddFlag("Sometimes & Medium", false); + Trolls[index].AddFlag("Constantly", true); + t_hideHUDIndex = index; + index = SetupTroll("Meta: Random", "Picks a random troll", TrollMod_Instant); + index = SetupTroll("Meta: Inverse", "Uhm you are not supposed to see this...", TrollMod_Instant); + Trolls[index].hidden = true; + Trolls[index].AddFlagPrompt(false); + Trolls[index].AddFlag("100%", true); + Trolls[index].AddFlag("50%", false); + Trolls[index].AddFlag("10%", false); + + + + + + // Initialize the default flag values to -1 + for(int i = 0; i <= MAX_TROLLS; i++) { + for(int j = 1; j <= MAXPLAYERS; j++) { + Trolls[i].timerHandles[j] = null; + Trolls[i].activeFlagClients[j] = -1; + } + } + +} + +void AddMagnetFlags(int index) { + Trolls[index].AddCustomFlagPrompt("Choose Magnet Chance:", false); + Trolls[index].AddFlag("Always (100%)", true); + Trolls[index].AddFlag("Half Time (50%)", false); + Trolls[index].AddFlag("Rare (10%)", false); +} + +TrollEffectResponse ApplyAffect(int victim, const Troll troll, int activator, trollModifier modifier, int flags) { + bool toActive = IsTrollActiveByRawID(victim, troll.id); + if(StrEqual(troll.name, "Reset User")) { + LogAction(activator, victim, "\"%L\" reset all effects for \"%L\"", activator, victim); + ShowActivityEx(activator, "[FTT] ", "reset effects for %N. ", victim); + // for(int i = 0; i <= MAX_TROLLS; i++) { + // Trolls[i].activeFlagClients[victim] = -1; + // } + // SetEntityGravity(victim, 1.0); + // SetEntPropFloat(victim, Prop_Send, "m_flLaggedMovementValue", 1.0); + ResetClient(victim, true); + return TE_Error; // Not an error, but don't want to show activation + } else if(StrEqual(troll.name, "Slow Speed")) { + if(toActive) { + float movement = 0.0; + if(flags & 1) movement = 0.9; + else if(flags & 2) movement = 0.8; + else if(flags & 4) movement = 0.7; + else if(flags & 8) movement = 0.5; + else if(flags & 16) movement = 0.3; + SetEntPropFloat(victim, Prop_Send, "m_flLaggedMovementValue", movement); + } else + SetEntPropFloat(victim, Prop_Send, "m_flLaggedMovementValue", 1.0); + } else if(StrEqual(troll.name, "Higher Gravity")) + SetEntityGravity(victim, toActive ? 1.3 : 1.0); + else if(StrEqual(troll.name, "UziRules / AwpSmells")) { + DisableTroll(victim, "No Pickup"); + DisableTroll(victim, "Primary Disable"); + } else if(StrEqual(troll.name, "Primary Disable")) { + DisableTroll(victim, "UziRules / AwpSmells"); + DisableTroll(victim, "No Pickup"); + SDKHook(victim, SDKHook_WeaponCanUse, Event_ItemPickup); + } else if(StrEqual(troll.name, "No Pickup")) { + DisableTroll(victim, "UziRules / AwpSmells"); + DisableTroll(victim, "Primary Disable"); + SDKHook(victim, SDKHook_WeaponCanUse, Event_ItemPickup); + } else if(StrEqual(troll.name, "CameTooEarly")) { + ReplyToCommand(activator, "This troll mode is not implemented."); + } else if(StrEqual(troll.name, "KillMeSoftly")) { + static char wpn[32]; + GetClientWeaponName(victim, 4, wpn, sizeof(wpn)); + if(StrEqual(wpn, "weapon_adrenaline") || StrEqual(wpn, "weapon_pain_pills")) { + SetSlot(victim, 5); + pdata[victim].flags |= view_as(Flag_PendingItemGive); + }else{ + ReplyToCommand(activator, "User does not have pills or adrenaline"); + return TE_Error; + } + //TODO: Implement TrollMod_Constant + return TE_Error; + } else if(StrEqual(troll.name, "Throw It All")) { + if(modifier & TrollMod_Instant) { + if(flags & 1) { // Hacky, just throw their kit + ThrowItemToPlayer(victim, activator, 3); + } else ThrowAllItems(victim); + } + } else if(StrEqual(troll.name, "Swarm")) { + if(modifier & TrollMod_Instant) { + L4D2_RunScript("RushVictim(GetPlayerFromUserID(%d), %d)", victim, 15000); + } + } else if(StrEqual(troll.name, "Gun Jam")) { + int wpn = GetClientWeaponEntIndex(victim, 0); + if(wpn > -1) + SDKHook(wpn, SDKHook_Reload, Event_WeaponReload); + else { + ReplyToCommand(activator, "Victim does not have a primary weapon."); + return TE_Error; + } + } else if(StrEqual(troll.name, "Vomit Player")) + L4D_CTerrorPlayer_OnVomitedUpon(victim, victim); + else if(StrEqual(troll.name, "Insta Special")) { + int mode = 0; + if(flags & 2) mode = 1; + ShowInstaSpecialChooser(activator, GetClientUserId(victim), mode); + return TE_Menu; + } else if(StrEqual(troll.name, "Goo")) { + static float pos[3], ang[3]; + GetClientAbsOrigin(victim, pos); + GetClientAbsAngles(victim, ang); + L4D2_SpitterPrj(victim, pos, ang); + } else if(StrEqual(troll.name, "Stagger")) { + L4D_StaggerPlayer(victim, victim, NULL_VECTOR); + } else if(StrEqual(troll.name, "Voice Mute")) { + BaseComm_SetClientMute(victim, toActive); + } else if(StrEqual(troll.name, "Spicy Gas")) { + SDKHook(victim, SDKHook_WeaponCanUse, Event_ItemPickup); + } else if(StrEqual(troll.name, "Car Splat")) { + if(flags & 1) { + if(!SpawnCarOnPlayer(victim)) { + ReplyToCommand(activator, "Could not find a suitable area to spawn a car. Requires vertical space above victim."); + return TE_Error; + } + } else if(flags & 2) { + if(!SpawnCarToPlayer(victim, 450.0)) { + ReplyToCommand(activator, "Could not find a suitable area to spawn a car. Requires space ahead of victim"); + return TE_Error; + } + } else if(flags & 4) { + if(!SpawnCarToPlayer(victim, -450.0)) { + ReplyToCommand(activator, "Could not find a suitable area to spawn a car. Requires space behind victim"); + return TE_Error; + } + } + } else if(StrEqual(troll.name, "Instant Commons")) { + if(modifier & TrollMod_Instant) { + float pos[3]; + GetHorizontalPositionFromClient(victim, flags & 1 ? -40.0 : 40.0, pos); + int victimId = GetClientUserId(victim); + for(int i = 0; i < 30; i++) { + int c = L4D_SpawnCommonInfected(pos); + L4D2_RunScript("CommandABot({cmd=0,bot=EntIndexToHScript(%i),target=GetPlayerFromUserID(%i)})", c, victimId); + } + } + } else if(StrEqual(troll.name, "Randomize Clip Ammo")) { + if(modifier & TrollMod_Instant) { + int primaryWpn = GetPlayerWeaponSlot(victim, 0); + if(primaryWpn > 0) { + int maxCap = GetEntProp(primaryWpn, Prop_Send, "m_iClip1"); + SetEntProp(primaryWpn, Prop_Send, "m_iClip1", GetRandomInt(0, maxCap)); + } + } + } else if(StrEqual(troll.name, "Rock Dropper")) { + float pos[3], dropPos[3]; + GetClientEyePosition(victim, pos); + dropPos = pos; + dropPos[2] += 150.0; + TR_TraceRayFilter(pos, dropPos, MASK_SOLID, RayType_EndPoint, Filter_IgnorePlayer, victim); + if(TR_DidHit()) { + ReplyToCommand(activator, "Could not find a suitable area. Requires vertical space."); + return TE_Error; + } + float ang[3]; + ang[0] = 90.0; + L4D_TankRockPrj(0, dropPos, ang); + } else if(StrEqual(troll.name, "Molotov Bath")) { + int count = 1; + if(flags & 2) count = 8; + float pos[3], dropPos[3]; + GetClientEyePosition(victim, pos); + dropPos = pos; + dropPos[2] += 20.0; + TR_TraceRayFilter(pos, dropPos, MASK_SOLID, RayType_EndPoint, Filter_IgnorePlayer, victim); + if(TR_DidHit()) { + ReplyToCommand(activator, "Could not find a suitable area. Requires vertical space."); + return TE_Error; + } + if(IsAnySurvivorInRange(pos, 55.0, victim)) { + ReplyToCommand(activator, "Victim is too close to other players."); + return TE_Error; + } + float vel[3]; + vel[2] = -90.0; + for(int i = 0; i < count; i++) { + L4D_MolotovPrj(victim, dropPos, vel); + } + } else if(StrEqual(troll.name, "Dep Bots")) { + if(!toActive) { + StopHealingBots(); + return TE_Success; + } else if(healTargetPlayer != 0) { + if(stopHealingTimer != null) { + TriggerTimer(stopHealingTimer); + } + return TE_Success; + } + bool spawnExtra = flags & 2 > 0; + + int numBots = 4; + if(flags & 4) numBots = 1; + else if(flags & 8) numBots = 2; + else if(flags & 16) numBots = 3; + else if(flags & 64) numBots = 5; + + float timeout = 0.0; + if(flags & 255) timeout = 15.0; + else if(flags & 512) timeout = 30.0; + else if(flags & 1024) timeout = 60.0; + else if(flags & 2048) timeout = 300.0; + + // TODO: Extract this !! + healTargetPlayer = GetClientUserId(victim); + + char buffer[32]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2 && IsFakeClient(i)) { + int kit = GetPlayerWeaponSlot(i, 3); + if(kit > 0) { + GetEntityClassname(kit, buffer, sizeof(buffer)); + if(StrEqual(buffer, "weapon_first_aid_kit")) { + PrintToServer("[FTT] Dep Bots: Found bot %N", i); + pdata[i].flags |= view_as(Flag_IsTargettingHealer); + + if(--numBots == 0) { + break; + } + } + } + } + } + CreateTimer(2.0, Timer_UpdateHealTargetPos, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + if(timeout > 0.0) { + DataPack pack; + stopHealingTimer = CreateDataTimer(timeout, Timer_StopHealBots, pack); + pack.WriteCell(GetClientUserId(activator)); + pack.WriteCell(GetClientUserId(victim)) + } + + if(spawnExtra && numBots > 0) { + if(hAbmAutoHard != null) { + wasAbmAutoHard = hAbmAutoHard.IntValue; + hAbmAutoHard.IntValue = 0; + } + CreateTimer(0.2, Timer_SpawnHealBots, numBots, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); + } + + if(hSbFixEnabled != null) { + wasSbFixEnabled = hSbFixEnabled.BoolValue; + hSbFixEnabled.BoolValue = false; + } + } else if(StrEqual(troll.name, "Smart Charge")) { + if(pdata[victim].smartChargeActivator > 0) { + ReplyToCommand(activator, "Target already has smart charge enabled"); + return TE_Error; + } + int timeout = 15; + if(flags & 2) timeout = 30; + else if(flags & 4) timeout = 60; + else if(flags & 8) timeout = 300; + pdata[victim].smartChargeAttempts = 0; + pdata[victim].smartChargeMaxAttempts = timeout; + pdata[victim].smartChargeActivator = GetClientUserId(activator); + CreateTimer(1.0, Timer_CheckForChargerOpportunity, GetClientUserId(victim), TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + } else if(StrEqual(troll.name, "No Rushing Us")) { + SetEntPropFloat(victim, Prop_Send, "m_flLaggedMovementValue", 1.0); + } else if(StrEqual(troll.name, "Hide HUD")) { + if(toActive) + HideHUDRandom(victim); + else + SetEntProp(victim, Prop_Send, "m_iHideHUD", 0); + } else if(StrEqual(troll.name, "Meta: Random")) { + int rndTroll = GetRandomInt(0, MAX_TROLLS); + int rndFlags = 0; + int maxFlags = Trolls[rndTroll].GetFlagCount(); + int numFlags = GetRandomInt(0, maxFlags); + while(numFlags > 0) { + // Apply a random flag + rndFlags |= GetRandomInt(0, maxFlags) + numFlags--; + } + trollModifier rndMod = Trolls[rndTroll].GetDefaultMod(); + if(Trolls[rndTroll].HasMod(TrollMod_Constant) && GetURandomFloat() > 0.5) { + rndMod = TrollMod_Instant; + } else if(Trolls[rndTroll].HasMod(TrollMod_Instant) && GetURandomFloat() > 0.5) { + rndMod = TrollMod_Constant; + } + Trolls[rndTroll].Activate(victim, activator, rndMod, rndFlags); + } else if(~modifier & TrollMod_Constant) { + PrintToServer("[FTT] Warn: Possibly invalid troll, no apply action defined for \"%s\"", troll.name); + #if defined DEBUG + ReplyToCommand(activator, "[FTT/Debug] If nothing occurs, this troll possibly was not implemented correctly. "); + #endif + } + return TE_Success; +} \ No newline at end of file diff --git a/scripting/include/ftt.inc b/scripting/include/ftt.inc new file mode 100644 index 0000000..7242a69 --- /dev/null +++ b/scripting/include/ftt.inc @@ -0,0 +1,120 @@ +enum L4D2Infected +{ + L4D2Infected_None = 0, + L4D2Infected_Smoker = 1, + L4D2Infected_Boomer = 2, + L4D2Infected_Hunter = 3, + L4D2Infected_Spitter = 4, + L4D2Infected_Jockey = 5, + L4D2Infected_Charger = 6, + L4D2Infected_Witch = 7, + L4D2Infected_Tank = 8 +}; + +GlobalForward g_PlayerMarkedForward; +GlobalForward g_TrollAppliedForward; +Handle g_hWitchAttack; +int g_iWitchAttackVictim; + +ConVar hAllowEnemyTeam; +ConVar hAutoPunish; +ConVar hShoveFailChance; +ConVar hAutoPunishExpire; +ConVar hMagnetTargetMode; +ConVar hBadThrowHitSelf; +ConVar hBotReverseFFDefend; +ConVar hSbFriendlyFire; +ConVar hBotDefendChance; +ConVar hAntirushBaseFreq; +ConVar hAntirushIncFreq + +ConVar hSbFixEnabled; +bool wasSbFixEnabled; + +int wasAbmAutoHard; +ConVar hAbmAutoHard; + +enum playerDataFlags { + Flag_PendingItemGive = 1, + Flag_HasSpitTimer = 2, + Flag_IsTargettingHealer = 4 +} + +enum struct PlayerData { + int flags; + + int attackerTargetUid; + int specialAttackFlags; + int pendingTrollBan; // Includes ent index of activator + + float lastInSpitTime; + + int shootAtTarget; + int shootAtLoops; + int shootAtTargetHealth; + + int smartChargeAttempts; + int smartChargeMaxAttempts; + int smartChargeActivator; + + char steamid[32]; + + void Reset() { + this.flags = 0; + this.attackerTargetUid = 0; + this.specialAttackFlags = 0; + this.pendingTrollBan = 0; + this.lastInSpitTime = 0.0; + this.shootAtTarget = 0; + this.shootAtLoops = 0; + this.smartChargeAttempts = 0; + this.steamid[0] = '\0'; + } +} + +PlayerData pdata[MAXPLAYERS+1]; + +int lastButtonUser; +int lastCrescendoUser; + +bool spIsActive; +enum SpecialSpawnFlags { + Special_Anywhere = 0, + Special_OnTarget = 1, + Special_SpawnDirectOnFailure = 2, + Special_KillOnIncap = 4, + Special_AlwaysTarget = 8 +} + +enum SpecialInternalFlags { + SPI_KillOnSpawn = 1, + SPI_AlwaysTarget = 2, + SPI_KillOnTargetIncap = 4 +} + +int healTargetPlayer; +float healTargetPos[3]; +Handle stopHealingTimer; + +float entLastHeight[2048]; + +float fLastAntiRushEvent[MAXPLAYERS+1]; +float fAntiRushFrequencyCounter[MAXPLAYERS+1]; + +float noRushingUsSpeed[MAXPLAYERS+1]; + + + +#define MODEL_CAR "models/props_vehicles/cara_95sedan.mdl" + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + diff --git a/scripting/include/gamemodes/base.inc b/scripting/include/gamemodes/base.inc new file mode 100644 index 0000000..db652f7 --- /dev/null +++ b/scripting/include/gamemodes/base.inc @@ -0,0 +1,291 @@ +#include +char GAMEMODE_NAME[30] = "_UNINITIALIZED_GAMEMODE_"; +char GAMEMODE_PREFIX[32]; + + +// Meta +char gamemode[32]; +bool isEnabled, lateLoaded; + +char g_currentSet[16]; +char g_currentMap[64]; +char nextRoundMap[64]; + +// Legacy: +bool isNavBlockersEnabled = true, isPropsEnabled = true, isPortalsEnabled = true + +static int _debugFlags = BaseDebug_Server; + +enum { + BaseDebug_None, + BaseDebug_Server = 1, + BaseDebug_ConsoleAll = 2, + BaseDebug_ChatAll = 4 +} + +static bool ents_NavBlockers = true; +static bool ents_Props = true; +static bool ents_Portals = true; + +int g_iLaserIndex; + +// Gamemode state +bool isPendingPlay[MAXPLAYERS+1]; +static char buffer[256]; + +methodmap BaseGame { + property int DebugFlags { + public get() { return _debugFlags; } + public set(int flags) { + _debugFlags = flags; + } + } + + public void Init(const char[] name, const char[] prefix = "") { + strcopy(GAMEMODE_NAME, sizeof(GAMEMODE_NAME), name); + if(StrEqual(prefix, "")) + Format(GAMEMODE_PREFIX, sizeof(GAMEMODE_PREFIX), "[%s]", name); + else + Format(GAMEMODE_PREFIX, sizeof(GAMEMODE_PREFIX), "[%s]", prefix); + } + + public void PrintToServer(const char[] format, any ...) { + VFormat(buffer, sizeof(buffer), format, 3); + PrintToServer("[%s] %s", GAMEMODE_NAME, buffer); + } + + public void Warn(const char[] format, any ...) { + VFormat(buffer, sizeof(buffer), format, 3); + PrintToServer("[%s::WARN] %s", GAMEMODE_NAME, buffer); + } + + public void Broadcast(const char[] format, any ...) { + VFormat(buffer, sizeof(buffer), format, 3); + PrintToChatAll("[%s] %s", GAMEMODE_NAME, buffer); + } + + public void Debug(const char[] format, any ...) { + if(_debugFlags == BaseDebug_None) return; + VFormat(buffer, sizeof(buffer), format, 3); + if(_debugFlags & BaseDebug_Server) + PrintToServer("[%s/debug] %s", GAMEMODE_NAME, buffer); + if(_debugFlags & BaseDebug_ChatAll) + PrintToChatAll("[%s/debug] %s", GAMEMODE_NAME, buffer); + if(_debugFlags & BaseDebug_ConsoleAll) + PrintToConsoleAll("[%s/debug] %s", GAMEMODE_NAME, buffer); + } + + public void DebugConsole(const char[] format, any ...) { + if(_debugFlags == BaseDebug_None) return; + VFormat(buffer, sizeof(buffer), format, 3); + PrintToConsoleAll("[%s/debug] %s", GAMEMODE_NAME, buffer); + } + + public void DebugCustom(const char[] format, int flags, any ...) { + if(flags == BaseDebug_None) return; + VFormat(buffer, sizeof(buffer), format, 3); + if(flags & BaseDebug_Server) + PrintToServer("[%s/debug] %s", GAMEMODE_NAME, buffer); + if(flags & BaseDebug_ChatAll) + PrintToChatAll("[%s/debug] %s", GAMEMODE_NAME, buffer); + if(flags & BaseDebug_ConsoleAll) + PrintToConsoleAll("[%s/debug] %s", GAMEMODE_NAME, buffer); + } + + property bool Enabled { + public get() { + return isEnabled + } + public set(bool value) { + isEnabled = value; + } + } + + property bool Blockers { + public get() { + return ents_NavBlockers; + } + public set(bool value) { + ents_NavBlockers = value; + } + } + + property bool Props { + public get() { + return ents_Props; + } + public set(bool value) { + ents_Props = value; + } + } + + property bool Portals { + public get() { + return ents_Portals; + } + public set(bool value) { + ents_Portals = value; + } + } + +} + + +// PeekCam specifics +PeekCamera PeekCam; +static int seekerCam = INVALID_ENT_REFERENCE; +static bool isViewingCam[MAXPLAYERS+1]; +static int seekerTarget; + +enum PeekPerspective { + Cam_Unknown, + Cam_FirstPerson, + Cam_ThirdPerson +} + +methodmap PeekCamera { + property int Target { + public get() { + return GetClientOfUserId(seekerTarget); + } + public set(int client) { + this.Create(); + seekerTarget = GetClientUserId(client); + + AcceptEntityInput(seekerCam, "ClearParent"); + AcceptEntityInput(seekerCam, "Disable"); + } + } + + property PeekPerspective Perspective { + public set(PeekPerspective perspective) { + this.SetPerspective(perspective); + } + } + + public void SetPerspective(PeekPerspective perspective) { + float pos[3], ang[3]; + int client = this.Target; + GetClientEyePosition(this.Target, pos); + GetClientEyeAngles(client, ang); + + if(perspective == Cam_FirstPerson) { + + TeleportEntity(seekerCam, pos, ang, NULL_VECTOR); + SetParent(seekerCam, client); + SetParentAttachment(seekerCam, "primary", false); + } else if(perspective == Cam_ThirdPerson) { + float endPos[3]; + TR_TraceRayFilter(pos, ang, CONTENTS_PLAYERCLIP | MASK_SOLID | MASK_VISIBLE, RayType_Infinite, Filter_IgnoreAll); + if(TR_DidHit()) { + TR_GetEndPosition(endPos); + } + endPos[2] += 50.0; + + ang[0] = 0.0; + float deltaA = endPos[0] - pos[0]; + float deltaB = endPos[1] - pos[1]; + float deltaC = endPos[2] - pos[2]; + ang[0] = RadToDeg(ArcTangent(deltaC / GetVectorDistance(endPos, pos, false) )); + ang[1] = RadToDeg(ArcTangent2(deltaA, deltaB)); + TeleportEntity(seekerCam, endPos, ang, NULL_VECTOR); + } + } + + public void SetViewing(int client, bool active) { + if(seekerCam != INVALID_ENT_REFERENCE) { + AcceptEntityInput(seekerCam, "Enable", client); // Need to always activate before deactivating to fix a semi-common bug + if(!active) { + AcceptEntityInput(seekerCam, "Disable", client); + } + } else { + PrintToServer("WARN: SetPeekCamActive(%d, %b) when seekerCam invalid", client, active); + } + isViewingCam[client] = active; + } + + public void Enable(int client = -1) { + AcceptEntityInput(seekerCam, "Enable", client); + if(client > 0) { + isViewingCam[client] = true; + } + } + public void Disable(int client = -1) { + AcceptEntityInput(seekerCam, "Disable", client); + if(client > 0) { + isViewingCam[client] = false; + } + } + + public bool IsViewing(int client) { + return isViewingCam[client]; + } + + public void Create() { + if(seekerCam == INVALID_ENT_REFERENCE || !IsValidEntity(seekerCam)) { + seekerCam = CreateEntityByName("point_viewcontrol_survivor"); + DispatchKeyValue(seekerCam, "targetname", "hscam"); + DispatchSpawn(seekerCam); + for(int i = 0; i <= MaxClients; i++) { + isViewingCam[i] = false; + } + } + } + + public bool Exists() { + return seekerCam != INVALID_ENT_REFERENCE && IsValidEntity(seekerCam) + } + + public void Destroy() { + if(seekerCam != INVALID_ENT_REFERENCE && IsValidEntity(seekerCam)) { + AcceptEntityInput(seekerCam, "Disable"); + AcceptEntityInput(seekerCam, "Kill"); + seekerCam = INVALID_ENT_REFERENCE + } + seekerTarget = 0; + } +} + +bool Filter_IgnoreAll(int entity, int mask) { + return false; +} + +enum struct EntityConfig { + float origin[3]; + float rotation[3]; + char type[32]; + char model[64]; + float scale[3]; + float offset[3]; +} + +enum struct MapConfig { + ArrayList entities; + ArrayList inputs; + float spawnpoint[3]; + bool hasSpawnpoint; + int mapTime; + bool canClimb; + bool pressButtons; +} + +MapConfig mapConfig; +ArrayList validMaps; +ArrayList validSets; + +stock void SetParent(int child, int parent) { + SetVariantString("!activator"); + AcceptEntityInput(child, "SetParent", parent); +} + +stock void SetParentAttachment(int child, const char[] attachment, bool withOffset = false) { + SetVariantString(attachment); + if(withOffset) + AcceptEntityInput(child, "SetParentAttachmentMaintainOffset"); + else + AcceptEntityInput(child, "SetParentAttachment"); +} + +stock void ClearParent(int child) { + AcceptEntityInput(child, "ClearParent"); +} diff --git a/scripting/include/gamemodes/cvars.inc b/scripting/include/gamemodes/cvars.inc new file mode 100644 index 0000000..d43b0b2 --- /dev/null +++ b/scripting/include/gamemodes/cvars.inc @@ -0,0 +1,67 @@ +static char buffer[128]; + +methodmap GameConVarStorage < StringMap { + public GameConVarStorage() { + return view_as(new StringMap()); + } + + public void Restore() { + StringMapSnapshot snapshot = this.Snapshot(); + char key[32]; + #if defined DEBUG_GAME_CVAR_STORAGE + PrintToServer("GameConVarStorage: Restoring %d saved convars", snapshot.Length); + #endif + for(int i = 0; i < snapshot.Length; i++) { + snapshot.GetKey(i, key, sizeof(key)); + ConVar convar = FindConVar(key); + if(convar != null) { + float value; + if(this.GetValue(key, value)) { + convar.FloatValue = value; + } else if(this.GetString(key, buffer, sizeof(buffer))) { + convar.SetString(buffer); + } else { + LogError("GameConVarStorage: Cannot restore invalid cvar (\"%s\")", key); + } + } + } + this.Clear(); + } + +} + +methodmap GameConVar < ConVar { + public GameConVar(const char[] name) { + return view_as(FindConVar(name)); + } + + public void RecordInt(int value, GameConVarStorage storage) { + if(this == null) return; + if(storage != null) { + this.GetName(buffer, sizeof(buffer)); + storage.SetValue(buffer, float(value)); + } + this.IntValue = value; + } + + public void RecordFloat(float value, GameConVarStorage storage) { + if(this == null) return; + if(storage != null) { + this.GetName(buffer, sizeof(buffer)); + storage.SetValue(buffer, value); + } + this.FloatValue = value; + } + + public void RecordString(const char[] value, GameConVarStorage storage) { + if(this == null) return; + if(storage != null) { + char prevValue[32]; + this.GetName(buffer, sizeof(buffer)); + this.GetString(prevValue, sizeof(prevValue)); + storage.SetString(buffer, prevValue); + } + this.SetString(value); + } + +} \ No newline at end of file diff --git a/scripting/include/gamemodes/ents.inc b/scripting/include/gamemodes/ents.inc new file mode 100644 index 0000000..ea99bc9 --- /dev/null +++ b/scripting/include/gamemodes/ents.inc @@ -0,0 +1,307 @@ +#if !defined ENT_PROP_NAME + #define ENT_PROP_NAME "cprop" +#endif +#if !defined ENT_BLOCKER_NAME + #define ENT_BLOCKER_NAME "cblocker" +#endif +#if !defined ENT_PORTAL_NAME + #define ENT_PORTAL_NAME "cportal" +#endif +#if !defined ENT_ENV_NAME + #define ENT_ENV_NAME "cenv" +#endif + +stock void DeleteCustomEnts() { + EntFireTarget(ENT_PROP_NAME, "Kill"); + EntFireTarget(ENT_BLOCKER_NAME, "Kill"); + EntFireTarget(ENT_PORTAL_NAME, "Kill"); + EntFireTarget(ENT_ENV_NAME, "Kill"); +} + +stock void EntFireTarget(const char[] name, const char[] input) { + static char targetname[64]; + static char cmd[32]; + #if defined DEBUG_LOG_MAPSTART + PrintToServer("EntFireTarget: %s \"%s\"", name, input); + #endif + int len = SplitString(input, " ", cmd, sizeof(cmd)); + if(len > -1) SetVariantString(input[len]); + + for(int i = MaxClients + 1; i <= 4096; i++) { + if(IsValidEntity(i) && (IsValidEdict(i) || EntIndexToEntRef(i) != -1)) { + GetEntPropString(i, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } + } +} + +stock int CreateEnvBlockerScaled(const char[] entClass, const float pos[3], const float scale[3] = { 5.0, 5.0, 5.0 }, bool enabled = true) { + int entity = CreateEntityByName(entClass); + DispatchKeyValue(entity, "targetname", ENT_BLOCKER_NAME); + DispatchKeyValue(entity, "initialstate", "1"); + DispatchKeyValue(entity, "BlockType", "0"); + static float mins[3]; + mins = scale; + NegateVector(mins); + DispatchKeyValueVector(entity, "boxmins", mins); + DispatchKeyValueVector(entity, "boxmaxs", scale); + DispatchKeyValueVector(entity, "mins", mins); + DispatchKeyValueVector(entity, "maxs", scale); + + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + if(DispatchSpawn(entity)) { + #if defined DEBUG_LOG_MAPSTART + PrintToServer("spawn blocker scaled %.1f %.1f %.1f scale [%.0f %.0f %.0f]", pos[0], pos[1], pos[2], scale[0], scale[1], scale[2]); + #endif + SetEntPropVector(entity, Prop_Send, "m_vecMaxs", scale); + SetEntPropVector(entity, Prop_Send, "m_vecMins", mins); + if(enabled) + AcceptEntityInput(entity, "Enable"); + #if defined DEBUG_BLOCKERS + Effect_DrawBeamBoxRotatableToAll(pos, mins, scale, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 0, 255}, 0); + #endif + return entity; + } else { + #if defined DEBUG_LOG_MAPSTART + PrintToServer("FAILED: spawn blocker scaled %.1f %.1f %.1f scale [%.0f %.0f %.0f]", pos[0], pos[1], pos[2], scale[0], scale[1], scale[2]); + #endif + } + return -1; +} + +enum PortalType { + Portal_Relative, + Portal_Teleport +} +enum struct EntData { + PortalType portalType; + float portalOffsets[3]; +} +EntData entData[2048]; + +stock int CreatePortal(PortalType type, const char model[64], const float pos[3], const float offset[3] = { 40.0, 40.0, 0.0 }, const float scale[3] = { 5.0, 5.0, 5.0 }) { + int entity = CreateEntityByName("trigger_multiple"); + if(entity == -1) return -1; + DispatchKeyValue(entity, "spawnflags", "513"); + DispatchKeyValue(entity, "solid", "6"); + DispatchKeyValue(entity, "targetname", ENT_PORTAL_NAME); + DispatchKeyValue(entity, "wait", "0"); + if(DispatchSpawn(entity)) { + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + static float mins[3]; + mins = scale; + NegateVector(mins); + SetEntPropVector(entity, Prop_Send, "m_vecMaxs", scale); + SetEntPropVector(entity, Prop_Send, "m_vecMins", mins); + SetEntProp(entity, Prop_Send, "m_nSolidType", 2); + + HookSingleEntityOutput(entity, "OnStartTouch", OnPortalTouch, false); + #if defined DEBUG_BLOCKERS + Effect_DrawBeamBoxRotatableToAll(pos, mins, scale, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 255, 255}, 0); + #endif + #if defined DEBUG_LOG_MAPSTART + PrintToServer("spawn portal %d - pos %.1f %.1f %.1f - scale %.1f %.1f %.1f", entity, pos[0], pos[1], pos[2], scale[0], scale[1], scale[2]); + #endif + AcceptEntityInput(entity, "Enable"); + + entData[entity].portalOffsets = NULL_VECTOR; + + // Convert relative offset to one based off full scale: + entData[entity].portalType = type; + if(type == Portal_Relative) { + if(offset[0] != 0.0) entData[entity].portalOffsets[0] = (scale[0] * 2) + offset[0]; + if(offset[1] != 0.0) entData[entity].portalOffsets[1] = (scale[1] * 2) + offset[1]; + if(offset[2] != 0.0) entData[entity].portalOffsets[2] = (scale[2] * 2) + offset[2]; + } else { + entData[entity].portalOffsets = offset; + } + + return entity; + } + return -1; +} + +void OnPortalTouch(const char[] output, int caller, int activator, float delay) { + if(entData[caller].portalType == Portal_Relative) { + float pos[3]; + GetClientAbsOrigin(activator, pos); + float ang[3]; + GetClientAbsAngles(activator, ang); + if(ang[0] < 0) pos[0] -= entData[caller].portalOffsets[0]; + else pos[0] += entData[caller].portalOffsets[0]; + if(ang[1] < 0) pos[1] -= entData[caller].portalOffsets[1]; + else pos[1] += entData[caller].portalOffsets[1]; + if(ang[2] < 0) pos[2] -= entData[caller].portalOffsets[2]; + else pos[2] += entData[caller].portalOffsets[2]; + TeleportEntity(activator, pos, NULL_VECTOR, NULL_VECTOR); + } else { + TeleportEntity(activator, entData[caller].portalOffsets, NULL_VECTOR, NULL_VECTOR); + } + #if defined PORTAL_ENTER_SOUND + EmitSoundToClient(activator, PORTAL_ENTER_SOUND, activator); + #endif +} + +stock int StartPropCreate(const char[] entClass, const char[] model, const float pos[3], const float ang[3] = NULL_VECTOR, const float vel[3] = NULL_VECTOR) { + int entity = CreateEntityByName(entClass); + if(entity == -1) return -1; + DispatchKeyValue(entity, "model", model); + DispatchKeyValue(entity, "solid", "6"); + DispatchKeyValue(entity, "targetname", ENT_PROP_NAME); + DispatchKeyValue(entity, "disableshadows", "1"); + TeleportEntity(entity, pos, ang, vel); + return entity; +} + +stock int CreateProp(const char[] entClass, const char[] model, const float pos[3], const float ang[3] = NULL_VECTOR, const float vel[3] = NULL_VECTOR) { + int entity = StartPropCreate(entClass, model, pos, ang, vel); + if(DispatchSpawn(entity)) { + #if defined DEBUG_LOG_MAPSTART + PrintToServer("spawn prop %.1f %.1f %.1f model %s", pos[0], pos[1], pos[2], model[7]); + #endif + return entity; + } + return -1; +} + +stock int CreateDummy(const char[] model, const char[] anim, const float pos[3], const float ang[3] = NULL_VECTOR) { + int entity = StartPropCreate("commentary_dummy", model, pos, ang); + if(entity == -1) return -1; + DispatchKeyValue(entity, "targetname", ENT_PROP_NAME); + DispatchKeyValue(entity, "LookAtPlayers", "Yes"); + DispatchKeyValue(entity, "StartingWeapons", "weapon_rifle_ak47"); + DispatchKeyValue(entity, "StartingAnim", anim); //idle_calm_rifle + DispatchKeyValueFloat(entity, "LookAtPlayers", 40.0); + DispatchSpawn(entity); + return entity; +} + +stock int CreateFire(const float pos[3], float damage = 10.0, float size = 256.0, float attack = 4.0) { + int entity = CreateEntityByName("env_fire"); + if(entity == -1) return -1; + DispatchKeyValue(entity, "spawnflags", "13"); + DispatchKeyValue(entity, "targetname", ENT_ENV_NAME); + DispatchKeyValueFloat(entity, "firesize", size); + DispatchKeyValueFloat(entity, "fireattack", attack); + DispatchKeyValueFloat(entity, "damagescale", damage); + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(entity); + AcceptEntityInput(entity, "Enable"); + AcceptEntityInput(entity, "StartFire"); + #if defined DEBUG_LOG_MAPSTART + + PrintToServer("spawn env_fire at %.1f %.1f %.1f", pos[0], pos[1], pos[2]); + #endif + return entity; +} + +// Taken from silver's https://forums.alliedmods.net/showthread.php?p=1658873 +stock int CreateDynamicLight(float vOrigin[3], float vAngles[3], int color, float brightness, int style = 0) { + int entity = CreateEntityByName("light_dynamic"); + if( entity == -1) + return -1; + + DispatchKeyValue(entity, "_light", "0 0 0 255"); + DispatchKeyValue(entity, "brightness", "1"); + DispatchKeyValueFloat(entity, "spotlight_radius", 32.0); + DispatchKeyValueFloat(entity, "distance", brightness); + DispatchKeyValue(entity, "targetname", ENT_ENV_NAME); + DispatchKeyValueFloat(entity, "style", float(style)); + SetEntProp(entity, Prop_Send, "m_clrRender", color); + if(DispatchSpawn(entity)) { + TeleportEntity(entity, vOrigin, vAngles, NULL_VECTOR); + AcceptEntityInput(entity, "TurnOn"); + #if defined DEBUG_LOG_MAPSTART + PrintToServer("spawn dynamic light %.1f %.1f %.1f", vOrigin[0], vOrigin[1], vOrigin[2]); + #endif + return entity; + } + return -1; +} + +// From l4d_anomaly +stock int CreateParticle(const char[] sParticle, const float vPos[3], const float vAng[3], int client = 0) +{ + int entity = CreateEntityByName("info_particle_system"); + + if( entity != -1 ) + { + DispatchKeyValue(entity, "effect_name", sParticle); + DispatchKeyValue(entity, "targetname", ENT_PORTAL_NAME) + DispatchSpawn(entity); + ActivateEntity(entity); + AcceptEntityInput(entity, "start"); + + if( client ) + { + // Attach to survivor + SetVariantString("!activator"); + AcceptEntityInput(entity, "SetParent", client); + } + + TeleportEntity(entity, vPos, vAng, NULL_VECTOR); + + // Refire + float refire = 0.2; + static char sTemp[64]; + Format(sTemp, sizeof(sTemp), "OnUser1 !self:Stop::%f:-1", refire - 0.05); + SetVariantString(sTemp); + AcceptEntityInput(entity, "AddOutput"); + Format(sTemp, sizeof(sTemp), "OnUser1 !self:FireUser2::%f:-1", refire); + SetVariantString(sTemp); + AcceptEntityInput(entity, "AddOutput"); + AcceptEntityInput(entity, "FireUser1"); + + SetVariantString("OnUser2 !self:Start::0:-1"); + AcceptEntityInput(entity, "AddOutput"); + SetVariantString("OnUser2 !self:FireUser1::0:-1"); + AcceptEntityInput(entity, "AddOutput"); + + return entity; + } + + return 0; +} + +stock void CreateDecal(const char[] texture, const float vPos[3]) { + int index = PrecacheDecal("decals/checkpointarrow01_black.vmt"); + TE_Start("World Decal"); + TE_WriteVector("m_vecOrigin", vPos); + TE_WriteNum("m_nIndex", index); + TE_SendToAll(); + + TE_Start("BSP Decal"); + TE_WriteVector("m_vecOrigin", vPos); + TE_WriteNum("m_nIndex", index); + TE_SendToAll(); + // int entity = CreateEntityByName("infodecal"); + // if( entity != -1 ) { + // DispatchKeyValue(entity, "texture", "decals/checkpointarrow01_black.vmt"); + // DispatchKeyValue(entity, "targetname", ENT_ENV_NAME); + // TeleportEntity(entity, vPos, NULL_VECTOR, NULL_VECTOR); + // DispatchSpawn(entity); + // ActivateEntity(entity); + // } +} + +// From l4d_anomaly +stock void PrecacheParticle(const char[] sEffectName) +{ + static int table = INVALID_STRING_TABLE; + if( table == INVALID_STRING_TABLE ) + { + table = FindStringTable("ParticleEffectNames"); + } + + if( FindStringIndex(table, sEffectName) == INVALID_STRING_INDEX ) + { + bool save = LockStringTables(false); + AddToStringTable(table, sEffectName); + LockStringTables(save); + } +} + + diff --git a/scripting/include/guesswho/gwcmds.inc b/scripting/include/guesswho/gwcmds.inc new file mode 100644 index 0000000..7fd0c47 --- /dev/null +++ b/scripting/include/guesswho/gwcmds.inc @@ -0,0 +1,393 @@ +#define GAMEMODE_PROP_NAME "gwprop" +#define GAMEMODE_BLOCKER_NAME "gwblocker" + + + +public Action Command_GuessWho(int client, int args) { + if(!isEnabled) ReplyToCommand(client, "Warn: %s is not active", GAMEMODE_NAME); + if(args > 0) { + char subcmd[32]; + GetCmdArg(1, subcmd, sizeof(subcmd)); + if(StrEqual(subcmd, "points")) { + GetCmdArg(2, subcmd, sizeof(subcmd)); + if(StrEqual(subcmd, "clear")) { + movePoints.Clear(); + ReplyToCommand(client, "Movement locations have been cleared"); + } else if(StrEqual(subcmd, "save")) { + if(args == 3) { + GetCmdArg(2, subcmd, sizeof(subcmd)); + } else { + subcmd = g_currentSet; + } + if(movePoints.SaveMap(g_currentMap, subcmd)) { + ReplyToCommand(client, "Saved movement data for %s/%s", g_currentMap, subcmd); + } else { + ReplyToCommand(client, "Failed to save map data"); + } + } else if(StrEqual(subcmd, "load")) { + MovePoints points = MovePoints.LoadMap(g_currentMap, g_currentSet); + if(points != null) { + Game.SetPoints(points); + ReplyToCommand(client, "Loaded movement data for %s/%s", g_currentMap, g_currentSet); + } else { + ReplyToCommand(client, "Failed to load map data"); + } + } else if(StrEqual(subcmd, "record")) { + float recordInterval = 0.5; + if(args == 3) { + GetCmdArg(3, subcmd, sizeof(subcmd)); + recordInterval = StringToFloat(subcmd); + if(recordInterval <= 0.0) { + ReplyToCommand(client, "Invalid record interval (%f)", recordInterval); + return Plugin_Handled; + } + } + + if(recordTimer != null) { + ReplyToCommand(client, "Stopped recording. %d ready to save. \"/guesswho points save\" to save", movePoints.Length); + delete recordTimer; + } else { + // Assume recorder doesn't leav + recordTimer = CreateTimer(recordInterval, Timer_RecordPoints, client, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); + ReplyToCommand(client, "Recording movement points every %.2f seconds. Type command again to stop", recordInterval); + } + } else { + ReplyToCommand(client, "Unknown option. Valid options: 'clear', 'save', 'load'"); + } + } else if(StrEqual(subcmd, "r") || StrEqual(subcmd, "reload", false)) { + GetCurrentMap(g_currentMap, sizeof(g_currentMap)); + char arg[4]; + GetCmdArg(2, arg, sizeof(arg)); + if(ReloadMapDB()) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: Map has no config file"); + } + Game.Cleanup(true); + if(arg[0] == 'f') { + InitGamemode(); + } + SetupEntities(Game.Blockers, Game.Props, Game.Portals); + ReplyToCommand(client, "Reloaded map from config"); + } else { + ReplyToCommand(client, "Error occurred while reloading map file"); + } + } else if(StrEqual(subcmd, "set", false)) { + char set[16]; + if(args == 1) { + ReplyToCommand(client, "Current Map Set: \"%s\" (Specify with /gw set )", g_currentSet); + if(validSets.Length == 0) ReplyToCommand(client, "Available Sets: (no map config found)"); + else { + ReplyToCommand(client, "Available Sets: "); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + ReplyToCommand(client, "%d. %s", i + 1, set); + } + } + } else { + GetCmdArg(2, g_currentSet, sizeof(g_currentSet)); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + if(StrEqual(set, g_currentSet)) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: No config entry for %s", g_currentMap); + } + MovePoints points = MovePoints.LoadMap(g_currentMap, g_currentSet); + if(points != null) { + if(movePoints.Length == 0) { + ReplyToCommand(client, "Warn: No map data found for %s/%s", g_currentMap, g_currentSet); + } + Game.SetPoints(points); + } else { + ReplyToCommand(client, "Warn: %s/%s has 0 saved movement locations", g_currentMap, g_currentSet); + } + Game.Cleanup(); + SetupEntities(Game.Blockers, Game.Props, Game.Portals); + PrintToChatAll("[GuessWho] Map set has been changed to \"%s\"", g_currentSet); + return Plugin_Handled; + } + } + ReplyToCommand(client, "Warning: Set was not found, use /gw r to force load."); + } + } else if(StrEqual(subcmd, "toggle")) { + char type[32]; + GetCmdArg(2, type, sizeof(type)); + bool doAll = StrEqual(type, "all"); + bool isUnknown = true; + + if(doAll || StrEqual(type, "blockers", false)) { + if(Game.Blockers) { + EntFire(GAMEMODE_BLOCKER_NAME, "Disable"); + ReplyToCommand(client, "Disabled all custom gamemode blockers"); + } else { + EntFire(GAMEMODE_BLOCKER_NAME, "Enable"); + ReplyToCommand(client, "Enabled all custom gamemode blockers"); + } + Game.Blockers = !Game.Blockers; + isUnknown = false; + } + if(doAll || StrEqual(type, "props", false)) { + if(Game.Props) { + EntFire(GAMEMODE_PROP_NAME, "Disable"); + EntFire(GAMEMODE_PROP_NAME, "DisableCollision"); + ReplyToCommand(client, "Disabled all custom gamemode props"); + } else { + EntFire(GAMEMODE_PROP_NAME, "Enable"); + EntFire(GAMEMODE_PROP_NAME, "EnableCollision"); + ReplyToCommand(client, "Enabled all custom gamemode props"); + } + Game.Props = !Game.Props; + isUnknown = false; + } + if(isUnknown) ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', or 'all'"); + } else if(StrEqual(subcmd, "clear", false)) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "all")) { + Game.Cleanup(); + ReplyToCommand(client, "Cleaned up everything."); + } else if(StrEqual(arg, "props")) { + EntFire(GAMEMODE_PROP_NAME, "kill"); + ReplyToCommand(client, "Removed all custom gamemode props"); + } else if(StrEqual(arg, "blockers")) { + EntFire(GAMEMODE_BLOCKER_NAME, "kill"); + ReplyToCommand(client, "Removed all custom gamemode blockers"); + } else ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', or 'all'"); + } else if(StrEqual(subcmd, "settime")) { + int prev = Game.MapTime; + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int time = StringToInt(arg); + mapConfig.mapTime = time; + Game.MapTime = time; + ReplyToCommand(client, "Map's time is temporarily set to %d seconds (was %d)", time, prev); + } else if(StrEqual(subcmd, "settick")) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int tick = -StringToInt(arg); + Game.Tick = tick; + ReplyToCommand(client, "Set tick time to %d", tick); + } else if(StrContains(subcmd, "map") >= 0) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "list")) { + ReplyToCommand(client, "See the console for available maps"); + char map[64]; + for(int i = 0; i < validMaps.Length; i++) { + validMaps.GetString(i, map, sizeof(map)); + PrintToConsole(client, "%d. %s", i + 1, map); + } + } else if(StrEqual(arg, "random")) { + bool foundMap; + char map[64]; + do { + int mapIndex = GetURandomInt() % validMaps.Length; + validMaps.GetString(mapIndex, map, sizeof(map)); + if(!StrEqual(g_currentMap, map, false)) { + foundMap = true; + } + } while(!foundMap); + PrintToChatAll("%s Switching map to %s", GAMEMODE_PREFIX, map); + ChangeMap(map); + } else if(StrEqual(arg, "next", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change on the next round: 'next '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + strcopy(nextRoundMap, sizeof(nextRoundMap), arg2); + PrintToChatAll("%s Switching map next round to %s", GAMEMODE_PREFIX, arg2); + ForceChangeLevel(arg, "SetMapSelect"); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else if(StrEqual(arg, "force", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change to: 'force '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + PrintToChatAll("[H&S] Switching map to %s", arg2); + ChangeMap(arg2); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else { + ReplyToCommand(client, "Syntax: 'map /next >"); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "pos", false)) { + float pos[3]; + GetAbsOrigin(client, pos); + ReplyToCommand(client, "\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientEyeAngles(client, pos); + ReplyToCommand(client, "\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + } else if(StrEqual(subcmd, "prop", false)) { + float pos[3]; + GetAbsOrigin(client, pos); + ReplyToCommand(client, "\"MYPROP\""); + ReplyToCommand(client, "{"); + ReplyToCommand(client, "\t\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientAbsAngles(client, pos); + ReplyToCommand(client, "\t\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + ReplyToCommand(client, "\t\"type\" \"prop_dynamic\""); + ReplyToCommand(client, "\t\"model\" \"props_junk/dumpster_2.mdl\""); + ReplyToCommand(client, "}"); + } else if(StrEqual(subcmd, "setspawn", false)) { + GetClientAbsOrigin(client, mapConfig.spawnpoint); + ReplyToCommand(client, "Set map's temporarily spawnpoint to your location."); + } else if(StrEqual(subcmd, "stuck")) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + } else if(StrEqual(subcmd, "peekfix")) { + if(!PeekCam.Exists()) { + PeekCam.Target = client; + } + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + PeekCam.SetViewing(client, true); + PeekCam.SetViewing(client, false); + } + } + PeekCam.Destroy(); + ReplyToCommand(client, "Killing active camera"); + } else if(StrEqual(subcmd, "seeker")) { + if(args == 2) { + char arg1[32]; + GetCmdArg(2, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_list[0] <= 0){ + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + Game.ForceSetSeeker(target_list[0]); + ReplyToCommand(client, "Set the current seeker to %N", target_list[0]); + } else { + ReplyToCommand(client, "The current seeker is: %N", Game.Seeker); + } + } else if(StrEqual(subcmd, "debug")) { + ReplyToCommand(client, "- Game Info -"); + ReplyToCommand(client, "Current seeker: %N(%d)", Game.Seeker, Game.Seeker); + ReplyToCommand(client, "State: %d | Tick: %d", view_as(Game.State), Game.Tick); + + ReplyToCommand(client, "- Map Info -"); + ReplyToCommand(client, "Map: %s (set %s)", g_currentMap, g_currentSet); + if(mapConfig.hasSpawnpoint) + ReplyToCommand(client, "Has Spawnpoint: yes (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + else + ReplyToCommand(client, "Has Spawnpoint: no (possibly map spawn %f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + ReplyToCommand(client, "Map Time: %d", mapConfig.mapTime); + ReplyToCommand(client, "Flow Bounds: (%f, %f)", movePoints.MinFlow, movePoints.MaxFlow); + } else if(StrEqual(subcmd, "test")) { + + } else { + ReplyToCommand(client, "Unknown option. Leave blank for help"); + } + return Plugin_Handled; + } + ReplyToCommand(client, " === [ %s Commands ] ===", GAMEMODE_NAME); + if(GetUserAdmin(client) != INVALID_ADMIN_ID) { + ReplyToCommand(client, "- Dev Commands -"); + ReplyToCommand(client, "points:"); + ReplyToCommand(client, "\tsave [set]: Save all movement data for map, and a optional set (defaults to current set)"); + ReplyToCommand(client, "\tload: Loads movement data for current map & set"); + ReplyToCommand(client, "\tclear: Removes all active movement data"); + ReplyToCommand(client, "r/reload [force]: Reloads map config from file"); + ReplyToCommand(client, "toggle : Toggles all specified entities"); + ReplyToCommand(client, "clear : Clear all specified"); + ReplyToCommand(client, "settime [seconds]: Sets the time override for the map"); + ReplyToCommand(client, "settick [tick]: Sets the current tick timer value"); + ReplyToCommand(client, "- Admin Commands -"); + ReplyToCommand(client, "set [new set]: Change the prop set or view current"); + ReplyToCommand(client, "setspawn: Sets the temporary spawnpoint for the map"); + ReplyToCommand(client, "peekfix - Clear peek camera from all players"); + ReplyToCommand(client, "seeker [new seeker]: Get the active seeker, or set a new one."); + ReplyToCommand(client, "- User Commands -"); + } + ReplyToCommand(client, "stuck: Teleports you to spawn to unstuck yourself"); + return Plugin_Handled; +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) { + if(isEnabled) { + if(!StrEqual(command, "say")) { //Is team message + if(currentSeeker <= 0 || currentSeeker == client) { + return Plugin_Continue; + } + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && i != currentSeeker) + PrintToChat(i, "[Hiders] %N: %s", client, sArgs); + } + return Plugin_Handled; + } + } + return Plugin_Continue; +} + + +public Action Command_Join(int client, int args) { + if(!isEnabled) return Plugin_Continue; + static float tpLoc[3]; + FindSpawnPosition(tpLoc); + if(args == 1) { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(GetClientTeam(target) != 2) { + ChangeClientTeam(target, 2); + L4D_RespawnPlayer(target); + TeleportEntity(target, tpLoc, NULL_VECTOR, NULL_VECTOR); + isPendingPlay[client] = false; + CheatCommand(target, "give", "knife"); + } + } + ReplyToCommand(client, "Joined %s", target_name); + } else { + if(currentSeeker == client) { + ReplyToCommand(client, "You are already in-game as a seeker."); + return Plugin_Handled; + } + isPendingPlay[client] = false; + ChangeClientTeam(client, 2); + L4D_RespawnPlayer(client); + TeleportEntity(client, tpLoc, NULL_VECTOR, NULL_VECTOR); + Game.SetupPlayer(client); + if(!ArePlayersJoining()) { + InitGamemode(); + } + } + return Plugin_Handled; +} diff --git a/scripting/include/guesswho/gwcore.inc b/scripting/include/guesswho/gwcore.inc new file mode 100644 index 0000000..2b68953 --- /dev/null +++ b/scripting/include/guesswho/gwcore.inc @@ -0,0 +1,172 @@ +#define FOLDER_PERMS ( FPERM_U_READ | FPERM_U_WRITE | FPERM_U_EXEC | FPERM_G_EXEC | FPERM_G_WRITE | FPERM_G_READ | FPERM_O_EXEC ) + +#include +#include +#include +#include +#include + + +static KeyValues kv; +StringMap mapConfigs; + +bool ReloadMapDB() { + if(kv != null) { + delete kv; + } + kv = new KeyValues("guesswho"); + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/guesswho"); + CreateDirectory(sPath, FOLDER_PERMS); + Format(sPath, sizeof(sPath), "%s/config.cfg", sPath); + + if(!FileExists(sPath) || !kv.ImportFromFile(sPath)) { + delete kv; + return false; + } + + validMaps.Clear(); + + char map[64]; + kv.GotoFirstSubKey(true); + do { + kv.GetSectionName(map, sizeof(map)); + validMaps.PushString(map); + } while(kv.GotoNextKey(true)); + kv.GoBack(); + return true; +} + +static float DEFAULT_SCALE[3] = { 5.0, 5.0, 5.0 }; + +bool LoadConfigForMap(const char[] map) { + kv.Rewind(); + if (kv.JumpToKey(map)) { + MapConfig config; + config.entities = new ArrayList(sizeof(EntityConfig)); + config.inputs = new ArrayList(ByteCountToCells(64)); + validSets.Clear(); + + static char buffer[64]; + buffer[0] = '\0'; + if(StrEqual(g_currentSet, "default") && kv.GetString("defaultset", buffer, sizeof(buffer)) && buffer[0] != '\0') { + strcopy(g_currentSet, sizeof(g_currentSet), buffer); + } + PrintToServer("[GuessWho] Loading config data for set %s on %s", g_currentSet, map); + + if(kv.JumpToKey("ents")) { + kv.GotoFirstSubKey(); + do { + EntityConfig entCfg; + kv.GetVector("origin", entCfg.origin, NULL_VECTOR); + kv.GetVector("rotation", entCfg.rotation, NULL_VECTOR); + kv.GetString("type", entCfg.type, sizeof(entCfg.type), "env_physics_blocker"); + kv.GetString("model", entCfg.model, sizeof(entCfg.model), ""); + if(entCfg.model[0] != '\0') + Format(entCfg.model, sizeof(entCfg.model), "models/%s", entCfg.model); + kv.GetVector("scale", entCfg.scale, DEFAULT_SCALE); + kv.GetVector("offset", entCfg.offset, NULL_VECTOR); + kv.GetString("set", buffer, sizeof(buffer), "default"); + if(validSets.FindString(buffer) == -1) { + validSets.PushString(buffer); + } + if(StrEqual(buffer, "default") || StrEqual(g_currentSet, buffer, false)) { + + config.entities.PushArray(entCfg); + } else { + kv.GetSectionName(buffer, sizeof(buffer)); + PrintToServer("Skipping %s", buffer); + } + } while (kv.GotoNextKey()); + // JumpToKey and GotoFirstSubKey both traverse, i guess, go back + kv.GoBack(); + kv.GoBack(); + } + if(kv.JumpToKey("inputs")) { + kv.GotoFirstSubKey(false); + do { + kv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + kv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (kv.GotoNextKey(false)); + kv.GoBack(); + kv.GoBack(); + } + int mapTime; + + config.hasSpawnpoint = false; + config.canClimb = true; + config.pressButtons = true; + if(!StrEqual(g_currentSet, "default") && kv.JumpToKey("sets")) { + char set[16]; + kv.GotoFirstSubKey(true); + do { + kv.GetSectionName(set, sizeof(set)); + if(validSets.FindString(set) == -1) { + validSets.PushString(set); + } + if(StrEqual(g_currentSet, set, false)) { + kv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[GuessWho] Using provided custom spawnpoint for set %s at %0.1f, %0.1f, %0.1f", g_currentSet, config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } + mapTime = kv.GetNum("maptime", 0); + if(kv.JumpToKey("inputs")) { + kv.GotoFirstSubKey(false); + do { + kv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + kv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (kv.GotoNextKey(false)); + kv.GoBack(); + kv.GoBack(); + } + break; + } + + } while(kv.GotoNextKey(true)); + kv.GoBack(); + kv.GoBack(); + } + + if(!config.hasSpawnpoint) { + kv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[GuessWho] Using provided custom spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else if (FindSpawnPosition(config.spawnpoint, false)) { + PrintToServer("[GuessWho] Using map spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else { + PrintToServer("[GuessWho] Could not find any spawnpoints, using default spawn"); + config.hasSpawnpoint = false; + } + } + + // Use default maptime if exists + if(mapTime == 0) + mapTime = kv.GetNum("maptime", 0); + if(mapTime > 0) { + config.mapTime = mapTime; + PrintToServer("[GuessWho] Map time overwritten to %d seconds", mapTime); + } + + mapConfigs.SetArray(map, config, sizeof(MapConfig)); + // Discard entInputs if unused + if(config.inputs.Length == 0) { + delete config.inputs; + } + mapConfig = config; + return true; + } else { + mapConfig.hasSpawnpoint = false; + PrintToServer("[GuessWho] %s has no config entry", map); + return false; + } +} \ No newline at end of file diff --git a/scripting/include/guesswho/gwents.inc b/scripting/include/guesswho/gwents.inc new file mode 100644 index 0000000..670c13e --- /dev/null +++ b/scripting/include/guesswho/gwents.inc @@ -0,0 +1,128 @@ +#define ENT_PROP_NAME "gwprop" +#define ENT_BLOCKER_NAME "gwblocker" +#define ENT_PORTAL_NAME "gwportal" +#define ENT_ENV_NAME "gwenv" +#include + +stock void CheatCommand(int client, const char[] command, const char[] argument1) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", command, argument1); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} + + +stock void EntFire(const char[] name, const char[] input) { + static char targetname[64]; + static char cmd[32]; + #if defined DEBUG_LOG_MAPSTART + PrintToServer("EntFire: %s \"%s\"", name, input); + #endif + int len = SplitString(input, " ", cmd, sizeof(cmd)); + if(len > -1) SetVariantString(input[len]); + + int hammerId = name[0] == '!' ? StringToInt(name[1]) : 0; + for(int i = MaxClients + 1; i <= 4096; i++) { + if(IsValidEntity(i) && (IsValidEdict(i) || EntIndexToEntRef(i) != -1)) { + if(hammerId > 0) { + if(hammerId == Entity_GetHammerId(i)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } else { + GetEntPropString(i, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + + } else { + GetEntityClassname(i, targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } + } + } + } +} + + + +void SetupEntities(bool blockers = true, bool props = true, bool portals = true) { + #if defined DEBUG_BLOCKERS + if(mapConfig.hasSpawnpoint) { + PrecacheModel("survivors/survivor_teenangst.mdl", true); + int dummy = CreateDummy("models/survivors/survivor_teenangst.mdl", "idle", mapConfig.spawnpoint, NULL_VECTOR); + SetEntProp(dummy, Prop_Data, "m_nSolidType", 0); + SetEntProp(dummy, Prop_Send, "m_CollisionGroup", 0); + SetEntProp(dummy, Prop_Send, "movetype", MOVETYPE_NONE); + } + EntFire("info_changelevel", "Kill"); + #endif + if(mapConfig.entities != null) { + PrintToServer("[GuessWho] Deploying %d custom entities (Set: %s) (blockers:%b props:%b portals:%b)", mapConfig.entities.Length, g_currentSet, blockers, props, portals); + for(int i = 0; i < mapConfig.entities.Length; i++) { + EntityConfig config; + mapConfig.entities.GetArray(i, config); + + if(config.model[0] != '\0') PrecacheModel(config.model); + + if(StrEqual(config.type, "env_physics_blocker")) { + if(blockers && CreateEnvBlockerScaled(config.type, config.origin, config.scale, isNavBlockersEnabled) == -1) { + Game.Warn("Failed to spawn blocker [type=%s] at (%.1f,%.1f, %.1f)", config.type, config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_relportal")) { + if(portals && CreatePortal(Portal_Relative, config.model, config.origin, config.offset, config.scale) == -1) { + Game.Warn("Failed to spawn rel portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_portal")) { + if(portals && CreatePortal(Portal_Teleport, config.model, config.origin, config.offset, config.scale) == -1) { + Game.Warn("Failed to spawn portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_lantern")) { + int parent = CreateProp("prop_dynamic", config.model, config.origin, config.rotation); + if(parent == -1) { + Game.Warn("Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]); + } else { + float pos[3]; + pos = config.origin; + pos[2] += 15.0; + int child = CreateDynamicLight(pos, config.rotation, GetColorInt(255, 255, 242), 80.0, 11); + if(child == -1) { + Game.Warn("Failed to spawn light source for _lantern"); + } else { + SetParent(child, parent); + TeleportEntity(parent, config.origin, NULL_VECTOR, NULL_VECTOR); + } + } + } else if(StrEqual(config.type, "_dummy")) { + if(CreateDummy(config.model, "hitby_tankpunch", config.origin, config.rotation) == -1) { + Game.Warn("Failed to spawn dummy [model=%s] at (%.1f,%.1f, %.1f)", config.model, config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "env_fire")) { + if(props && CreateFire(config.origin, config.scale[0], config.scale[1], config.scale[2]) == -1) { + Game.Warn("Failed to spawn env_fire at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(props) { + if(CreateProp(config.type, config.model, config.origin, config.rotation) == -1) { + Game.Warn("Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]); + } + } + } + + static char key[64]; + static char value[64]; + if(mapConfig.inputs != null) { + for(int i = 0; i < mapConfig.inputs.Length - 1; i += 2) { + mapConfig.inputs.GetString(i, key, sizeof(key)); + mapConfig.inputs.GetString(i + 1, value, sizeof(value)); + EntFire(key, value); + } + } + } +} + diff --git a/scripting/include/guesswho/gwgame.inc b/scripting/include/guesswho/gwgame.inc new file mode 100644 index 0000000..9911593 --- /dev/null +++ b/scripting/include/guesswho/gwgame.inc @@ -0,0 +1,471 @@ +static int mapChangeMsgTicks = 5; + +int GetColorInt(int r, int g, int b) { + int color = r; + color += 256 * g; + color += 65536 * b; + return color; +} + +Action Timer_ChangeMap(Handle h) { + PrintToChatAll("Changing map to %s in %d seconds", nextRoundMap, mapChangeMsgTicks); + if(mapChangeMsgTicks-- == 0) { + ForceChangeLevel(nextRoundMap, "GuessWhoMapSelect"); + nextRoundMap[0] = '\0'; + return Plugin_Stop; + } + return Plugin_Continue; +} + +void ChangeMap(const char map[64], int time = 5) { + strcopy(nextRoundMap, sizeof(nextRoundMap), map); + mapChangeMsgTicks = time; + CreateTimer(1.0, Timer_ChangeMap, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); +} + +bool FindSpawnPosition(float pos[3], bool includePlayers = true) { + if(includePlayers) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + GetClientAbsOrigin(i, pos); + return true; + } + } + } + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "info_player_start")) != INVALID_ENT_REFERENCE) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + return true; + } + return false; +} + +static char buffer[128]; + +methodmap GuessWhoGame < BaseGame { + + property int Seeker { + public get() { + if(currentSeeker <= 0 || !IsClientConnected(currentSeeker)) + currentSeeker = this._FindSeeker(); + return currentSeeker; + } + public set(int client) { + int existingSeeker = currentSeeker; + currentSeeker = client; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + this.SetupInventory(i); + } + } + // Reset things incase set mid-start + if(existingSeeker > 0) { + SetEntPropFloat(existingSeeker, Prop_Send, "m_flLaggedMovementValue", 1.0); + SetPlayerBlind(existingSeeker, 0); + L4D2_RemoveEntityGlow(existingSeeker); + } + + L4D2_SetEntityGlow(client, L4D2Glow_Constant, 0, 10, SEEKER_GLOW_COLOR, false); + + hasBeenSeeker[client] = true; + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.CurrentSeeker = GetPlayerFromUserID(%d);", GetClientUserId(client)); + L4D2_ExecVScriptCode(buffer); + } + } + + property int Tick { + public get() { + if(!isEnabled) return -1; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.Tick", buffer, sizeof(buffer)); + int value = -1; + if(StringToIntEx(buffer, value) > 0) { + return value; + } else { + return -1; + } + } + public set(int tick) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.Tick = %d", tick); + L4D2_ExecVScriptCode(buffer); + } + } + + property GameState State { + public get() { + if(!isEnabled) return State_Unknown; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.State", buffer, sizeof(buffer)); + int stage = 0; + if(StringToIntEx(buffer, stage) > 0) { + return view_as(stage); + } else { + return State_Unknown; + } + } + public set(GameState state) { + if(isEnabled) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.State = %d", view_as(state)); + L4D2_ExecVScriptCode(buffer); + } + } + } + + property int MapTime { + public get() { + L4D2_GetVScriptOutput("g_ModeScript.MutationState.MaxTime", buffer, sizeof(buffer)); + return StringToInt(buffer); + } + public set(int seconds) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.MaxTime = %d", seconds); + L4D2_ExecVScriptCode(buffer); + if(timesUpTimer != null) { + float remaining = float(seconds) - float(this.Tick); + delete timesUpTimer; + timesUpTimer = CreateTimer(remaining, Timer_TimesUp, _, TIMER_FLAG_NO_MAPCHANGE); + } + } + } + + public void Start() { + + } + + public void End(GameState state) { + if(recordTimer != null) { + PrintToChatAll("Active recording stopped due to end of game. %d ready to save. \"/guesswho points save\" to save", movePoints.Length); + delete recordTimer; + } + if(acquireLocationsTimer != null) delete acquireLocationsTimer; + if(timesUpTimer != null) delete timesUpTimer; + if(hiderCheckTimer != null) delete hiderCheckTimer; + currentSeeker = 0; + this.State = state; + if(state == State_HidersWin) { + // Show the hiders + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsFakeClient(i)) { + if(IsFakeClient(i)) { + ClearInventory(i); + KickClient(i); + } else { + L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 20, PLAYER_GLOW_COLOR, false); + L4D2_SetPlayerSurvivorGlowState(i, true); + } + } + } + } + this.CleanupGnomes(true); + CreateTimer(5.0, Timer_ResetAll); + } + + public void Cleanup(bool noClearInv = false) { + DeleteCustomEnts(); + PeekCam.Destroy(); + if(recordTimer != null) delete recordTimer; + if(doorToggleTimer != null) delete doorToggleTimer; + if(waitForStartTimer != null && IsValidHandle(waitForStartTimer)) delete waitForStartTimer; + if(waitTimer != null) delete waitTimer; + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(!noClearInv && isEnabled) + ClearInventory(i); + Game.UnsetupPlayer(i); + } + if(moveTimers[i] != null) { + delete moveTimers[i]; + } + } + // Annoying + this.CleanupGnomes(); + } + + public void CleanupGnomes(bool orphansOnly = false) { + int entity = INVALID_ENT_REFERENCE; + char model[32]; + while ((entity = FindEntityByClassname(entity, "prop_physics")) != INVALID_ENT_REFERENCE) { + int parent = GetEntPropEnt(entity, Prop_Data, "m_hParent"); + if(orphansOnly && parent >= 0) continue; + GetEntPropString(entity, Prop_Data, "m_ModelName", model, sizeof(model)); + if(StrEqual(model, "models/props_junk/gnome.mdl")) { + RemoveEntity(entity); + } + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "weapon_gnome")) != INVALID_ENT_REFERENCE) { + int owner = GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); + if(orphansOnly && owner >= 0) continue; + GetEntPropString(entity, Prop_Data, "m_ModelName", model, sizeof(model)); + } + } + + + public int _FindSeeker() { + if(!isEnabled) return -1; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.CurrentSeeker && \"GetPlayerUserId\" in g_ModeScript.MutationState.CurrentSeeker ? g_ModeScript.MutationState.CurrentSeeker.GetPlayerUserId() : -1", buffer, sizeof(buffer)); + int uid = StringToInt(buffer); + if(uid > 0) { + return GetClientOfUserId(uid); + } else { + Game.Debug("Mutation has no seeker, manually attempting to find seeker"); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + int entity = GetPlayerWeaponSlot(i, 1); + if(entity > -1 && GetEntityClassname(entity, buffer, sizeof(buffer)) && StrEqual(buffer, "melee")) { + GetEntPropString(entity, Prop_Data, "m_strMapSetScriptName", buffer, sizeof(buffer)); + if(StrEqual(buffer, "fireaxe")) { + return i; + } + } + } + } + } + Game.Debug("All attempts to find a seeker failed"); + return -1; + } + + + public void ForceSetSeeker(int client, bool ignoreBalance = false) { + ignoreSeekerBalance = true; + this.Seeker = client; + } + + public bool TeleportToSpawn(int client) { + if(mapConfig.hasSpawnpoint) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + return true; + } else { + float pos[3]; + if(FindSpawnPosition(pos)) { + return false; + } + TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR); + } + return false; + } + + public void TeleportAllToStart() { + if(mapConfig.hasSpawnpoint) { + PrintToServer("[GuessWho] Teleporting all players to provided spawnpoint (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + this.TeleportToSpawn(i); + } + } + } else { + PrintToServer("[GuessWho] Warn: No spawnpoint found (provided or map spawn)"); + } + } + + public void SetPoints(MovePoints points) { + if(movePoints != null) { + delete movePoints; + } + if(points == null) { + movePoints = new MovePoints(); + } else { + movePoints = points; + } + } + + // Ignores seeker + property int AlivePlayers { + public get() { + int amount = 0; + for(int i = 1; i <= MaxClients; i++) { + if(i != currentSeeker && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && !IsFakeClient(i)) { + amount++; + } + } + return amount; + } + } + + public void SetupInventory(int client) { + ClearInventory(client); + ignoreDrop[client] = true; + if(client == this.Seeker) { + CheatCommand(client, "give", "fireaxe"); + } else { + GivePlayerItem(client, "weapon_gnome"); + } + ignoreDrop[client] = false; + } + + public void SetupPlayer(int client) { + this.SetupInventory(client); + SDKHook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + SDKHook(client, SDKHook_WeaponEquip, OnWeaponEquip); + } + + public void UnsetupPlayer(int client) { + SDKUnhook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + SDKUnhook(client, SDKHook_WeaponEquip, OnWeaponEquip); + } +} + +stock bool ArePlayersJoining() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsClientInGame(i)) { + return true; + } + } + return false; +} + +stock void GetHorizontalPositionFromClient(int client, float units, float finalPosition[3]) { + float pos[3], ang[3]; + GetClientEyeAngles(client, ang); + GetClientAbsOrigin(client, pos); + + float theta = DegToRad(ang[1]); + pos[0] += units * Cosine(theta); + pos[1] += units * Sine(theta); + finalPosition = pos; +} + +stock void GetAnglesLookAt(int iClient, int iTarget, float fFinalPos[3]) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + + GetEntPropVector(iClient, Prop_Send, "m_vecOrigin", fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + // TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} +stock void AddInFrontOf(const float fVecOrigin[3], const float fVecAngle[3], float fUnits, float fOutPut[3]) +{ + float fVecView[3]; GetViewVector(fVecAngle, fVecView); + + fOutPut[0] = fVecView[0] * fUnits + fVecOrigin[0]; + fOutPut[1] = fVecView[1] * fUnits + fVecOrigin[1]; + fOutPut[2] = fVecView[2] * fUnits + fVecOrigin[2]; +} +stock void GetViewVector(const float fVecAngle[3], float fOutPut[3]) +{ + fOutPut[0] = Cosine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[1] = Sine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[2] = -Sine(fVecAngle[0] / (180 / FLOAT_PI)); +} + +stock void LookAtClient(int iClient, int iTarget) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + static float fFinalPos[3]; + + GetClientEyePosition(iClient, fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} + +stock void LookAtPoint(int client, const float targetPos[3]) { + static float targetAngles[3]; + static float clientPos[3]; + static float fFinalPos[3]; + + GetClientEyePosition(client, clientPos); + GetClientEyeAngles(client, targetAngles); + + float fVecFinal[3]; + AddInFrontOf(targetPos, targetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(clientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + TeleportEntity(client, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} + + +void SetPlayerBlind(int target, int amount) { + int targets[1]; + targets[0] = target; + + int duration = 1536; + int holdtime = 1536; + int flags = (amount == 0) ? (0x0001 | 0x0010) : (0x0002 | 0x0008); + int color[4] = { 0, 0, 0, 0 }; + color[3] = amount; + + Handle message = StartMessageEx(g_FadeUserMsgId, targets, 1); + BfWrite bf = UserMessageToBfWrite(message); + bf.WriteShort(duration); + bf.WriteShort(holdtime); + bf.WriteShort(flags); + bf.WriteByte(color[0]); + bf.WriteByte(color[1]); + bf.WriteByte(color[2]); + bf.WriteByte(color[3]); + EndMessage(); +} + +#define HIDER_DISTANCE_MAX_SIZE 10 + + +#define MAX_AUTO_VOCALIZATIONS 9 +static char AUTO_VOCALIZATIONS[MAX_AUTO_VOCALIZATIONS][] = { + "PlayerLaugh", + "PlayerSpotPill", + "Playerlookout", + "EatPills", + "ReviveMeInterrupted", + "PlayerIncapacitated", + "PlayerNiceShot", + "ResponseSoftDispleasureSwear", + "PlayerAreaClear" +}; + +enum struct HiderDistQueue { + int index; + float list[HIDER_DISTANCE_MAX_SIZE]; + int lastVocalize; + + void AddPos(const float pos[3]) { + this.list[this.index] = GetVectorDistance(seekerPos, pos); + if(++this.index == HIDER_DISTANCE_MAX_SIZE) { + this.index = 0; + } + } + + void Clear() { + for(int i = 0; i < HIDER_DISTANCE_MAX_SIZE; i++) { + this.list[i] = 0.0; + } + } + + float GetAverage() { + float sum = 0.0; + for(int i = 0; i < HIDER_DISTANCE_MAX_SIZE; i++) { + sum += this.list[i]; + } + return sum / float(HIDER_DISTANCE_MAX_SIZE); + } + + void Check(int i) { + if(this.GetAverage() > HIDER_MIN_AVG_DISTANCE_AUTO_VOCALIZE) { + int time = GetTime(); + if(time - this.lastVocalize > HIDER_AUTO_VOCALIZE_GRACE_TIME) { + this.lastVocalize = time; + int index = GetRandomInt(0, MAX_AUTO_VOCALIZATIONS - 1); + PerformScene(i, AUTO_VOCALIZATIONS[index]); + } + } + } +} + +HiderDistQueue distQueue[MAXPLAYERS+1]; \ No newline at end of file diff --git a/scripting/include/guesswho/gwpoints.inc b/scripting/include/guesswho/gwpoints.inc new file mode 100644 index 0000000..637d2df --- /dev/null +++ b/scripting/include/guesswho/gwpoints.inc @@ -0,0 +1,134 @@ +enum struct LocationMeta { + float pos[3]; + float ang[3]; + bool runto; + bool jump; + int attempts; // # of attempts player has moved until they will try to manage +} + +// Game settings +LocationMeta activeBotLocations[MAXPLAYERS+1]; + +methodmap MovePoints < ArrayList { + public MovePoints() { + return view_as(new ArrayList(sizeof(LocationMeta))); + } + + public bool SaveMap(const char[] map, const char[] set = "default") { + char buffer[256]; + // guesswho folder should be created by ReloadMapDB + BuildPath(Path_SM, buffer, sizeof(buffer), "data/guesswho/%s", map); + CreateDirectory(buffer, FOLDER_PERMS); + BuildPath(Path_SM, buffer, sizeof(buffer), "data/guesswho/%s/%s.txt", map, set); + File file = OpenFile(buffer, "w+"); + if(file != null) { + file.WriteLine("px\tpy\tpz\tax\tay\taz"); + LocationMeta meta; + for(int i = 0; i < movePoints.Length; i++) { + movePoints.GetArray(i, meta); + file.WriteLine("%.1f %.1f %.1f %.1f %.1f %.1f", meta.pos[0], meta.pos[1], meta.pos[2], meta.ang[0], meta.ang[1], meta.ang[2]); + } + PrintToServer("[GuessWho] Saved %d locations to %s/%s.txt", movePoints.Length, map, set); + file.Flush(); + delete file; + return true; + } + PrintToServer("[GuessWho] OpenFile(w+) returned null for %s", buffer); + return false; + } + + public static MovePoints LoadMap(const char[] map, const char[] set = "default") { + char buffer[256]; + BuildPath(Path_SM, buffer, sizeof(buffer), "data/guesswho/%s/%s.txt", map, set); + LoadConfigForMap(map); + File file = OpenFile(buffer, "r+"); + if(file != null) { + char line[64]; + char pieces[16][6]; + file.ReadLine(line, sizeof(line)); // Skip header + float min = L4D2Direct_GetMapMaxFlowDistance(); + float max = 0.0; + MovePoints points = new MovePoints(); + while(file.ReadLine(line, sizeof(line))) { + ExplodeString(line, " ", pieces, 6, 16, false); + LocationMeta meta; + meta.pos[0] = StringToFloat(pieces[0]); + meta.pos[1] = StringToFloat(pieces[1]); + meta.pos[2] = StringToFloat(pieces[2]); + meta.ang[0] = StringToFloat(pieces[3]); + meta.ang[1] = StringToFloat(pieces[4]); + meta.ang[2] = StringToFloat(pieces[5]); + + // Calculate the flow bounds + Address nav = L4D2Direct_GetTerrorNavArea(meta.pos); + if(nav == Address_Null) { + nav = L4D_GetNearestNavArea(meta.pos); + if(nav == Address_Null) { + PrintToServer("[GuessWho] WARN: POINT AT (%f,%f,%f) IS INVALID (NO NAV AREA); skipping", meta.pos[0], meta.pos[1], meta.pos[2]); + continue; + } + } + float flow = L4D2Direct_GetTerrorNavAreaFlow(nav); + if(flow < min) min = flow; + else if(flow > max) max = flow; + + points.AddPoint(meta); + } + // Give some buffer space, to not trigger TOO FAR + min -= FLOW_BOUND_BUFFER; + max += FLOW_BOUND_BUFFER; + + movePoints.SetBounds(min, max); + + PrintToServer("[GuessWho] Loaded %d locations with bounds [%.0f, %.0f] for %s/%s", points.Length, min, max, map, set); + delete file; + return points; + } + PrintToServer("[GuessWho] No point data for %s/%s", map, set); + return null; + } + + property float MinFlow { + public get() { return flowMin; } + } + property float MaxFlow { + public get() { return flowMax; } + } + + public void SetBounds(float min, float max) { + flowMin = min; + flowMax = max; + } + + public void GetRandomPoint(LocationMeta meta) { + if(this.Length == 0) return; + meta.runto = GetURandomFloat() < BOT_MOVE_RUN_CHANCE; + meta.attempts = 0; + this.GetArray(GetURandomInt() % this.Length, meta); + #if defined DEBUG_SHOW_POINTS + Effect_DrawBeamBoxRotatableToAll(meta.pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 255, 120}, 0); + #endif + } + + public bool GetRandomPointFar(const float src[3], float pos[3], float distanceAway = 100.0, int tries = 3) { + while(tries-- > 0) { + this.GetArray(GetURandomInt() % this.Length, pos); + if(FloatAbs(GetVectorDistance(src, pos)) > distanceAway) { + return true; + } + } + return false; + } + + public bool AddPoint(LocationMeta meta) { + bool hitLimit = false; + if(this.Length + 1 > MAX_VALID_LOCATIONS) { + PrintToServer("[GuessWho] Hit MAX_VALID_LOCATIONS (%d), clearing some locations", MAX_VALID_LOCATIONS); + this.Sort(Sort_Random, Sort_Float); + this.Erase(RoundFloat(MAX_VALID_LOCATIONS * MAX_VALID_LOCATIONS_KEEP_PERCENT)); + hitLimit = true; + } + this.PushArray(meta); + return hitLimit; + } +} \ No newline at end of file diff --git a/scripting/include/guesswho/gwtimers.inc b/scripting/include/guesswho/gwtimers.inc new file mode 100644 index 0000000..1a37392 --- /dev/null +++ b/scripting/include/guesswho/gwtimers.inc @@ -0,0 +1,70 @@ + +Action Timer_RecordPoints(Handle h, int i) { + if(GetEntityFlags(i) & FL_ONGROUND && IsPlayerAlive(i)) { + LocationMeta meta; + GetClientAbsOrigin(i, meta.pos); + GetClientEyeAngles(i, meta.ang); + if(meta.pos[0] != vecLastLocation[i][0] || meta.pos[1] != vecLastLocation[i][1] || meta.pos[2] != vecLastLocation[i][2]) { + if(movePoints.AddPoint(meta)) { + recordTimer = null; + return Plugin_Stop; + } + Effect_DrawBeamBoxRotatableToClient(i, meta.pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {0, 0, 255, 64}, 0); + vecLastLocation[i] = meta.pos; + } + } + PrintHintText(i, "Points: %d / %d", movePoints.Length, MAX_VALID_LOCATIONS); + return Plugin_Continue; +} + +bool firstCheckDone = false; +Action Timer_WaitForPlayers(Handle h) { + if(!isEnabled) return Plugin_Stop; + if(!ArePlayersJoining()) { + Game.Debug("No players pending, ready to go"); + if(!firstCheckDone) { + // Wait one more iteration + firstCheckDone = true; + } else { + firstCheckDone = false; + InitGamemode(); + return Plugin_Stop; + } + } + Game.Debug("Waiting for players"); + return Plugin_Continue; +} + + +Action Timer_CheckHiders(Handle h) { + static float pos[3]; + static char classname[16]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + GetClientAbsOrigin(i, pos); + distQueue[i].AddPos(pos); + distQueue[i].Check(i); + + int activeWeapon = GetEntPropEnt(i, Prop_Send, "m_hActiveWeapon"); + if(IsValidEntity(activeWeapon)) { + GetEntityClassname(activeWeapon, classname, sizeof(classname)); + if(i == currentSeeker) { + if(StrEqual(classname, "weapon_melee")) continue; + Game.SetupInventory(i); + } else if(StrEqual(classname, "weapon_gnome")) continue; + } + Game.SetupInventory(i); + } + } + Game.CleanupGnomes(true); + return Plugin_Continue; +} + +Action Timer_ResetAll(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + ForcePlayerSuicide(i); + } + } + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/include/hats/props/base.sp b/scripting/include/hats/props/base.sp index 41d8517..01a23de 100644 --- a/scripting/include/hats/props/base.sp +++ b/scripting/include/hats/props/base.sp @@ -22,7 +22,6 @@ enum struct PlayerPropData { // When did the user last interact with prop spawner? (Shows hints after long inactivity) int lastActiveTime; char classnameOverride[32]; - ChatPrompt chatPrompt; ArrayList markedProps; diff --git a/scripting/include/hideandseek/hscmds.inc b/scripting/include/hideandseek/hscmds.inc new file mode 100644 index 0000000..4906c45 --- /dev/null +++ b/scripting/include/hideandseek/hscmds.inc @@ -0,0 +1,370 @@ +public Action Command_HideAndSeek(int client, int args) { + if(args > 0) { + char subcmd[16]; + GetCmdArg(1, subcmd, sizeof(subcmd)); + if(StrEqual(subcmd, "r") || StrEqual(subcmd, "reload", false)) { + GetCurrentMap(g_currentMap, sizeof(g_currentMap)); + char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(ReloadMapDB()) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: Map has no config file"); + } + Cleanup(); + if(arg[0] == 'f') { + CreateTimer(0.1, Timer_RoundStart); + } + SetupEntities(isNavBlockersEnabled, isPropsEnabled, isPortalsEnabled); + ReplyToCommand(client, "Reloaded map from config"); + } else { + ReplyToCommand(client, "Error occurred while reloading map file"); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "set", false)) { + char set[16]; + if(args == 1) { + if(validSets.Length == 0) ReplyToCommand(client, "Map has no map sets or no map configuration"); + else { + ReplyToCommand(client, "Available Map Sets: "); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + if(StrEqual(g_currentSet, set)) { + CReplyToCommand(client, "{olive}%d. %s (Active)", i + 1, set); + } else + ReplyToCommand(client, "%d. %s", i + 1, set); + } + CReplyToCommand(client, "Change map set with {yellow}/hs set "); + } + } else { + GetCmdArg(2, g_currentSet, sizeof(g_currentSet)); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + if(StrEqual(set, g_currentSet)) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: Map has no config file"); + } + Cleanup(); + SetupEntities(isNavBlockersEnabled, isPropsEnabled, isPortalsEnabled); + CPrintToChatAll("[H&S] Map set changed to {olive}%s", g_currentSet); + return Plugin_Handled; + } + } + ReplyToCommand(client, "Warning: Set was not found, if this is an error use /hs r to load."); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "toggle")) { + char type[32]; + GetCmdArg(2, type, sizeof(type)); + bool doAll = StrEqual(type, "all"); + bool isUnknown = true; + + if(doAll || StrEqual(type, "blockers", false)) { + if(isNavBlockersEnabled) { + EntFire("hsblocker", "Disable"); + ReplyToCommand(client, "Disabled all custom gamemode blockers"); + } else { + EntFire("hsblocker", "Enable"); + ReplyToCommand(client, "Enabled all custom gamemode blockers"); + } + isNavBlockersEnabled = !isNavBlockersEnabled; + isUnknown = false; + } + if(doAll || StrEqual(type, "props", false)) { + if(isPropsEnabled) { + EntFire("hsprop", "Disable"); + EntFire("hsprop", "DisableCollision"); + ReplyToCommand(client, "Disabled all custom gamemode props"); + } else { + EntFire("hsprop", "Enable"); + EntFire("hsprop", "EnableCollision"); + ReplyToCommand(client, "Enabled all custom gamemode props"); + } + isPropsEnabled = !isPropsEnabled; + isUnknown = false; + } + if(doAll || StrEqual(type, "portals", false)) { + if(isPortalsEnabled) { + EntFire("hsportal", "Disable"); + ReplyToCommand(client, "Disabled all custom gamemode portals"); + } else { + EntFire("hsportal", "Enable"); + ReplyToCommand(client, "Enabled all custom gamemode portals"); + } + isPortalsEnabled = !isPortalsEnabled; + isUnknown = false; + } + if(isUnknown) ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', 'portals', or 'all'"); + return Plugin_Handled; + } else if(StrEqual(subcmd, "clear", false)) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "all")) { + Cleanup(); + ReplyToCommand(client, "Cleaned up everything."); + } else if(StrEqual(arg, "props")) { + EntFire("hsprop", "kill"); + ReplyToCommand(client, "Removed all custom gamemode props"); + } else if(StrEqual(arg, "blockers")) { + EntFire("hsblocker", "kill"); + ReplyToCommand(client, "Removed all custom gamemode blockers"); + } else if(StrEqual(arg, "portals")) { + EntFire("hsportal", "kill"); + ReplyToCommand(client, "Removed all custom gamemode portals"); + } else ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', 'portals', or 'all'"); + return Plugin_Handled; + } else if(StrEqual(subcmd, "settime")) { + int prev = GetMapTime(); + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int time = StringToInt(arg); + mapConfig.mapTime = time; + SetMapTime(time); + ReplyToCommand(client, "Map's time is temporarily set to %d seconds (was %d)", time, prev); + return Plugin_Handled; + } else if(StrEqual(subcmd, "settick")) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int tick = -StringToInt(arg); + SetTick(tick); + ReplyToCommand(client, "Set tick time to %d", tick); + return Plugin_Handled; + } else if(StrEqual(subcmd, "map")) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "list")) { + ReplyToCommand(client, "See the console for available maps"); + char map[64]; + for(int i = 0; i < validMaps.Length; i++) { + validMaps.GetString(i, map, sizeof(map)); + PrintToConsole(client, "%d. %s", i + 1, map); + } + } else if(StrEqual(arg, "random")) { + bool foundMap; + char map[64]; + do { + int mapIndex = GetURandomInt() % validMaps.Length; + validMaps.GetString(mapIndex, map, sizeof(map)); + if(!StrEqual(g_currentMap, map, false)) { + foundMap = true; + } + } while(!foundMap); + CPrintToChatAll("[H&S] Switching map to {olive}%s", map); + ChangeMap(map); + } else if(StrEqual(arg, "next", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change on the next round: 'next '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + strcopy(nextRoundMap, sizeof(nextRoundMap), arg2); + CPrintToChatAll("[H&S] Switching map next round to {olive}%s", arg2); + ForceChangeLevel(arg, "SetMapSelect"); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else if(StrEqual(arg, "force", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change to: 'force '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + CPrintToChatAll("[H&S] Switching map to {olive}%s", arg2); + ChangeMap(arg2); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else { + ReplyToCommand(client, "Syntax: 'map /next >"); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "pos", false)) { + float pos[3]; + GetAbsOrigin(client, pos); + ReplyToCommand(client, "\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientEyeAngles(client, pos); + ReplyToCommand(client, "\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + return Plugin_Handled; + } else if(StrEqual(subcmd, "prop", false)) { + float pos[3]; + GetAbsOrigin(client, pos); + ReplyToCommand(client, "\"MYPROP\""); + ReplyToCommand(client, "{"); + ReplyToCommand(client, "\t\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientAbsAngles(client, pos); + ReplyToCommand(client, "\t\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + ReplyToCommand(client, "\t\"type\" \"prop_dynamic\""); + ReplyToCommand(client, "\t\"model\" \"props_junk/dumpster_2.mdl\""); + ReplyToCommand(client, "}"); + return Plugin_Handled; + } else if(StrEqual(subcmd, "setspawn", false)) { + GetClientAbsOrigin(client, mapConfig.spawnpoint); + ReplyToCommand(client, "Set map's temporarily spawnpoint to your location."); + return Plugin_Handled; + } else if(StrEqual(subcmd, "stuck")) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + return Plugin_Handled; + } else if(StrEqual(subcmd, "bots")) { + if(args == 2) { + char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "toggle")) { + bool newValue = !IsBotsEnabled(); + SetBotsEnabled(newValue); + if(newValue) ReplyToCommand(client, "Bots are now enabled"); + else ReplyToCommand(client, "Bots are now disabled"); + return Plugin_Handled; + } else if(StrEqual(arg, "on") || StrEqual(arg, "true")) { + SetBotsEnabled(true); + ReplyToCommand(client, "Bots are now enabled"); + return Plugin_Handled; + } else if(StrEqual(arg, "off") || StrEqual(arg, "false")) { + SetBotsEnabled(false); + ReplyToCommand(client, "Bots are now disabled"); + return Plugin_Handled; + } + } + if(IsBotsEnabled()) ReplyToCommand(client, "Bots are enabled"); + else ReplyToCommand(client, "Bots are disabled"); + return Plugin_Handled; + } else if(StrEqual(subcmd, "peekfix")) { + if(!PeekCam.Exists()) { + PeekCam.Target = client; + } + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + PeekCam.SetViewing(client, true); + PeekCam.SetViewing(client, false); + } + } + PeekCam.Destroy(); + ReplyToCommand(client, "Killing active camera"); + return Plugin_Handled; + } else if(StrEqual(subcmd, "seeker")) { + if(args == 2) { + char arg1[32]; + GetCmdArg(2, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_list[0] == 0){ + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + SetSlasher(target_list[0], true); + ReplyToCommand(client, "Set the current seeker to %N", target_list[0]); + } else { + ReplyToCommand(client, "The current seeker is: %N", GetSlasher()); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "debug")) { + ReplyToCommand(client, "- Game Info -"); + int addSlasher = GetSlasher(); + ReplyToCommand(client, "Current seeker: %N(%d) (addon says %N(%d))", currentSeeker, currentSeeker, addSlasher, addSlasher); + ReplyToCommand(client, "State: %d | Tick: %d", view_as(GetState()), GetTick()); + + ReplyToCommand(client, "- Map Info -"); + ReplyToCommand(client, "Map: %s (set %s)", g_currentMap, g_currentSet); + if(mapConfig.hasSpawnpoint) + ReplyToCommand(client, "Has Spawnpoint: yes (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + else + ReplyToCommand(client, "Has Spawnpoint: no (possibly map spawn %f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + ReplyToCommand(client, "Climbing: %b", mapConfig.canClimb); + ReplyToCommand(client, "Buttons Auto-press: %b", mapConfig.pressButtons); + ReplyToCommand(client, "Map Time Override: %d", mapConfig.mapTime); + ReplyToCommand(client, "Your travel distance: %f", distanceTraveled[client]); + return Plugin_Handled; + } + ReplyToCommand(client, "Unknown command"); + return Plugin_Handled; + } + ReplyToCommand(client, " === [ Hide & Seek Commands ] ==="); + if(GetUserAdmin(client) != INVALID_ADMIN_ID) { + ReplyToCommand(client, "- Dev Commands -"); + ReplyToCommand(client, "r/reload [force]: Reloads map config from file"); + ReplyToCommand(client, "toggle : Toggles all specified entities"); + ReplyToCommand(client, "clear : Clear all specified"); + ReplyToCommand(client, "settime [seconds]: Sets the time override for the map"); + ReplyToCommand(client, "settick [tick]: Sets the current tick timer value"); + ReplyToCommand(client, "- Admin Commands -"); + ReplyToCommand(client, "set [new set]: Change the prop set or view current"); + ReplyToCommand(client, "setspawn: Sets the temporary spawnpoint for the map"); + ReplyToCommand(client, "bots [toggle, [value]]: View if bots are enabled, or turn them on"); + ReplyToCommand(client, "peekfix - Clear peek camera from all players"); + ReplyToCommand(client, "seeker [new seeker]: Get the active seeker, or set a new one."); + ReplyToCommand(client, "sm_cvar hs_peekcam <0/2> - Turn the peek camera on or off"); + ReplyToCommand(client, "- User Commands -"); + } + ReplyToCommand(client, "stuck: Teleports you to spawn to unstuck yourself"); + return Plugin_Handled; +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) { + if(isEnabled) { + if(!StrEqual(command, "say")) { //Is team message + if(currentSeeker <= 0 || currentSeeker == client) { + return Plugin_Continue; + } + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && i != currentSeeker) + PrintToChat(i, "[Hiders] %N: %s", client, sArgs); + } + return Plugin_Handled; + } + } + return Plugin_Continue; +} + + +public Action Command_Join(int client, int args) { + if(!isEnabled) return Plugin_Continue; + if(args == 1) { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(GetClientTeam(target) != 2) { + JoinGame(target); + } + } + ReplyToCommand(client, "Joined %s", target_name); + } else { + if(currentSeeker == client) { + ReplyToCommand(client, "You are already in-game as a seeker."); + return Plugin_Handled; + } + JoinGame(client); + } + return Plugin_Handled; +} diff --git a/scripting/include/hideandseek/hscore.inc b/scripting/include/hideandseek/hscore.inc new file mode 100644 index 0000000..c4f903a --- /dev/null +++ b/scripting/include/hideandseek/hscore.inc @@ -0,0 +1,203 @@ +#include +#include +#include + +static KeyValues kv; +StringMap mapConfigs; + +static float DEFAULT_SCALE[3] = { 5.0, 5.0, 5.0 }; + +bool ReloadMapDB() { + if(kv != null) { + delete kv; + } + kv = new KeyValues("hideandseek"); + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/hideandseek.cfg"); + + + if(!FileExists(sPath) || !kv.ImportFromFile(sPath)) { + delete kv; + return false; + } + + validMaps.Clear(); + + char map[64]; + kv.GotoFirstSubKey(true); + do { + kv.GetSectionName(map, sizeof(map)); + validMaps.PushString(map); + } while(kv.GotoNextKey(true)); + kv.GoBack(); + return true; +} + + +bool LoadConfigForMap(const char[] map) { + kv.Rewind(); + if (kv.JumpToKey(map)) { + MapConfig config; + config.entities = new ArrayList(sizeof(EntityConfig)); + config.inputs = new ArrayList(ByteCountToCells(64)); + validSets.Clear(); + + static char buffer[64]; + if(StrEqual(g_currentSet, "default") && kv.GetString("defaultset", buffer, sizeof(buffer)) && buffer[0] != '\0') { + strcopy(g_currentSet, sizeof(g_currentSet), buffer); + } + PrintToServer("[H&S] Loading config data for set %s on %s", g_currentSet, map); + + if(kv.JumpToKey("ents")) { + kv.GotoFirstSubKey(); + do { + EntityConfig entCfg; + kv.GetVector("origin", entCfg.origin, NULL_VECTOR); + kv.GetVector("rotation", entCfg.rotation, NULL_VECTOR); + kv.GetString("type", entCfg.type, sizeof(entCfg.type), "env_physics_blocker"); + kv.GetString("model", entCfg.model, sizeof(entCfg.model), ""); + if(entCfg.model[0] != '\0') + Format(entCfg.model, sizeof(entCfg.model), "models/%s", entCfg.model); + kv.GetVector("scale", entCfg.scale, DEFAULT_SCALE); + kv.GetVector("offset", entCfg.offset, NULL_VECTOR); + kv.GetString("set", buffer, sizeof(buffer), "default"); + if(validSets.FindString(buffer) == -1) { + validSets.PushString(buffer); + } + if(StrEqual(buffer, "default") || StrEqual(g_currentSet, buffer, false)) { + kv.GetSectionName(buffer, sizeof(buffer)); + PrintToServer("Loaded %s", buffer); + config.entities.PushArray(entCfg); + } else { + kv.GetSectionName(buffer, sizeof(buffer)); + PrintToServer("Skipping %s", buffer); + } + } while (kv.GotoNextKey()); + // JumpToKey and GotoFirstSubKey both traverse, i guess, go back + kv.GoBack(); + kv.GoBack(); + } + if(kv.JumpToKey("inputs")) { + kv.GotoFirstSubKey(false); + do { + kv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + kv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (kv.GotoNextKey(false)); + kv.GoBack(); + kv.GoBack(); + } + int mapTime; + + config.hasSpawnpoint = false; + config.canClimb = true; + config.pressButtons = true; + if(!StrEqual(g_currentSet, "default") && kv.JumpToKey("sets")) { + char set[16]; + kv.GotoFirstSubKey(true); + do { + kv.GetSectionName(set, sizeof(set)); + if(validSets.FindString(set) == -1) { + validSets.PushString(set); + } + if(StrEqual(g_currentSet, set, false)) { + kv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[H&S] Using provided custom spawnpoint for set %s at %0.1f, %0.1f, %0.1f", g_currentSet, config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } + char buf[8]; + kv.GetString("climbing", buf, sizeof(buf)); + config.canClimb = !StrEqual(buf, "off"); + kv.GetString("buttons", buf, sizeof(buf)); + config.pressButtons = !StrEqual(buf, "no"); + mapTime = kv.GetNum("maptime", 0); + if(kv.JumpToKey("inputs")) { + kv.GotoFirstSubKey(false); + do { + kv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + kv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (kv.GotoNextKey(false)); + kv.GoBack(); + kv.GoBack(); + } + break; + } + + } while(kv.GotoNextKey(true)); + kv.GoBack(); + kv.GoBack(); + } + + if(!config.hasSpawnpoint) { + kv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[H&S] Using provided custom spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else if (GetSpawnPosition(config.spawnpoint, false)) { + PrintToServer("[H&S] Using map spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else { + PrintToServer("[H&S] Could not find any spawnpoints, using default spawn"); + config.hasSpawnpoint = false; + } + } + + // Use default maptime if exists + if(mapTime == 0) + mapTime = kv.GetNum("maptime", 0); + if(mapTime > 0) { + config.mapTime = mapTime; + PrintToServer("[H&S] Map time overwritten to %d seconds", mapTime); + } + + char buf[8]; + if(config.canClimb) { + kv.GetString("climbing", buf, sizeof(buf)); + config.canClimb = !StrEqual(buf, "off"); + } + if(config.pressButtons) { + kv.GetString("buttons", buf, sizeof(buf)); + config.pressButtons = !StrEqual(buf, "no"); + } + + + + mapConfigs.SetArray(map, config, sizeof(MapConfig)); + // Discard entInputs if unused + if(config.inputs.Length == 0) { + delete config.inputs; + } + mapConfig = config; + return true; + } else { + mapConfig.hasSpawnpoint = false; + PrintToServer("[H&S] No map config exists for %s", map); + return false; + } +} + +int COLOR_GREY[4] = { 194, 197, 204, 255 }; +int COLOR_GREEN[4] = { 0, 128, 0, 255 }; + +void ShowBeacon(int target, float radius = 100.0) { + float vec[3]; + GetClientAbsOrigin(target, vec); + vec[2] += 10; + + if (g_BeamSprite > -1 && g_HaloSprite > -1) { + TE_SetupBeamRingPoint(vec, 10.0, radius, g_BeamSprite, g_HaloSprite, 0, 15, 0.5, 5.0, 0.0, COLOR_GREY, 10, 0); + TE_SendToAll(); + TE_SetupBeamRingPoint(vec, 10.0, radius, g_BeamSprite, g_HaloSprite, 0, 10, 0.6, 10.0, 0.5, COLOR_GREEN, 10, 0); + TE_SendToAll(); + } + + GetClientEyePosition(target, vec); + EmitAmbientSound("buttons/button17.wav", vec, target, SNDLEVEL_RAIDSIREN); +} \ No newline at end of file diff --git a/scripting/include/hideandseek/hsents.inc b/scripting/include/hideandseek/hsents.inc new file mode 100644 index 0000000..962f13f --- /dev/null +++ b/scripting/include/hideandseek/hsents.inc @@ -0,0 +1,136 @@ +#define ENT_PROP_NAME "hsprop" +#define ENT_BLOCKER_NAME "hsblocker" +#define ENT_PORTAL_NAME "hsportal" +#define ENT_ENV_NAME "hsenv" +#define PORTAL_ENTER_SOUND "custom/xen_teleport.mp3" +#include + +stock void CheatCommand(int client, const char[] command, const char[] argument1) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", command, argument1); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} + +stock void EntFire(const char[] name, const char[] input) { + static char targetname[64]; + static char cmd[32]; + #if defined DEBUG_LOG_MAPSTART + PrintToServer("EntFire: %s \"%s\"", name, input); + #endif + int len = SplitString(input, " ", cmd, sizeof(cmd)); + if(len > -1) SetVariantString(input[len]); + + int hammerId = name[0] == '!' ? StringToInt(name[1]) : 0; + bool setTeam = StrEqual(cmd, "_setteam"); + for(int i = MaxClients + 1; i <= 4096; i++) { + if(IsValidEntity(i) && (IsValidEdict(i) || EntIndexToEntRef(i) != -1)) { + if(hammerId > 0) { + if(hammerId == Entity_GetHammerId(i)) { + if(setTeam) { + SDKHook(i, SDKHook_TraceAttackPost, Hook_OnAttackPost); + SetEntProp(i, Prop_Send, "m_iTeamNum", 0); + } else if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } else { + GetEntPropString(i, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(setTeam) { + SDKHook(i, SDKHook_TraceAttackPost, Hook_OnAttackPost); + SetEntProp(i, Prop_Send, "m_iTeamNum", 0); + } else if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + + } else { + GetEntityClassname(i, targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } + } + } + } +} + + +void SetupEntities(bool blockers = true, bool props = true, bool portals = true) { + #if defined DEBUG_BLOCKERS + if(mapConfig.hasSpawnpoint) { + PrecacheModel("survivors/survivor_teenangst.mdl", true); + int dummy = CreateDummy("models/survivors/survivor_teenangst.mdl", "idle", mapConfig.spawnpoint, NULL_VECTOR); + SetEntProp(dummy, Prop_Data, "m_nSolidType", 0); + SetEntProp(dummy, Prop_Send, "m_CollisionGroup", 0); + SetEntProp(dummy, Prop_Send, "movetype", MOVETYPE_NONE); + } + #endif + if(mapConfig.entities != null) { + PrintToServer("[H&S] Deploying %d custom entities (Set: %s) (blockers:%b props:%b portals:%b)", mapConfig.entities.Length, g_currentSet, blockers, props, portals); + for(int i = 0; i < mapConfig.entities.Length; i++) { + EntityConfig config; + mapConfig.entities.GetArray(i, config); + + if(config.model[0] != '\0') PrecacheModel(config.model); + + if(StrEqual(config.type, "env_physics_blocker")) { + if(blockers && CreateEnvBlockerScaled(config.type, config.origin, config.scale, isNavBlockersEnabled) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn blocker [type=%s] at (%.1f,%.1f, %.1f)", config.type, config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_relportal")) { + if(portals && CreatePortal(Portal_Relative, config.model, config.origin, config.offset, config.scale) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn rel portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_portal")) { + if(portals && CreatePortal(Portal_Teleport, config.model, config.origin, config.offset, config.scale) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "_portal_xen")) { + if(portals) { + if(CreatePortal(Portal_Teleport, config.model, config.origin, config.offset, config.scale) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + CreateParticle(PARTICLE_ELMOS, config.origin, NULL_VECTOR); // Pulsating + } + } else if(StrEqual(config.type, "_lantern")) { + int parent = CreateProp("prop_dynamic", config.model, config.origin, config.rotation); + if(parent == -1) { + PrintToServer("[H&S:WARN] Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]); + } else { + float pos[3]; + pos = config.origin; + pos[2] += 15.0; + int child = CreateDynamicLight(pos, config.rotation, GetColorInt(255, 255, 242), 80.0, 11); + if(child == -1) { + PrintToServer("[H&S] Failed to spawn light source for _lantern"); + } else { + SetParent(child, parent); + TeleportEntity(parent, config.origin, NULL_VECTOR, NULL_VECTOR); + } + } + } else if(StrEqual(config.type, "_dummy")) { + if(CreateDummy(config.model, "hitby_tankpunch", config.origin, config.rotation) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn dummy [model=%s] at (%.1f,%.1f, %.1f)", config.model, config.origin[0], config.origin[1], config.origin[2]); + } + }else if(props) { + if(CreateProp(config.type, config.model, config.origin, config.rotation) == -1) { + PrintToServer("[H&S:WARN] Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]); + } + } + } + + static char key[64]; + static char value[64]; + if(mapConfig.inputs != null) { + for(int i = 0; i < mapConfig.inputs.Length - 1; i += 2) { + mapConfig.inputs.GetString(i, key, sizeof(key)); + mapConfig.inputs.GetString(i + 1, value, sizeof(value)); + EntFire(key, value); + } + } + } +} + diff --git a/scripting/include/hideandseek/hsgame.inc b/scripting/include/hideandseek/hsgame.inc new file mode 100644 index 0000000..e1553dc --- /dev/null +++ b/scripting/include/hideandseek/hsgame.inc @@ -0,0 +1,248 @@ +static int mapChangeMsgTicks = 5; + + +int GetColorInt(int r, int g, int b) { + int color = r; + color += 256 * g; + color += 65536 * b; + return color; +} + +void Cleanup() { + EntFire("hsprop", "kill"); + EntFire("hsblocker", "kill"); + EntFire("hsportal", "kill"); + PeekCam.Destroy(); + +} + +GameState GetState() { + if(!isEnabled) return State_Unknown; + static char buffer[4]; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.CurrentStage", buffer, sizeof(buffer)); + int stage = -1; + if(StringToIntEx(buffer, stage) > 0) { + return view_as(stage); + } else { + return State_Unknown; + } +} + +int GetSlasher() { + if(!isEnabled) return -1; + static char buffer[8]; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.CurrentSlasher && \"GetPlayerUserId\" in g_ModeScript.MutationState.CurrentSlasher ? g_ModeScript.MutationState.CurrentSlasher.GetPlayerUserId() : -1", buffer, sizeof(buffer)); + int uid = StringToInt(buffer); + if(uid > 0) { + return GetClientOfUserId(uid); + } else { + PrintToServer("[H&S] Could not find real slasher, falling back to manual check"); + return FindSlasher(); + } +} + +int FindSlasher() { + char buf[16]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + int entity = GetPlayerWeaponSlot(i, 1); + if(entity > -1 && GetEntityClassname(entity, buf, sizeof(buf)) && StrEqual(buf, "melee")) { + GetEntPropString(entity, Prop_Data, "m_strMapSetScriptName", buf, sizeof(buf)); + if(StrEqual(buf, "fireaxe")) { + return i; + } + } + } + } + return -1; +} + +void SetSlasher(int client, bool ignoreBalance = false) { + if(ignoreBalance) { + ignoreSeekerBalance = true; + } + GameState state = GetState(); + char buf[256]; + ArrayList hiders = new ArrayList(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + for(int s = 0; s < 6; s++) { + int ent = GetPlayerWeaponSlot(i, s); + if(ent > 0) AcceptEntityInput(ent, "Kill"); + } + if(i != client) { + hiders.Push(i); + if(state == State_Hunting) + CheatCommand(i, "give", "pistol_magnum"); + else + CheatCommand(i, "give", "knife"); + } + } + } + int defibHolder = hiders.Get(GetRandomInt(0, hiders.Length - 1)); + CheatCommand(defibHolder, "give", "defibrillator"); + Format(buf, sizeof(buf), "g_ModeScript.MutationState.CurrentSlasher = GetPlayerFromUserID(%d); g_ModeScript.GiveSeekerItem(GetPlayerFromUserID(%d))", GetClientUserId(client), GetClientUserId(client)); + L4D2_ExecVScriptCode(buf); + currentSeeker = client; + CheatCommand(client, "give", "fireaxe"); + CheatCommand(client, "give", "adrenaline"); + delete hiders; +} + +int GetTick() { + if(!isEnabled) return -1; + static char buffer[4]; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.StateTick", buffer, sizeof(buffer)); + int value = -1; + if(StringToIntEx(buffer, value) > 0) { + return value; + } else { + return -1; + } +} + +void SetTick(int tick) { + static char buf[64]; + Format(buf, sizeof(buf), "g_ModeScript.MutationState.StateTick = %d", tick); + L4D2_ExecVScriptCode(buf); +} + + +int GetMapTime() { + static char mapTime[16]; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.MapTime", mapTime, sizeof(mapTime)); + return StringToInt(mapTime); +} + +void SetMapTime(int seconds) { + static char buf[64]; + Format(buf, sizeof(buf), "g_ModeScript.MutationState.MapTime = %d", seconds); + L4D2_ExecVScriptCode(buf); +} + +Action Timer_ChangeMap(Handle h) { + PrintToChatAll("Changing map to %s in %d seconds", nextRoundMap, mapChangeMsgTicks); + if(mapChangeMsgTicks-- == 0) { + ForceChangeLevel(nextRoundMap, "H&SMapSelect"); + nextRoundMap[0] = '\0'; + return Plugin_Stop; + } + return Plugin_Continue; +} + +void ChangeMap(const char map[64], int time = 5) { + strcopy(nextRoundMap, sizeof(nextRoundMap), map); + mapChangeMsgTicks = time; + CreateTimer(1.0, Timer_ChangeMap, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); +} + +bool GetSpawnPosition(float pos[3], bool includePlayers = true) { + if(includePlayers) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + GetClientAbsOrigin(i, pos); + return true; + } + } + } + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "info_player_start")) != INVALID_ENT_REFERENCE) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + return true; + } + return false; +} + +bool SetState(GameState state) { + if(!isEnabled) return false; + static char buffer[64]; + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.CurrentStage = %d", view_as(state)); + return L4D2_ExecVScriptCode(buffer); +} + +void JoinGame(int target) { + float tpLoc[3]; + GetSpawnPosition(tpLoc); + ChangeClientTeam(target, 2); + L4D_RespawnPlayer(target); + TeleportEntity(target, tpLoc, NULL_VECTOR, NULL_VECTOR); + isPendingPlay[target] = false; + +} + +bool IsGameSoloOrPlayersLoading() { + int connecting, ingame; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i)) { + if(IsClientInGame(i)) + ingame++; + else + connecting++; + } + } + return connecting > 0 || ingame == 1; +} + +//cm_NoSurvivorBots +bool SetBotsEnabled(bool value) { + static char buffer[64]; + if(value) + Format(buffer, sizeof(buffer), "g_ModeScript.MutationOptions.cm_NoSurvivorBots = true"); + else + Format(buffer, sizeof(buffer), "g_ModeScript.MutationOptions.cm_NoSurvivorBots = false"); + return L4D2_ExecVScriptCode(buffer); +} + +bool IsBotsEnabled() { + static char result[8]; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.cm_NoSurvivorBots", result, sizeof(result)); + return StrEqual(result, "true", false); +} + +stock void GetHorizontalPositionFromClient(int client, float units, float finalPosition[3]) { + float pos[3], ang[3]; + GetClientEyeAngles(client, ang); + GetClientAbsOrigin(client, pos); + + float theta = DegToRad(ang[1]); + pos[0] += units * Cosine(theta); + pos[1] += units * Sine(theta); + finalPosition = pos; +} + +stock void GetAnglesLookAt(int iClient, int iTarget, float fFinalPos[3]) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + + GetEntPropVector(iClient, Prop_Send, "m_vecOrigin", fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + // TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} +stock void AddInFrontOf(float fVecOrigin[3], float fVecAngle[3], float fUnits, float fOutPut[3]) +{ + float fVecView[3]; GetViewVector(fVecAngle, fVecView); + + fOutPut[0] = fVecView[0] * fUnits + fVecOrigin[0]; + fOutPut[1] = fVecView[1] * fUnits + fVecOrigin[1]; + fOutPut[2] = fVecView[2] * fUnits + fVecOrigin[2]; +} +stock void GetViewVector(float fVecAngle[3], float fOutPut[3]) +{ + fOutPut[0] = Cosine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[1] = Sine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[2] = -Sine(fVecAngle[0] / (180 / FLOAT_PI)); +} + +stock float Get2DVectorDistance(const float a[3], const float b[3]) { + // sqrt((x-y)^2) + return SquareRoot(Pow(a[0] - b[0], 2.0) + Pow(a[1] - b[1], 2.0)); +} \ No newline at end of file diff --git a/scripting/include/json.inc b/scripting/include/json.inc new file mode 100644 index 0000000..a3ace6e --- /dev/null +++ b/scripting/include/json.inc @@ -0,0 +1,813 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_included + #endinput +#endif +#define _json_included + +#include +#include +#include +#include +#include +#include +#include + +/** + * Calculates the buffer size required to store an encoded JSON instance. + * + * @param obj Object to encode. + * @param options Bitwise combination of `JSON_ENCODE_*` options. + * @param depth The current depth of the encoder. + * @return The required buffer size. + */ +stock int json_encode_size(JSON_Object obj, int options = JSON_NONE, int depth = 0) +{ + bool pretty_print = (options & JSON_ENCODE_PRETTY) != 0; + + bool is_array = obj.IsArray; + + int size = 1; // for opening bracket + + // used in key iterator + int json_size = obj.Length; + JSON_Object child = null; + bool is_empty = true; + int str_length = 0; + + int key_length = 0; + for (int i = 0; i < json_size; i += 1) { + key_length = is_array ? JSON_INT_BUFFER_SIZE : obj.GetKeySize(i); + char[] key = new char[key_length]; + + if (is_array) { + IntToString(i, key, key_length); + } else { + obj.GetKey(i, key, key_length); + } + + // skip keys that are marked as hidden + if (obj.GetHidden(key)) { + continue; + } + + JSONCellType type = obj.GetType(key); + // skip keys of unknown type + if (type == JSON_Type_Invalid) { + continue; + } + + if (pretty_print) { + size += strlen(JSON_PP_NEWLINE); + size += (depth + 1) * strlen(JSON_PP_INDENT); + } + + if (! is_array) { + // add the size of the key and + 1 for : + size += json_cell_string_size(key) + 1; + + if (pretty_print) { + size += strlen(JSON_PP_AFTER_COLON); + } + } + + switch (type) { + case JSON_Type_String: { + str_length = obj.GetSize(key); + char[] value = new char[str_length]; + obj.GetString(key, value, str_length); + + size += json_cell_string_size(value); + } + case JSON_Type_Int: { + size += JSON_INT_BUFFER_SIZE; + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + size += JSON_INT64_BUFFER_SIZE; + } + #endif + case JSON_Type_Float: { + size += JSON_FLOAT_BUFFER_SIZE; + } + case JSON_Type_Bool: { + size += JSON_BOOL_BUFFER_SIZE; + } + case JSON_Type_Object: { + child = obj.GetObject(key); + size += child != null ? json_encode_size(child, options, depth + 1) : JSON_NULL_BUFFER_SIZE; + } + } + + // increment for comma + size += 1; + + is_empty = false; + } + + if (! is_empty) { + // remove the final comma + size -= 1; + + if (pretty_print) { + size += strlen(JSON_PP_NEWLINE); + size += depth * strlen(JSON_PP_INDENT); + } + } + + size += 2; // closing bracket + NULL + + return size; +} + +/** + * Encodes a JSON instance into its string representation. + * + * @param obj Object to encode. + * @param output String buffer to store output. + * @param max_size Maximum size of string buffer. + * @param options Bitwise combination of `JSON_ENCODE_*` options. + * @param depth The current depth of the encoder. + */ +stock void json_encode( + JSON_Object obj, + char[] output, + int max_size, + int options = JSON_NONE, + int depth = 0 +) +{ + bool pretty_print = (options & JSON_ENCODE_PRETTY) != 0; + + bool is_array = obj.IsArray; + strcopy(output, max_size, is_array ? "[" : "{"); + + // used in key iterator + int json_size = obj.Length; + int builder_size = 0; + int str_length = 1; + JSON_Object child = null; + int cell_length = 0; + bool is_empty = true; + + int key_length = 0; + for (int i = 0; i < json_size; i += 1) { + key_length = is_array ? JSON_INT_BUFFER_SIZE : obj.GetKeySize(i); + char[] key = new char[key_length]; + + if (is_array) { + IntToString(i, key, key_length); + } else { + obj.GetKey(i, key, key_length); + } + + // skip keys that are marked as hidden + if (obj.GetHidden(key)) { + continue; + } + + JSONCellType type = obj.GetType(key); + // skip keys of unknown type + if (type == JSON_Type_Invalid) { + continue; + } + + // determine the length of the char[] needed to represent our cell data + cell_length = 0; + switch (type) { + case JSON_Type_String: { + str_length = obj.GetSize(key); + char[] value = new char[str_length]; + obj.GetString(key, value, str_length); + + cell_length = json_cell_string_size(value); + } + case JSON_Type_Int: { + cell_length = JSON_INT_BUFFER_SIZE; + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + cell_length = JSON_INT64_BUFFER_SIZE; + } + #endif + case JSON_Type_Float: { + cell_length = JSON_FLOAT_BUFFER_SIZE; + } + case JSON_Type_Bool: { + cell_length = JSON_BOOL_BUFFER_SIZE; + } + case JSON_Type_Object: { + child = obj.GetObject(key); + cell_length = child != null ? max_size : JSON_NULL_BUFFER_SIZE; + } + } + + // fit the contents into the cell + char[] cell = new char[cell_length]; + switch (type) { + case JSON_Type_String: { + char[] value = new char[str_length]; + obj.GetString(key, value, str_length); + json_cell_string(value, cell, cell_length); + } + case JSON_Type_Int: { + int value = obj.GetInt(key); + IntToString(value, cell, cell_length); + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + int value[2]; + obj.GetInt64(key, value); + Int64ToString(value, cell, cell_length); + } + #endif + case JSON_Type_Float: { + float value = obj.GetFloat(key); + FloatToString(value, cell, cell_length); + + // trim trailing 0s from float output up until decimal point + int last_char = strlen(cell) - 1; + while (cell[last_char] == '0' && cell[last_char - 1] != '.') { + cell[last_char--] = '\0'; + } + } + case JSON_Type_Bool: { + bool value = obj.GetBool(key); + strcopy(cell, cell_length, value ? "true" : "false"); + } + case JSON_Type_Object: { + if (child != null) { + json_encode(child, cell, cell_length, options, depth + 1); + } else { + strcopy(cell, cell_length, "null"); + } + } + } + + // make the builder fit our key:value + // use previously determined cell length and + 1 for , + builder_size = cell_length + 1; + if (! is_array) { + // get the length of the key and + 1 for : + builder_size += json_cell_string_size(key) + 1; + + if (pretty_print) { + builder_size += strlen(JSON_PP_AFTER_COLON); + } + } + + char[] builder = new char[builder_size]; + strcopy(builder, builder_size, ""); + + // add the key if we're working with an object + if (! is_array) { + json_cell_string(key, builder, builder_size); + StrCat(builder, builder_size, ":"); + + if (pretty_print) { + StrCat(builder, builder_size, JSON_PP_AFTER_COLON); + } + } + + // add the value and a trailing comma + StrCat(builder, builder_size, cell); + StrCat(builder, builder_size, ","); + + // prepare pretty printing then send builder to output afterwards + if (pretty_print) { + StrCat(output, max_size, JSON_PP_NEWLINE); + + for (int j = 0; j < depth + 1; j += 1) { + StrCat(output, max_size, JSON_PP_INDENT); + } + } + + StrCat(output, max_size, builder); + + is_empty = false; + } + + if (! is_empty) { + // remove the final comma + output[strlen(output) - 1] = '\0'; + + if (pretty_print) { + StrCat(output, max_size, JSON_PP_NEWLINE); + + for (int j = 0; j < depth; j += 1) { + StrCat(output, max_size, JSON_PP_INDENT); + } + } + } + + // append closing bracket + StrCat(output, max_size, is_array ? "]" : "}"); +} + +/** + * Decodes a JSON string into a JSON instance. + * + * @param buffer Buffer to decode. + * @param options Bitwise combination of `JSON_DECODE_*` options. + * @param pos Current position of the decoder as bytes + * offset into the buffer. + * @param depth Current nested depth of the decoder. + * @return JSON instance or null if decoding failed becase + * the buffer didn't contain valid JSON. + * @error If the buffer does not contain valid JSON, + * an error will be thrown. + */ +stock JSON_Object json_decode( + const char[] buffer, + int options = JSON_NONE, + int &pos = 0, + int depth = 0 +) +{ + int length = strlen(buffer); + // skip preceding whitespace + if (! json_skip_whitespace(buffer, length, pos)) { + json_set_last_error("buffer ended early at position %d", pos); + + return null; + } + + bool is_array = false; + JSON_Array arr = null; + JSON_Object obj = null; + if (buffer[pos] == '{') { + is_array = false; + obj = new JSON_Object(); + } else if (buffer[pos] == '[') { + is_array = true; + arr = new JSON_Array(); + } else { + json_set_last_error("no object or array found at position %d", pos); + + return null; + } + + bool allow_single_quotes = (options & JSON_DECODE_SINGLE_QUOTES) > 0; + + bool empty_checked = false; + + // while we haven't reached the end of our structure + while ( + (! is_array && buffer[pos] != '}') + || (is_array && buffer[pos] != ']') + ) { + // pos is either an opening structure or comma, so increment past it + pos += 1; + + // skip any whitespace preceding the element + if (! json_skip_whitespace(buffer, length, pos)) { + json_set_last_error("buffer ended early at position %d", pos); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + // if we haven't checked for empty yet and we are at the end + // of an object or array, we can stop here (empty structure) + if (! empty_checked) { + if ( + (! is_array && buffer[pos] == '}') + || (is_array && buffer[pos] == ']') + ) { + break; + } + + empty_checked = true; + } + + int key_length = 1; + if (! is_array) { + // if dealing with an object, look for the key and determine length + if (! json_is_string(buffer[pos], allow_single_quotes)) { + json_set_last_error("expected key string at position %d", pos); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + key_length = json_extract_string_size( + buffer, + length, + pos, + is_array + ); + } + + char[] key = new char[key_length]; + + if (! is_array) { + // extract the key from the buffer + json_extract_string(buffer, length, pos, key, key_length, is_array); + + // skip any whitespace following the key + if (! json_skip_whitespace(buffer, length, pos)) { + json_set_last_error("buffer ended early at position %d", pos); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + // ensure that we find a colon + if (buffer[pos++] != ':') { + json_set_last_error( + "expected colon after key at position %d", + pos + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + // skip any whitespace following the colon + if (! json_skip_whitespace(buffer, length, pos)) { + json_set_last_error("buffer ended early at position %d", pos); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + } + + int cell_length = 1; + JSONCellType cell_type = JSON_Type_Invalid; + if (buffer[pos] == '{' || buffer[pos] == '[') { + cell_type = JSON_Type_Object; + } else if (json_is_string(buffer[pos], allow_single_quotes)) { + cell_type = JSON_Type_String; + cell_length = json_extract_string_size( + buffer, + length, + pos, + is_array + ); + } else { + // in this particular instance, we use JSON_Type_Invalid to + // represent any type that isn't an object or string + cell_length = json_extract_until_end_size( + buffer, + length, + pos, + is_array + ); + } + + if (! is_array && obj.HasKey(key)) { + obj.Remove(key); + } + + char[] cell = new char[cell_length]; + switch (cell_type) { + case JSON_Type_Object: { + // if we are dealing with an object or array, decode recursively + JSON_Object value = json_decode( + buffer, + options, + pos, + depth + 1 + ); + + // decoding failed, error will be logged in json_decode + if (value == null) { + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + if (is_array) { + arr.PushObject(value); + } else { + obj.SetObject(key, value); + } + } + case JSON_Type_String: { + // if we are dealing with a string, attempt to extract it + if (! json_extract_string( + buffer, + length, + pos, + cell, + cell_length, + is_array + )) { + json_set_last_error( + "couldn't extract string at position %d", + pos + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + if (is_array) { + arr.PushString(cell); + } else { + obj.SetString(key, cell); + } + } + case JSON_Type_Invalid: { + if (! json_extract_until_end( + buffer, + length, + pos, + cell, + cell_length, + is_array + )) { + json_set_last_error( + "couldn't extract until end at position %d", + pos + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + if (strlen(cell) == 0) { + json_set_last_error( + "empty cell encountered at position %d", + pos + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + if (json_is_int(cell)) { + int value = StringToInt(cell); + #if SM_INT64_SUPPORTED + if (json_is_int64(cell, value)) { + int values[2]; + StringToInt64(cell, values); + + if (is_array) { + arr.PushInt64(values); + } else { + obj.SetInt64(key, values); + } + } else { + if (is_array) { + arr.PushInt(value); + } else { + obj.SetInt(key, value); + } + } + #else + if (is_array) { + arr.PushInt(value); + } else { + obj.SetInt(key, value); + } + #endif + } else if (json_is_float(cell)) { + float value = StringToFloat(cell); + if (is_array) { + arr.PushFloat(value); + } else { + obj.SetFloat(key, value); + } + } else if (StrEqual(cell, "true") || StrEqual(cell, "false")) { + bool value = StrEqual(cell, "true"); + if (is_array) { + arr.PushBool(value); + } else { + obj.SetBool(key, value); + } + } else if (StrEqual(cell, "null")) { + if (is_array) { + arr.PushObject(null); + } else { + obj.SetObject(key, null); + } + } else { + json_set_last_error( + "unknown type encountered at position %d: %s", + pos, + cell + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + } + } + + if (! json_skip_whitespace(buffer, length, pos)) { + json_set_last_error("buffer ended early at position %d", pos); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + } + + // skip remaining whitespace and ensure we're at the end of the buffer + pos += 1; + if (json_skip_whitespace(buffer, length, pos) && depth == 0) { + json_set_last_error( + "unexpected data after structure end at position %d", + pos + ); + json_cleanup_and_delete(obj); + json_cleanup_and_delete(arr); + + return null; + } + + return is_array ? view_as(arr) : obj; +} + +/** + * Encodes the object with the options provided and writes + * the output to the file at the path specified. + * + * @param obj Object to encode/write to file. + * @param path Path of file to write to. + * @param options Options to pass to `json_encode`. + * @return True on success, false otherwise. + */ +stock bool json_write_to_file( + JSON_Object obj, + const char[] path, + int options = JSON_NONE +) +{ + File f = OpenFile(path, "wb"); + if (f == null) { + return false; + } + + int size = json_encode_size(obj, options); + char[] buffer = new char[size]; + json_encode(obj, buffer, size, options); + + bool success = f.WriteString(buffer, false); + delete f; + + return success; +} + +/** + * Reads and decodes the contents of a JSON file. + * + * @param path Path of file to read from. + * @param options Options to pass to `json_decode`. + * @return The decoded object on success, null otherwise. + */ +stock JSON_Object json_read_from_file(const char[] path, int options = JSON_NONE) +{ + File f = OpenFile(path, "rb"); + if (f == null) { + return null; + } + + f.Seek(0, SEEK_END); + int size = f.Position + 1; + char[] buffer = new char[size]; + + f.Seek(0, SEEK_SET); + f.ReadString(buffer, size); + delete f; + + return json_decode(buffer, options); +} + +/** + * Creates a shallow copy of the specified object. + * + * @param obj Object to copy. + * @return A shallow copy of the specified object. + */ +stock JSON_Object json_copy_shallow(JSON_Object obj) +{ + bool isArray = obj.IsArray; + JSON_Object result = isArray + ? view_as(new JSON_Array()) + : new JSON_Object(); + + if (isArray) { + view_as(result).Concat(view_as(obj)); + } else { + result.Merge(obj); + } + + return result; +} + +/** + * Creates a deep copy of the specified object. + * + * @param obj Object to copy. + * @return A deep copy of the specified object. + */ +stock JSON_Object json_copy_deep(JSON_Object obj) +{ + JSON_Object result = json_copy_shallow(obj); + + int length = obj.Length; + int key_length = 0; + for (int i = 0; i < length; i += 1) { + key_length = obj.GetKeySize(i); + char[] key = new char[key_length]; + obj.GetKey(i, key, key_length); + + // only deep copy objects + JSONCellType type = obj.GetType(key); + if (type != JSON_Type_Object) { + continue; + } + + JSON_Object value = obj.GetObject(key); + result.SetObject(key, value != null ? json_copy_deep(value) : null); + } + + return result; +} + +/** + * Recursively cleans up the instance and any instances stored within. + * + * @param obj Object to clean up. + */ +stock void json_cleanup(JSON_Object obj) +{ + if (obj == null) { + return; + } + + int length = obj.Length; + int key_length = 0; + for (int i = 0; i < length; i += 1) { + key_length = obj.GetKeySize(i); + char[] key = new char[key_length]; + obj.GetKey(i, key, key_length); + + // only clean up objects + JSONCellType type = obj.GetType(key); + if (type != JSON_Type_Object) { + continue; + } + + JSON_Object value = obj.GetObject(key); + if (value != null) { + json_cleanup(value); + } + } + + obj.Super.Cleanup(); +} + +/** + * Cleans up an object and sets the passed variable to null. + * + * @param obj Object to clean up. + */ +stock void json_cleanup_and_delete(JSON_Object &obj) +{ + json_cleanup(obj); + obj = null; +} diff --git a/scripting/include/json/array.inc b/scripting/include/json/array.inc new file mode 100644 index 0000000..5f41162 --- /dev/null +++ b/scripting/include/json/array.inc @@ -0,0 +1,955 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_array_included + #endinput +#endif +#define _json_array_included + +#include +#include +#include +#include + +methodmap JSON_Array < JSON_Object +{ + /** + * @section Helpers + */ + + /** + * Views the instance as its superclass to access overridden methods. + */ + property JSON_Object Super + { + public get() + { + return view_as(this); + } + } + + /** + * The enforced type of the array. + */ + property JSONCellType Type + { + public get() + { + return view_as(this.Meta.GetOptionalValue( + JSON_ENFORCE_TYPE_KEY, + JSON_Type_Invalid + )); + } + + public set(JSONCellType value) + { + if (value == JSON_Type_Invalid) { + this.Meta.Remove(JSON_ENFORCE_TYPE_KEY); + } else { + this.Meta.SetValue(JSON_ENFORCE_TYPE_KEY, value); + } + } + } + + /** + * Checks whether the array accepts the type provided. + * + * @param type Type to check for enforcement. + * @return True if the type can be used, false otherwise. + */ + public bool CanUseType(JSONCellType type) + { + return this.Type == JSON_Type_Invalid || this.Type == type; + } + + /** + * Checks whether the object has an index. + * + * @param index Index to check existence of. + * @return True if the index exists, false otherwise. + */ + public bool HasKey(int index) + { + return index >= 0 && index < this.Length; + } + + /** + * @section Metadata Getters + */ + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * @internal + * + * @see MetaStringMap.GetMeta + */ + public any GetMeta(int index, JSONMetaInfo meta, any default_value) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return default_value; + } + + return this.Super.GetMeta(key, meta, default_value); + } + + /** + * Gets the cell type stored at an index. + * + * @param index Index to get value type for. + * @return Value type for index provided, + * or JSON_Type_Invalid if it does not exist. + */ + public JSONCellType GetType(int index) + { + return view_as( + this.GetMeta(index, JSON_Meta_Type, JSON_Type_Invalid) + ); + } + + /** + * Gets the length of the string stored at an index. + * + * @param index Index to get string length for. + * @return Length of string at index provided, + * or -1 if it is not a string/does not exist. + */ + public int GetSize(int index) + { + return view_as(this.GetMeta(index, JSON_Meta_Size, -1)); + } + + /** + * Gets whether the index should be hidden from encoding. + * + * @param index Index to get hidden state for. + * @return Whether or not the index should be hidden. + */ + public bool GetHidden(int index) + { + return view_as(this.GetMeta(index, JSON_Meta_Hidden, false)); + } + + /** + * @section Metadata Setters + */ + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * @internal + * + * @see JSON_Object.SetMeta + */ + public bool SetMeta(int index, JSONMetaInfo meta, any value) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetMeta(key, meta, value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * @internal + * + * @see JSON_Object.RemoveMeta + */ + public bool RemoveMeta(int index, JSONMetaInfo meta) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.RemoveMeta(key, meta); + } + + /** + * Sets whether the index should be hidden from encoding. + * + * @param index Index to set hidden state for. + * @param hidden Whether or not the index should be hidden. + * @return True on success, false otherwise. + */ + public bool SetHidden(int index, bool hidden) + { + return this.SetMeta(index, JSON_Meta_Hidden, hidden); + } + + /** + * @section Getters + */ + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetValue + */ + public bool GetValue(int index, any &value) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.GetValue(key, value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * @internal + * + * @see MetaStringMap.GetOptionalValue + */ + public any GetOptionalValue(int index, any default_value = -1) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.GetOptionalValue(key, default_value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetString + */ + public bool GetString(int index, char[] value, int max_size, int &size = 0) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.GetString(key, value, max_size, size); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetInt + */ + public int GetInt(int index, int default_value = -1) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return default_value; + } + + return this.Super.GetInt(key, default_value); + } + + #if SM_INT64_SUPPORTED + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.GetInt64 + */ + public bool GetInt64(int index, int value[2]) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.GetInt64(key, value); + } + #endif + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetFloat + */ + public float GetFloat(int index, float default_value = -1.0) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return default_value; + } + + return this.Super.GetFloat(key, default_value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetBool + */ + public bool GetBool(int index, bool default_value = false) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return default_value; + } + + return this.Super.GetBool(key, default_value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see MetaStringMap.GetObject + */ + public JSON_Object GetObject(int index, JSON_Object default_value = null) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return default_value; + } + + return this.Super.GetObject(key, default_value); + } + + /** + * @section Setters + */ + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetString + */ + public bool SetString(int index, const char[] value) + { + if (! this.CanUseType(JSON_Type_String)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetString(key, value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetInt + */ + public bool SetInt(int index, int value) + { + if (! this.CanUseType(JSON_Type_Int)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetInt(key, value); + } + + #if SM_INT64_SUPPORTED + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetInt64 + */ + public bool SetInt64(int index, int value[2]) + { + if (! this.CanUseType(JSON_Type_Int64)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetInt64(key, value); + } + #endif + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetFloat + */ + public bool SetFloat(int index, float value) + { + if (! this.CanUseType(JSON_Type_Float)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetFloat(key, value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetBool + */ + public bool SetBool(int index, bool value) + { + if (! this.CanUseType(JSON_Type_Bool)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetBool(key, value); + } + + /** + * Converts index to a string ('key') and calls the relevant Super method. + * + * @see JSON_Object.SetObject + */ + public bool SetObject(int index, JSON_Object value) + { + if (! this.CanUseType(JSON_Type_Object)) { + return false; + } + + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + return this.Super.SetObject(key, value); + } + + /** + * @section Pushers + */ + + /** + * Pushes a string to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushString(const char[] value) + { + int index = this.Length; + if (! this.SetString(index, value)) { + return -1; + } + + return index; + } + + /** + * Pushes an int to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushInt(int value) + { + int index = this.Length; + if (! this.SetInt(index, value)) { + return -1; + } + + return index; + } + + #if SM_INT64_SUPPORTED + /** + * Pushes an int64 to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushInt64(int value[2]) + { + int index = this.Length; + if (! this.SetInt64(index, value)) { + return -1; + } + + return index; + } + #endif + + /** + * Pushes a float to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushFloat(float value) + { + int index = this.Length; + if (! this.SetFloat(index, value)) { + return -1; + } + + return index; + } + + /** + * Pushes a bool to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushBool(bool value) + { + int index = this.Length; + if (! this.SetBool(index, value)) { + return -1; + } + + return index; + } + + /** + * Pushes a JSON object to the end of the array. + * + * @param value Value to push. + * @return The element's index on success, -1 otherwise. + */ + public int PushObject(JSON_Object value) + { + int index = this.Length; + if (! this.SetObject(index, value)) { + return -1; + } + + return index; + } + + /** + * @section Search Helpers + */ + + /** + * Finds the index of a value in the array. + * + * @param value Value to search for. + * @return The index of the value if it is found, -1 otherwise. + */ + public int IndexOf(any value) + { + any current; + int length = this.Length; + for (int i = 0; i < length; i += 1) { + if (this.GetValue(i, current) && value == current) { + return i; + } + } + + return -1; + } + + /** + * Finds the index of a string in the array. + * + * @param value String to search for. + * @return The index of the string if it is found, -1 otherwise. + */ + public int IndexOfString(const char[] value) + { + int length = this.Length; + for (int i = 0; i < length; i += 1) { + if (this.GetType(i) != JSON_Type_String) { + continue; + } + + int current_size = this.GetSize(i); + char[] current = new char[current_size]; + this.GetString(i, current, current_size); + if (StrEqual(value, current)) { + return i; + } + } + + return -1; + } + + /** + * Determines whether the array contains a value. + * + * @param value Value to search for. + * @return True if the value is found, false otherwise. + */ + public bool Contains(any value) + { + return this.IndexOf(value) != -1; + } + + /** + * Determines whether the array contains a string. + * + * @param value String to search for. + * @return True if the string is found, false otherwise. + */ + public bool ContainsString(const char[] value) + { + return this.IndexOfString(value) != -1; + } + + /** + * @section Misc + */ + + /** + * Removes an index and its related meta-keys from the array, + * and shifts down all following element indices. + * + * @param key Key to remove. + * @return True on success, false if the value was never set. + */ + public bool Remove(int index) + { + char key[JSON_INT_BUFFER_SIZE]; + if (! this.GetKey(index, key, sizeof(key))) { + return false; + } + + int length = this.Length; + + // remove existing value at index + if (! this.Super.Remove(key)) { + return false; + } + + // shift all following elements down + char current_key[JSON_INT_BUFFER_SIZE]; + for (int oldIndex = index + 1; oldIndex < length; oldIndex += 1) { + int newIndex = oldIndex - 1; + JSONCellType type = this.GetType(oldIndex); + + switch (type) { + case JSON_Type_String: { + int str_length = this.GetSize(oldIndex); + char[] str_value = new char[str_length]; + + this.GetString(oldIndex, str_value, str_length); + this.SetString(newIndex, str_value); + } + case JSON_Type_Int: { + this.SetInt(newIndex, this.GetInt(oldIndex)); + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + int value[2]; + this.GetInt64(oldIndex, value); + this.SetInt64(newIndex, value); + } + #endif + case JSON_Type_Float: { + this.SetFloat(newIndex, this.GetFloat(oldIndex)); + } + case JSON_Type_Bool: { + this.SetBool(newIndex, this.GetBool(oldIndex)); + } + case JSON_Type_Object: { + this.SetObject(newIndex, this.GetObject(oldIndex)); + } + } + + this.SetHidden(newIndex, this.GetHidden(oldIndex)); + + if (this.GetKey( + oldIndex, + current_key, + sizeof(current_key) + )) { + this.Super.Remove(current_key); + } + } + + return true; + } + + /** + * Concatenates the entries from the specified array + * on to the end of this array. + * + * @param from Array to concat entries from. + * @return True on success, false otherwise. + * @error If the object being merged is an object or the + * arrays being merged don't have the same strict + * type set, an error will be thrown. + */ + public bool Concat(JSON_Array from) + { + if (! this.IsArray || ! from.IsArray) { + json_set_last_error("attempted to concat using object(s)"); + + return false; + } + + if (this.Type != from.Type) { + json_set_last_error( + "attempted to concat arrays with mismatched strict types" + ); + + return false; + } + + int current_length = this.Length; + int json_size = from.Length; + for (int i = 0; i < json_size; i += 1) { + JSONCellType type = from.GetType(i); + // skip keys of unknown type + if (type == JSON_Type_Invalid) { + continue; + } + + // push value onto array + switch (type) { + case JSON_Type_String: { + int length = from.GetSize(i); + char[] value = new char[length]; + from.GetString(i, value, length); + + this.PushString(value); + } + case JSON_Type_Int: { + this.PushInt(from.GetInt(i)); + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + int value[2]; + from.GetInt64(i, value); + this.PushInt64(value); + } + #endif + case JSON_Type_Float: { + this.PushFloat(from.GetFloat(i)); + } + case JSON_Type_Bool: { + this.PushBool(from.GetBool(i)); + } + case JSON_Type_Object: { + this.PushObject(from.GetObject(i)); + } + } + + this.SetHidden(current_length + i, from.GetHidden(i)); + } + + return true; + } + + /** + * Typed Helpers + */ + + /** + * The length of the longest string in the array. + */ + property int MaxStringLength + { + public get() + { + int max = -1; + int current = -1; + int length = this.Length; + for (int i = 0; i < length; i += 1) { + if (this.GetType(i) != JSON_Type_String) { + continue; + } + + current = this.GetSize(i); + if (current > max) { + max = current; + } + } + + return max; + } + } + + /** + * Sets the array to enforce a specific type. + * This will fail if there are any existing elements + * in the array which are not of the same type. + * + * @param type Type to enforce. + * @return True if the type was enforced successfully, false otherwise. + */ + public bool EnforceType(JSONCellType type) + { + if (type == JSON_Type_Invalid) { + this.Type = type; + + return true; + } + + int length = this.Length; + for (int i = 0; i < length; i += 1) { + if (this.GetType(i) != type) { + return false; + } + } + + this.Type = type; + + return true; + } + + /** + * Imports a native array's values into the instance. + * + * @param type Type of native values. + * @param values Array of values. + * @param size Size of array. + * @return True on success, false otherwise. + */ + public bool ImportValues(JSONCellType type, any[] values, int size) + { + bool success = true; + for (int i = 0; i < size; i += 1) { + switch (type) { + case JSON_Type_Int: { + success = success && this.PushInt(values[i]) > -1; + } + case JSON_Type_Float: { + success = success && this.PushFloat(values[i]) > -1; + } + case JSON_Type_Bool: { + success = success && this.PushBool(values[i]) > -1; + } + case JSON_Type_Object: { + success = success && this.PushObject(values[i]) > -1; + } + } + } + + return success; + } + + /** + * Imports a native array's strings into the instance. + * + * @param strings Array of strings. + * @param size Size of array. + * @return True on success, false otherwise. + */ + public bool ImportStrings(const char[][] strings, int size) + { + bool success = true; + for (int i = 0; i < size; i += 1) { + success = success && this.PushString(strings[i]) > -1; + } + + return success; + } + + /** + * Exports the instance's values into a native array. + * + * @param values Array to export to. + * @param max_size Maximum size of array. + */ + public void ExportValues(any[] values, int max_size) + { + int length = this.Length; + if (length < max_size) { + max_size = length; + } + + for (int i = 0; i < max_size; i += 1) { + this.GetValue(i, values[i]); + } + } + + /** + * Exports the instance's strings into a native array. + * + * @param values Array to export to. + * @param max_size Maximum size of array. + * @param max_string_size Maximum size of array elements. + */ + public void ExportStrings( + char[][] values, + int max_size, + int max_string_size + ) { + int length = this.Length; + if (length < max_size) { + max_size = length; + } + + for (int i = 0; i < max_size; i += 1) { + this.GetString(i, values[i], max_string_size); + } + } + + /** + * json.inc Aliases + */ + + /** @see JSON_Object.ShallowCopy */ + public JSON_Array ShallowCopy() + { + return view_as(this.Super.ShallowCopy()); + } + + /** @see JSON_Object.DeepCopy */ + public JSON_Array DeepCopy() + { + return view_as(this.Super.DeepCopy()); + } + + /** + * @section Constructor + */ + + /** + * Creates a new JSON_Array. + * + * @param type The type to enforce for this array, or + * JSON_Type_Invalid for no enforced type. + * @return A new JSON_Array. + */ + public JSON_Array(JSONCellType type = JSON_Type_Invalid) + { + JSON_Array self = view_as(new JSON_Object()); + self.Meta.SetBool(JSON_ARRAY_KEY, true); + self.EnforceType(type); + + return self; + } +}; diff --git a/scripting/include/json/definitions.inc b/scripting/include/json/definitions.inc new file mode 100644 index 0000000..eba7b9c --- /dev/null +++ b/scripting/include/json/definitions.inc @@ -0,0 +1,180 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_definitions_included + #endinput +#endif +#define _json_definitions_included + +#include +#include + +#define SM_INT64_SUPPORTED SOURCEMOD_V_MAJOR >= 1 \ + && SOURCEMOD_V_MINOR >= 11 \ + && SOURCEMOD_V_REV >= 6861 + +/** + * @section Settings + */ + +/** Used when no options are desired. */ +#define JSON_NONE 0 + +/** + * @section json_encode settings + */ + +/** Should encoded output be pretty printed? */ +#define JSON_ENCODE_PRETTY 1 << 0 + +/** + * @section json_decode settings + */ + +/** Should single quote wrapped strings be accepted during decoding? */ +#define JSON_DECODE_SINGLE_QUOTES 1 << 0 + +/** + * @section json_merge settings + */ + +/** During merge, should existing keys be replaced if they exist in both objects? */ +#define JSON_MERGE_REPLACE 1 << 0 + +/** During merge, should existing objects be cleaned up if they exist in + * both objects? (only applies when JSON_MERGE_REPLACE is also set) */ +#define JSON_MERGE_CLEANUP 1 << 1 + +/** + * @section Pretty Print Constants + * + * Used to determine how pretty printed JSON should be formatted when encoded. + * You can modify these if you prefer your JSON formatted differently. + */ + +char JSON_PP_AFTER_COLON[32] = " "; +char JSON_PP_INDENT[32] = " "; +char JSON_PP_NEWLINE[32] = "\n"; + +/** + * @section Buffer Size Constants + */ + +/** The longest representable integer ("-2147483648") + NULL terminator */ +#define JSON_INT_BUFFER_SIZE 12 + +#if SM_INT64_SUPPORTED +/** The longest representable int64 ("-9223372036854775808") + NULL terminator */ +#define JSON_INT64_BUFFER_SIZE 21 +#endif + +/** You may need to change this if you are working with large floats. */ +#define JSON_FLOAT_BUFFER_SIZE 32 + +/** "true"|"false" + NULL terminator */ +#define JSON_BOOL_BUFFER_SIZE 6 + +/** "null" + NULL terminator */ +#define JSON_NULL_BUFFER_SIZE 5 + +/** + * @section Array/Object Constants + */ + +#define JSON_ARRAY_KEY "is_array" +#define JSON_ENFORCE_TYPE_KEY "enforce_type" + +/** + * Types of cells within a JSON object + */ +enum JSONCellType { + JSON_Type_Invalid = -1, + JSON_Type_String = 0, + JSON_Type_Int, + #if SM_INT64_SUPPORTED + JSON_Type_Int64, + #endif + JSON_Type_Float, + JSON_Type_Bool, + JSON_Type_Object +}; + +/** + * Types of metadata a JSON element can have + */ +enum JSONMetaInfo { + JSON_Meta_Type = 0, + JSON_Meta_Size, + JSON_Meta_Hidden, + JSON_Meta_Index +} + +/** + * An array of all possible meta info values. + */ +JSONMetaInfo JSON_ALL_METADATA[4] = { + JSON_Meta_Type, JSON_Meta_Size, JSON_Meta_Hidden, JSON_Meta_Index +}; + +/** + * Calculates the length required to store a meta key + * for a specified key/metainfo combination. + * @internal + * + * @param key + * @return The length required to store the meta key. + */ +stock int json_meta_key_length(const char[] key) +{ + // %s:%d + return strlen(key) + 1 + JSON_INT_BUFFER_SIZE; +} + +/** + * Formats the key/metainfo combination into a buffer. + * @internal + * + * @param output String buffer to store output. + * @param max_size Maximum size of string buffer. + * @param key Key to generate metakey for. + * @param meta Meta information to generate metakey for. + */ +stock void json_format_meta_key( + char[] output, + int max_size, + const char[] key, + JSONMetaInfo meta +) +{ + FormatEx(output, max_size, "k|%s:%d", key, view_as(meta)); +} diff --git a/scripting/include/json/helpers/decode.inc b/scripting/include/json/helpers/decode.inc new file mode 100644 index 0000000..c550de8 --- /dev/null +++ b/scripting/include/json/helpers/decode.inc @@ -0,0 +1,573 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_helpers_decode_included + #endinput +#endif +#define _json_helpers_decode_included + +#include +#include + +/** + * @section Determine Buffer Contents + */ + +/** + * Checks whether the character at the beginning of the buffer is whitespace. + * + * @param buffer String buffer of data. + * @return True if the first character in the buffer + * is whitespace, false otherwise. + */ +stock bool json_is_whitespace(const char[] buffer) +{ + return buffer[0] == ' ' + || buffer[0] == '\t' + || buffer[0] == '\r' + || buffer[0] == '\n'; +} + +/** + * Checks whether the character at the beginning + * of the buffer is the start of a string. + * + * @param buffer String buffer of data. + * @param allow_single_quotes Should strings using single quotes be accepted? + * @return True if the first character in the buffer + * is the start of a string, false otherwise. + */ +stock bool json_is_string(const char[] buffer, bool allow_single_quotes = false) +{ + return buffer[0] == '"' || (allow_single_quotes && buffer[0] == '\''); +} + +/** + * Checks whether the buffer provided contains an int. + * + * @param buffer String buffer of data. + * @return True if buffer contains an int, false otherwise. + */ +stock bool json_is_int(const char[] buffer) +{ + int length = strlen(buffer); + if (length == 0) { + return false; + } + + bool starts_with_zero = false; + bool has_digit_gt_zero = false; + + for (int i = 0; i < length; i += 1) { + // allow minus as first character only + if (i == 0 && buffer[i] == '-') { + continue; + } + + if (! IsCharNumeric(buffer[i])) { + return false; + } + + if (buffer[i] == '0') { + if (starts_with_zero) { + // detect repeating leading zeros + return false; + } else if (! has_digit_gt_zero) { + starts_with_zero = true; + } + } else if (starts_with_zero) { + // detect numbers with leading zero + return false; + } else { + has_digit_gt_zero = true; + } + } + + return true; +} + +#if SM_INT64_SUPPORTED +/** + * Checks whether the buffer provided contains an int64, assuming it has + * already been validated as an int and attempted to convert to an int32. + * + * @param buffer String buffer of data. + * @param value Converted int value to compare with. + * @return True if buffer contains an int64, false otherwise. + */ +stock bool json_is_int64(const char[] buffer, int value) +{ + if ( + (value == 0 && ! StrEqual(buffer, "0")) + || (value == -1 && ! StrEqual(buffer, "-1")) + ) { + // failed to produce output of validated int, must be 64bit + return true; + } + + if (buffer[0] != '-' && value < 0) { + // 32-bit unsigned positive int which is incorrectly + // interpreted as a negative signed int by sourcepawn + return true; + } + + if (buffer[0] == '-' && value > 0) { + return true; + } + + return false; +} +#endif + +/** + * Checks whether the buffer provided contains a float. + * + * @param buffer String buffer of data. + * @return True if buffer contains a float, false otherwise. + */ +stock bool json_is_float(const char[] buffer) +{ + int length = strlen(buffer); + if (length == 0) { + return false; + } + + bool starts_with_zero = false; + bool has_digit_gt_zero = false; + bool after_decimal = false; + bool has_digit_after_decimal = false; + bool after_exponent = false; + bool has_digit_after_exponent = false; + + for (int i = 0; i < length; i += 1) { + // allow minus as first character only + if (i == 0 && buffer[i] == '-') { + continue; + } + + // if we haven't encountered a decimal or exponent yet + if (! after_decimal && ! after_exponent) { + if (buffer[i] == '.') { + // if we encounter a decimal before any digits + if (! starts_with_zero && ! has_digit_gt_zero) { + return false; + } + + after_decimal = true; + } else if (buffer[i] == 'e' || buffer[i] == 'E') { + // if we encounter an exponent before any digits + if (! starts_with_zero && ! has_digit_gt_zero) { + return false; + } + + after_exponent = true; + } else if (IsCharNumeric(buffer[i])) { + if (buffer[i] == '0') { + if (starts_with_zero) { + // detect repeating leading zeros + return false; + } else if (! has_digit_gt_zero) { + starts_with_zero = true; + } + } else { + if (starts_with_zero) { + // detect numbers with leading zero + return false; + } + + has_digit_gt_zero = true; + } + } else { + return false; + } + } else if (after_decimal && ! after_exponent) { + // after decimal has been encountered, allow any numerics + if (IsCharNumeric(buffer[i])) { + has_digit_after_decimal = true; + } else if (buffer[i] == 'e' || buffer[i] == 'E') { + if (! has_digit_after_decimal) { + // detect exponents directly after decimal + return false; + } + + after_exponent = true; + } else { + return false; + } + } else if (after_exponent) { + if ( + (buffer[i] == '+' || buffer[i] == '-') + && (buffer[i - 1] == 'e' || buffer[i - 1] == 'E') + ) { + // allow + or - directly after exponent + continue; + } else if (IsCharNumeric(buffer[i])) { + has_digit_after_exponent = true; + } else { + return false; + } + } + } + + // if we have a decimal, there should be digit(s) after it + if (after_decimal && ! has_digit_after_decimal) { + return false; + } + + // if we have an exponent, there should be digit(s) after it + if (after_exponent && ! has_digit_after_exponent) { + return false; + } + + // we should have reached an exponent, decimal, or both + // otherwise this number can be handled by the int parser + return after_decimal || after_exponent; +} + +/** + * Checks whether the character at the beginning of the buffer + * is considered a valid 'end point' for an element, + * such as a colon (indicating the end of a key), + * a comma (indicating the end of an element), + * or the end of an object or array. + * + * @param buffer String buffer of data. + * @param is_array Whether the decoder is processing an array. + * @return True if the first character in the buffer + * is a valid element end point, false otherwise. + */ +stock bool json_is_at_end(const char[] buffer, bool is_array) +{ + return buffer[0] == ',' + || (! is_array && (buffer[0] == ':' || buffer[0] == '}')) + || (is_array && buffer[0] == ']'); +} + +/** + * @section Extract Contents from Buffer + */ + +/** + * Moves the position until it reaches a non-whitespace + * character or the end of the buffer's maximum size. + * + * @param buffer String buffer of data. + * @param max_size Maximum size of string buffer. + * @param pos Position to increment. + * @return True if pos has not reached the end + * of the buffer, false otherwise. + */ +stock bool json_skip_whitespace(const char[] buffer, int max_size, int &pos) +{ + while (json_is_whitespace(buffer[pos]) && pos < max_size) { + pos += 1; + } + + return pos < max_size; +} + +/** + * Calculates the size of the buffer required to store the next + * JSON cell stored in the provided buffer at the provided position. + * This function is quite forgiving of malformed input and shouldn't be + * relied upon as proof that the input is valid. + * + * @param buffer String buffer of data. + * @param max_size Maximum size of string buffer. + * @param pos Position to increment. + * @param is_array Whether the decoder is processing an array. + * @return The size of the buffer required to store the cell. + */ +stock int json_extract_until_end_size( + const char[] buffer, + int max_size, + int pos, + bool is_array +) +{ + int length = 1; // for NULL terminator + + // while we haven't hit whitespace, an end point or the end of the buffer + while ( + ! json_is_whitespace(buffer[pos]) + && ! json_is_at_end(buffer[pos], is_array) + && pos < max_size + ) { + pos += 1; + length += 1; + } + + return length; +} + +/** + * Extracts a JSON cell from the buffer until a valid end point is reached. + * + * @param buffer String buffer of data. + * @param max_size Maximum size of string buffer. + * @param pos Position to increment. + * @param output String buffer to store output. + * @param output_max_size Maximum size of output string buffer. + * @param is_array Whether the decoder is processing an array. + * @return True if pos has not reached the end + * of the buffer, false otherwise. + */ +stock bool json_extract_until_end( + const char[] buffer, + int max_size, + int &pos, + char[] output, + int output_max_size, + bool is_array +) { + strcopy(output, output_max_size, ""); + + // set start to position of first character in cell + int start = pos; + + // while we haven't hit whitespace, an end point or the end of the buffer + while ( + ! json_is_whitespace(buffer[pos]) + && ! json_is_at_end(buffer[pos], is_array) + && pos < max_size + ) { + pos += 1; + } + + // set end to the current position + int end = pos; + + // skip any following whitespace + json_skip_whitespace(buffer, max_size, pos); + + // if we aren't at a valid endpoint, extraction has failed + if (! json_is_at_end(buffer[pos], is_array)) { + return false; + } + + // copy only from start with length end - start + NULL terminator + strcopy(output, end - start + 1, buffer[start]); + + return pos < max_size; +} + +/** + * Calculates the size of the buffer required to store the next + * JSON string stored in the provided buffer at the provided position. + * This function is quite forgiving of malformed input and shouldn't be + * relied upon as proof that the input is valid. + * + * @param buffer String buffer of data. + * @param max_size Maximum size of string buffer. + * @param pos Position to increment. + * @param is_array Whether the decoder is processing an array. + * @return The size of the buffer required to store the string. + */ +stock int json_extract_string_size( + const char[] buffer, + int max_size, + int pos, + bool is_array +) +{ + int length = 1; // for NULL terminator + + // store initial quote + char quote = buffer[pos]; + + // increment past opening quote + pos += 1; + + // while we haven't hit the end of the buffer + int continuous_backslashes = 0; + while (pos < max_size) { + if (buffer[pos] == quote) { + // if we have an even number of preceding backslashes, + // the quote isn't escaped so this is the end of the string + if (continuous_backslashes % 2 == 0) { + break; + } + } + + if (buffer[pos] == '\\') { + continuous_backslashes += 1; + } else { + continuous_backslashes = 0; + } + + // pass over the character as it is part of the string + pos += 1; + length += 1; + } + + return length; +} + +/** + * Extracts a JSON string from the buffer until a valid end point is reached. + * + * @param buffer String buffer of data. + * @param max_size Maximum size of string buffer. + * @param pos Position to increment. + * @param output String buffer to store output. + * @param output_max_size Maximum size of output string buffer. + * @param is_array Whether the decoder is processing an array. + * @return True if pos has not reached the end + * of the buffer, false otherwise. + */ +stock bool json_extract_string( + const char[] buffer, + int max_size, + int &pos, + char[] output, + int output_max_size, + bool is_array +) { + strcopy(output, output_max_size, ""); + + // store initial quote + char quote = buffer[pos]; + + // increment past opening quote + pos += 1; + + // set start to position of first character in string + int start = pos; + + // while we haven't hit the end of the buffer + int continuous_backslashes = 0; + while (pos < max_size) { + // check for unescaped control characters + if ( + buffer[pos] == '\b' + || buffer[pos] == '\f' + || buffer[pos] == '\n' + || buffer[pos] == '\r' + || buffer[pos] == '\t' + ) { + return false; + } + + if (buffer[pos] == quote) { + // if we have an even number of preceding backslashes, + // the quote isn't escaped so this is the end of the string + if (continuous_backslashes % 2 == 0) { + break; + } + } + + if (buffer[pos] == '\\') { + continuous_backslashes += 1; + } else { + if (continuous_backslashes % 2 != 0) { + if (buffer[pos] == 'u') { + if (pos + 4 >= max_size) { + // less than 4 characters left in the buffer + return false; + } + + // ensure next 4 chars are hex and not a high surrogate + for (int i = 0; i < 4; i += 1) { + pos += 1; + + if (! json_char_is_hex(buffer[pos])) { + return false; + } + + if ( + i == 1 + && buffer[pos - 1] == 'D' + && buffer[pos] >= '8' + ) { + // detected a high surrogate value + return false; + } + } + + // jump back to the last hex char so it is safe to continue + pos -= 1; + } else if ( + buffer[pos] != '"' + && buffer[pos] != '\'' + && buffer[pos] != '/' + && buffer[pos] != 'b' + && buffer[pos] != 'f' + && buffer[pos] != 'n' + && buffer[pos] != 'r' + && buffer[pos] != 't' + ) { + // illegal escape detected + return false; + } + } + + continuous_backslashes = 0; + } + + // pass over the character as it is part of the string + pos += 1; + } + + // set end to the current position + int end = pos; + + // increment past closing quote + pos += 1; + + // skip trailing whitespace + if (! json_skip_whitespace(buffer, max_size, pos)) { + return false; + } + + // if we haven't reached an ending character at the end of the cell, + // there is likely junk data not encapsulated by a string + if (! json_is_at_end(buffer[pos], is_array)) { + return false; + } + + // copy only from start with length end - start + NULL terminator + int length = end - start + 1; + strcopy( + output, + length > output_max_size ? output_max_size : length, + buffer[start] + ); + + if (quote == '\'') { + ReplaceString(output, max_size, "\\'", "'"); + } + + json_unescape_string(output, max_size); + + return pos < max_size; +} diff --git a/scripting/include/json/helpers/errors.inc b/scripting/include/json/helpers/errors.inc new file mode 100644 index 0000000..7c3241c --- /dev/null +++ b/scripting/include/json/helpers/errors.inc @@ -0,0 +1,64 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_helpers_errors_included + #endinput +#endif +#define _json_helpers_errors_included + +static char g_jsonLastError[1024] = ""; + +/** + * Stores the error provided as the 'last error' for later access. + * @internal + * + * @param error Error to store. + * @param ... Further arguments to pass to message formatter. + */ +stock void json_set_last_error(const char[] error, any ...) +{ + VFormat(g_jsonLastError, sizeof(g_jsonLastError), error, 2); +} + +/** + * Retrieves the last error encountered and stores it in the buffer provided. + * + * @param buffer String buffer. + * @param max_size Maximum size of string buffer. + * @return True if the error was copied successfuly, + * false otherwise. + */ +stock bool json_get_last_error(char[] buffer, int max_size) +{ + return strcopy(buffer, max_size, g_jsonLastError) > 0; +} diff --git a/scripting/include/json/helpers/metastringmap.inc b/scripting/include/json/helpers/metastringmap.inc new file mode 100644 index 0000000..b89134a --- /dev/null +++ b/scripting/include/json/helpers/metastringmap.inc @@ -0,0 +1,237 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _metastringmap_included + #endinput +#endif +#define _metastringmap_included + +#include +#include + +/** + * A TypedStringMap which contains a nested `Data` `TypedStringMap` property. + * Standard methods and properties have been overridden to run against `Data`, + * but you can access the parent methods/properties using the `Meta` property. + */ +methodmap MetaStringMap < TypedStringMap +{ + /** + * @section Properties + */ + + /** + * Views the instance as its superclass to access overridden methods. + */ + property TypedStringMap Meta + { + public get() + { + return view_as(this); + } + } + + /** + * Gets the nested stringmap where data is stored. + */ + property TypedStringMap Data + { + public get() + { + return view_as(this.Meta.GetHandle("data")); + } + + public set(TypedStringMap value) + { + this.Meta.SetHandle("data", value); + } + } + + /** @see TypedStringMap.Length */ + property int Length { + public get() + { + return this.Data.Length; + } + } + + /** + * @section Getters + */ + + /** @see StringMap.GetValue */ + public bool GetValue(const char[] key, any &value) + { + return this.Data.GetValue(key, value); + } + + /** + * @see TypedStringMap.GetOptionalValue + * @internal + */ + public any GetOptionalValue(const char[] key, any default_value = -1) + { + return this.Data.GetOptionalValue(key, default_value); + } + + /** @see StringMap.GetString */ + public bool GetString( + const char[] key, + char[] value, + int max_size, + int &size = 0 + ) { + return this.Data.GetString(key, value, max_size, size); + } + + /** @see TypedStringMap.GetInt */ + public int GetInt(const char[] key, int default_value = -1) + { + return this.Data.GetInt(key, default_value); + } + + /** @see TypedStringMap.GetFloat */ + public float GetFloat(const char[] key, float default_value = -1.0) + { + return this.Data.GetFloat(key, default_value); + } + + /** @see TypedStringMap.GetBool */ + public bool GetBool(const char[] key, bool default_value = false) + { + return this.Data.GetBool(key, default_value); + } + + /** @see TypedStringMap.GetHandle */ + public Handle GetHandle(const char[] key, Handle default_value = null) + { + return this.Data.GetHandle(key, default_value); + } + + /** + * @section Setters + */ + + /** @see StringMap.SetValue */ + public bool SetValue(const char[] key, any value) + { + return this.Data.SetValue(key, value); + } + + /** @see StringMap.SetString */ + public bool SetString(const char[] key, const char[] value) + { + return this.Data.SetString(key, value); + } + + /** @see TypedStringMap.SetInt */ + public bool SetInt(const char[] key, int value) + { + return this.Data.SetInt(key, value); + } + + /** @see TypedStringMap.SetFloat */ + public bool SetFloat(const char[] key, float value) + { + return this.Data.SetFloat(key, value); + } + + /** @see TypedStringMap.SetBool */ + public bool SetBool(const char[] key, bool value) + { + return this.Data.SetBool(key, value); + } + + /** @see TypedStringMap.SetHandle */ + public bool SetHandle(const char[] key, Handle value) + { + return this.Data.SetHandle(key, value); + } + + /** @see StringMap.Remove */ + public bool Remove(const char[] key) + { + return this.Data.Remove(key); + } + + /** + * @section Misc + */ + + /** @see TypedStringMap.HasKey */ + public bool HasKey(const char[] key) + { + return this.Data.HasKey(key); + } + + /** @see StringMap.Clear */ + public void Clear() + { + TypedStringMap data = this.Data; + data.Clear(); + this.Meta.Clear(); + this.Data = data; + } + + /** + * Deletes the instance's data StringMap as well as the instance itself. + */ + public void Cleanup() + { + delete this.Data; + delete this; + } + + /** @see StringMap.Snapshot */ + public StringMapSnapshot Snapshot() + { + return this.Data.Snapshot(); + } + + /** + * @section Constructor + */ + + /** + * Creates a new MetaStringMap. + * + * @return A new MetaStringMap. + */ + public MetaStringMap() + { + MetaStringMap self = view_as(new TypedStringMap()); + self.Data = new TypedStringMap(); + + return self; + } +}; diff --git a/scripting/include/json/helpers/string.inc b/scripting/include/json/helpers/string.inc new file mode 100644 index 0000000..e01400c --- /dev/null +++ b/scripting/include/json/helpers/string.inc @@ -0,0 +1,247 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_helpers_string_included + #endinput +#endif +#define _json_helpers_string_included + +#include + +/** + * Mapping characters to their escaped form. + */ +char JSON_STRING_NORMAL[][] = { + "\\", "\"", "/", "\b", "\f", "\n", "\r", "\t" +}; +char JSON_STRING_ESCAPED[][] = { + "\\\\", "\\\"", "\\/", "\\b", "\\f", "\\n", "\\r", "\\t" +}; + +/** + * Escapes a string in-place in a buffer. + * + * @param buffer String buffer. + * @param max_size Maximum size of string buffer. + */ +stock void json_escape_string(char[] buffer, int max_size) +{ + for (int i = 0; i < sizeof(JSON_STRING_NORMAL); i += 1) { + ReplaceString( + buffer, + max_size, + JSON_STRING_NORMAL[i], + JSON_STRING_ESCAPED[i] + ); + } + + int length = strlen(buffer) + 1; + for (int pos = 0; pos < length && pos < max_size; pos += 1) { + if (buffer[pos] < 0x80) { + // skip standard ascii values + continue; + } + + // consume the ascii bytes of the next utf8 character + int ascii_size; + int utf8 = json_ascii_to_utf8(buffer[pos], length - pos, ascii_size); + if (ascii_size <= 0) { + continue; + } + + // convert the utf8 value to escaped format + char escaped[7]; + FormatEx(escaped, sizeof(escaped), "\\u%04x", utf8); + + // duplicate the consumed byte array + ascii_size += 1; + char[] ascii = new char[ascii_size]; + for (int i = 0; i < ascii_size; i += 1) { + ascii[i] = buffer[pos + i]; + } + ascii[ascii_size - 1] = '\0'; + + // replace bytes with the escaped value + int replacements = ReplaceString(buffer, max_size, ascii, escaped); + + // calculate new string length based on replacements made + length -= replacements * ascii_size - 1; + length += replacements * sizeof(escaped) - 1; + + // skip to the last of the bytes we just replaced + pos += sizeof(escaped) - 2; + } +} + +/** + * Unescapes a string in-place in a buffer. + * + * @param buffer String buffer. + * @param max_size Maximum size of string buffer. + */ +stock void json_unescape_string(char[] buffer, int max_size) +{ + int length = strlen(buffer) + 1; + int continuous_backslashes = 0; + for (int pos = 0; pos < length && pos < max_size; pos += 1) { + if (buffer[pos] == '\\') { + continuous_backslashes += 1; + } else { + if (continuous_backslashes % 2 != 0 && buffer[pos] == 'u') { + // consume the entire escape starting at backslash + pos -= 1; + char escaped[7]; + for (int i = 0; i < 6; i += 1) { + escaped[i] = buffer[pos + i]; + } + escaped[sizeof(escaped) - 1] = '\0'; + + // convert the hex to decimal + int utf8 = StringToInt(escaped[2], 16); + + // convert the utf8 to ascii + int ascii_size = json_utf8_to_ascii_size(utf8) + 1; + char[] ascii = new char[ascii_size]; + int written = json_utf8_to_ascii(utf8, ascii, ascii_size); + + // replace the escaped value with ascii bytes + int replacements = ReplaceString( + buffer, + max_size, + escaped, + ascii, + false + ); + + // calculate new string length based on replacements made + length -= replacements * sizeof(escaped) - 1; + length += replacements * written; + + // skip to the last of the bytes we just replaced + pos += written - 1; + } + + continuous_backslashes = 0; + } + } + + for (int i = 0; i < sizeof(JSON_STRING_NORMAL); i += 1) { + ReplaceString( + buffer, + max_size, + JSON_STRING_ESCAPED[i], + JSON_STRING_NORMAL[i] + ); + } +} + +/** + * Checks whether the provided character is a valid hexadecimal character. + * + * @param c Character to check. + * @return True if c is a hexadecimal character, false otherwise. + */ +stock bool json_char_is_hex(int c) +{ + return ( + (c >= '0' && c <= '9') + || (c >= 'a' && c <= 'f') + || (c >= 'A' && c <= 'F') + ); +} + +/** + * Calculates the maximum buffer length required to + * store the JSON cell representation of a string. + * + * @param length The length of the string. + * @return Maximum buffer length. + */ +stock int json_cell_string_size(const char[] input) +{ + int size = 3; // for outside quotes + NULL terminator + + bool foundEscapeTarget = false; + int length = strlen(input); + for (int pos = 0; pos < length; pos += 1) { + foundEscapeTarget = false; + for (int i = 0; i < sizeof(JSON_STRING_NORMAL); i += 1) { + if (input[pos] == JSON_STRING_NORMAL[i][0]) { + size += 2; + foundEscapeTarget = true; + break; + } + } + + if (foundEscapeTarget) { + continue; + } + + if (input[pos] < 0x80) { + size += 1; + continue; + } + + // consume the ascii bytes of the next utf8 character + int ascii_size; + json_ascii_to_utf8(input[pos], length - pos, ascii_size); + if (ascii_size <= 0) { + continue; + } + + pos += ascii_size - 1; + size += 6; // for unicode escape is \uXXXX + } + + return size; +} + +/** + * Generates the JSON cell representation of a string. + * + * @param input Value to generate output for. + * @param output String buffer to store output. + * @param max_size Maximum size of string buffer. + */ +stock void json_cell_string(const char[] input, char[] output, int max_size) +{ + // add input string to output, offset for start/end quotes + strcopy(output[1], max_size - 2, input); + + // escape the output + json_escape_string(output[1], max_size - 2); + + // surround output with quotations + output[0] = '"'; + StrCat(output, max_size, "\""); +} diff --git a/scripting/include/json/helpers/typedstringmap.inc b/scripting/include/json/helpers/typedstringmap.inc new file mode 100644 index 0000000..07ef8c0 --- /dev/null +++ b/scripting/include/json/helpers/typedstringmap.inc @@ -0,0 +1,222 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _typedstringmap_included + #endinput +#endif +#define _typedstringmap_included + +#include + +/** @see StringMap.ContainsKey */ +#define TRIE_SUPPORTS_CONTAINSKEY SOURCEMOD_V_MAJOR >= 1 \ + && SOURCEMOD_V_MINOR >= 11 \ + && SOURCEMOD_V_REV >= 6646 + +/** + * A StringMap with typed getters and setters. + */ +methodmap TypedStringMap < StringMap +{ + /** + * @section Properies + */ + + /** @see StringMap.Size */ + property int Length { + public get() + { + return this.Size; + } + } + + /** + * @section Misc + */ + + /** @see StringMap.ContainsKey */ + public bool HasKey(const char[] key) + { + #if TRIE_SUPPORTS_CONTAINSKEY + return this.ContainsKey(key); + #else + int dummy_int; + char dummy_str[1]; + + return this.GetValue(key, dummy_int) + || this.GetString(key, dummy_str, sizeof(dummy_str)); + #endif + } + + /** + * @section Getters + */ + + // GetValue is implemented natively by StringMap + + /** + * Retrieves the value stored at a key. + * @internal + * + * @param key Key to retrieve value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public any GetOptionalValue(const char[] key, any default_value = -1) + { + any value; + return this.GetValue(key, value) ? value : default_value; + } + + // GetString is implemented natively by StringMap + + /** + * Retrieves the int stored at a key. + * + * @param key Key to retrieve int value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public int GetInt(const char[] key, int default_value = -1) + { + return view_as(this.GetOptionalValue(key, default_value)); + } + + /** + * Retrieves the float stored at a key. + * + * @param key Key to retrieve float value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public float GetFloat(const char[] key, float default_value = -1.0) + { + return view_as(this.GetOptionalValue(key, default_value)); + } + + /** + * Retrieves the bool stored at a key. + * + * @param key Key to retrieve bool value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public bool GetBool(const char[] key, bool default_value = false) + { + return view_as(this.GetOptionalValue(key, default_value)); + } + + /** + * Retrieves the handle stored at a key. + * + * @param key Key to retrieve handle value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public Handle GetHandle( + const char[] key, + Handle default_value = null + ) { + return view_as(this.GetOptionalValue(key, default_value)); + } + + /** + * @section Setters + */ + + // SetValue is implemented natively by StringMap + + // SetString is implemented natively by StringMap + + /** + * Sets the int stored at a key. + * + * @param key Key to set to int value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetInt(const char[] key, int value) + { + return this.SetValue(key, value); + } + + /** + * Sets the float stored at a key. + * + * @param key Key to set to float value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetFloat(const char[] key, float value) + { + return this.SetValue(key, value); + } + + /** + * Sets the bool stored at a key. + * + * @param key Key to set to bool value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetBool(const char[] key, bool value) + { + return this.SetValue(key, value); + } + + /** + * Sets the handle stored at a key. + * + * @param key Key to set to object value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetHandle(const char[] key, Handle value) + { + return this.SetValue(key, value); + } + + /** + * @section Constructor + */ + + /** + * Creates a new TypedStringMap. + * + * @return A new TypedStringMap. + */ + public TypedStringMap() + { + return view_as(CreateTrie()); + } +}; diff --git a/scripting/include/json/helpers/unicode.inc b/scripting/include/json/helpers/unicode.inc new file mode 100644 index 0000000..1c4bb43 --- /dev/null +++ b/scripting/include/json/helpers/unicode.inc @@ -0,0 +1,185 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_helpers_unicode_included + #endinput +#endif +#define _json_helpers_unicode_included + +// most of the code here is adapted from https://dev.w3.org/XML/encoding.c + +/** + * Calculates how many bytes will be required to store the ASCII + * representation of a UTF-8 character. + * + * @param c The UTF-8 character. + * @return The number of bytes required, or -1 if c is invalid. + */ +stock int json_utf8_to_ascii_size(int c) +{ + if (c < 0 || c > 0x10FFFF) { + return -1; + } + + if (c < 0x80) { + return 1; + } else if (c < 0x800) { + return 2; + } else if (c < 0x10000) { + if (c >= 0xD800 && c <= 0xDFFF) { + // high surrogate + return -1; + } + + return 3; + } + + return 4; +} + +/** + * Converts a UTF-8 character to its ASCII representation. + * + * @param c The UTF-8 character. + * @param output String buffer to store output. + * @param max_size Maximum size of string buffer. + * @return The number of bytes written, or -1 if c is invalid. + */ +stock int json_utf8_to_ascii(int c, char[] output, int max_size) +{ + if (max_size < 1) { + return 0; + } + + if (c < 0 || c > 0x10FFFF) { + return -1; + } + + int size = 0; + if (c < 0x80) { + size = 1; + output[0] = c; + } else if (c < 0x800) { + size = 2; + output[0] = ((c >> 6) & 0x1F) | 0xC0; + } else if (c < 0x10000) { + if (c >= 0xD800 && c <= 0xDFFF) { + // high surrogate + return -1; + } + + size = 3; + output[0] = ((c >> 12) & 0x0F) | 0xE0; + } else { + size = 4; + output[0] = ((c >> 18) & 0x07) | 0xF0; + } + + if (size >= max_size) { + return -1; + } + + // first byte has already been calculated, calculate the rest + int i; + for (i = 1; i < size; i += 1) { + output[i] = ((c >> ((size - i - 1) * 6)) & 0x3F) | 0x80; + } + + return i; +} + +/** + * Converts bytes to their UTF-8 int representation. + * + * @param ascii The ascii/bytes to convert. + * @param max_size Maximum size of ascii. + * @return The UTF-8 int representation. + */ +stock int json_ascii_to_utf8(const char[] ascii, int max_size, int &size) +{ + size = 0; + if (max_size < 1) { + return -1; + } + + int c = 0; + if ((ascii[0] & 0x80) != 0) { + if (max_size < 2) { + return -1; + } + + if ((ascii[1] & 0xC0) != 0x80) { + return -1; + } + + if ((ascii[0] & 0xE0) == 0xE0) { + if (max_size < 3) { + return -1; + } + + if ((ascii[2] & 0xC0) != 0x80) { + return -1; + } + + if ((ascii[0] & 0xF0) == 0xF0) { + if (max_size < 4) { + return -1; + } + + if ((ascii[0] & 0xF8) != 0xF0 || (ascii[3] & 0xC0) != 0x80) { + return -1; + } + + size = 4; + c = (ascii[0] & 0x07) << 18; + } else { + size = 3; + c = (ascii[0] & 0x0F) << 12; + } + } else { + size = 2; + c = (ascii[0] & 0x1F) << 6; + } + } else { + size = 1; + c = ascii[0]; + } + + // first byte has already been calculated, calculate the rest + int i; + for (i = 1; i < size; i += 1) { + c |= (ascii[i] & 0x3F) << ((size - i - 1) * 6); + } + + return c; +} diff --git a/scripting/include/json/object.inc b/scripting/include/json/object.inc new file mode 100644 index 0000000..71a0603 --- /dev/null +++ b/scripting/include/json/object.inc @@ -0,0 +1,724 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * sm-json + * A pure SourcePawn JSON encoder/decoder. + * https://github.com/clugg/sm-json + * + * sm-json (C)2022 James Dickens. (clug) + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + */ + +#if defined _json_object_included + #endinput +#endif +#define _json_object_included + +#include +#include +#include +#include + +methodmap JSON_Object < MetaStringMap +{ + /** + * @section Properties + */ + + /** + * Views the instance as its superclass to access overridden methods. + */ + property MetaStringMap Super + { + public get() + { + return view_as(this); + } + } + + /** + * Whether the current object is an array. + */ + property bool IsArray { + public get() + { + return this.Meta.GetBool(JSON_ARRAY_KEY); + } + } + + /** + * @section Iteration Helpers + */ + + /** + * @section Metadata Getters + */ + + /** + * Gets the requested meta info for a key. + * @internal + * + * @param key Key to get meta info for. + * @param meta Meta info to get. + * @param default_value Value to return if meta does not exist. + * @return The meta value. + */ + public any GetMeta( + const char[] key, + JSONMetaInfo meta, + any default_value + ) { + int max_size = json_meta_key_length(key); + char[] meta_key = new char[max_size]; + json_format_meta_key(meta_key, max_size, key, meta); + + return this.Meta.GetOptionalValue(meta_key, default_value); + } + + /** + * Gets the cell type stored at a key. + * + * @param key Key to get value type for. + * @return Value type for key provided, + * or JSON_Type_Invalid if it does not exist. + */ + public JSONCellType GetType(const char[] key) + { + return view_as( + this.GetMeta(key, JSON_Meta_Type, JSON_Type_Invalid) + ); + } + + /** + * Gets the size of the string stored at a key. + * + * @param key Key to get buffer size for. + * @return Buffer size for string at key provided, + * or -1 if it is not a string/does not exist. + */ + public int GetSize(const char[] key) + { + return view_as(this.GetMeta(key, JSON_Meta_Size, -1)); + } + + /** + * Gets whether the key should be hidden from encoding. + * + * @param key Key to get hidden state for. + * @return Whether or not the key should be hidden. + */ + public bool GetHidden(const char[] key) + { + return view_as(this.GetMeta(key, JSON_Meta_Hidden, false)); + } + + /** + * Gets the index of a key. + * + * @param key Key to get index of. + * @return Index of the key provided, or -1 if it does not exist. + */ + public int GetIndex(const char[] key) + { + return view_as(this.GetMeta(key, JSON_Meta_Index, -1)); + } + + /** + * Gets the key stored at an index. + * If an array, will convert the index to its string value. + * If an array, will return false if the index is not between [0, length]. + * + * @param index Index of key. + * @param value Buffer to store key at. + * @param max_size Maximum size of value buffer. + * @return True on success, false otherwise. + */ + public bool GetKey(int index, char[] value, int max_size) + { + char[] index_key = new char[JSON_INT_BUFFER_SIZE]; + if (IntToString(index, index_key, JSON_INT_BUFFER_SIZE) == 0) { + return false; + } + + if (this.IsArray) { + // allow access of one past last index for intermediary operations + if (index < 0 || index > this.Length) { + return false; + } + + strcopy(value, max_size, index_key); + + return true; + } + + return this.Meta.GetString(index_key, value, max_size); + } + + /** + * Returns the buffer size required to store the key at the specified index. + * + * @param index Index of key. + * @return Buffer size required to store key. + */ + public int GetKeySize(int index) + { + if (this.IsArray) { + return JSON_INT_BUFFER_SIZE; + } + + int max_size = JSON_INT_BUFFER_SIZE + 4; + char[] index_size_key = new char[max_size]; + FormatEx(index_size_key, max_size, "%d:len", index); + + return this.Meta.GetInt(index_size_key); + } + + /** + * @section Metadata Setters + */ + + /** + * Sets meta info on a key. + * @internal + * + * @param key Key to set meta info for. + * @param meta Meta info to set. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetMeta(const char[] key, JSONMetaInfo meta, any value) + { + int max_size = json_meta_key_length(key); + char[] meta_key = new char[max_size]; + json_format_meta_key(meta_key, max_size, key, meta); + + return this.Meta.SetValue(meta_key, value); + } + + /** + * Removes meta info from a key. + * @internal + * + * @param key Key to remove meta info from. + * @param meta Meta info to remove. + * @return True on success, false otherwise. + */ + public bool RemoveMeta(const char[] key, JSONMetaInfo meta) + { + int max_size = json_meta_key_length(key); + char[] meta_key = new char[max_size]; + json_format_meta_key(meta_key, max_size, key, meta); + + return this.Meta.Remove(meta_key); + } + + /** + * Sets whether the key should be hidden from encoding. + * + * @param key Key to set hidden state for. + * @param hidden Whether or not the key should be hidden. + * @return True on success, false otherwise. + */ + public bool SetHidden(const char[] key, bool hidden) + { + return hidden + ? this.SetMeta(key, JSON_Meta_Hidden, hidden) + : this.RemoveMeta(key, JSON_Meta_Hidden); + } + + /** + * Tracks a key, setting it's type and index where necessary. + * @internal + * + * @param key Key to track. If the key already + * exists, it's index will not be changed. + * @param type Type to set key to. If a valid type is + * provided, the key's type will be updated. + * @param index Index to set key to. If the index is not + * provided (-1), the object length will be used. + * @return True on success, false otherwise. + */ + public bool TrackKey( + const char[] key, + JSONCellType type = JSON_Type_Invalid, + int index = -1 + ) { + // track type if provided + if (type != JSON_Type_Invalid) { + this.SetMeta(key, JSON_Meta_Type, type); + } + + if (this.IsArray) { + return true; + } + + if (index == -1) { + index = this.Length; + + // skip tracking index if we're pushing to end & key already exists + if (this.HasKey(key)) { + if (type != JSON_Type_Invalid && type != JSON_Type_String) { + // remove any existing size + this.RemoveMeta(key, JSON_Meta_Size); + } + + return true; + } + } + + char[] index_key = new char[JSON_INT_BUFFER_SIZE]; + IntToString(index, index_key, JSON_INT_BUFFER_SIZE); + + int max_size = JSON_INT_BUFFER_SIZE + 8; + char[] index_size_key = new char[max_size]; + FormatEx(index_size_key, max_size, "%d:len", index); + + return this.Meta.SetString(index_key, key) + && this.Meta.SetInt(index_size_key, strlen(key) + 1) + && this.SetMeta(key, JSON_Meta_Index, index); + } + + /** + * Untracks a key, cleaning up all it's meta and indexing data. + * @internal + * + * @param key Key to untrack. + * @return True on success, false otherwise. + */ + public bool UntrackKey(const char[] key) + { + int index = this.GetIndex(key); + + for (int i = 0; i < sizeof(JSON_ALL_METADATA); i += 1) { + this.RemoveMeta(key, JSON_ALL_METADATA[i]); + } + + if (this.IsArray) { + return true; + } + + if (index == -1) { + return false; + } + + char[] index_key = new char[JSON_INT_BUFFER_SIZE]; + IntToString(index, index_key, JSON_INT_BUFFER_SIZE); + + int max_size = JSON_INT_BUFFER_SIZE + 8; + char[] index_size_key = new char[max_size]; + FormatEx(index_size_key, max_size, "%d:len", index); + + if (! this.Meta.Remove(index_key) || ! this.Meta.Remove(index_size_key)) { + return false; + } + + int length = this.Length; + int last_index = length - 1; + if (index < last_index) { + for (int i = index + 1; i < length; i += 1) { + int new_key_size = this.GetKeySize(i); + char[] new_key = new char[new_key_size]; + this.GetKey(i, new_key, new_key_size); + + this.TrackKey(new_key, JSON_Type_Invalid, i - 1); + } + + IntToString(last_index, index_key, JSON_INT_BUFFER_SIZE); + FormatEx(index_size_key, max_size, "%d:len", last_index); + + this.Meta.Remove(index_key); + this.Meta.Remove(index_size_key); + } + + return true; + } + + /** + * @section Getters + */ + + #if SM_INT64_SUPPORTED + /** + * Retrieves the int64 stored at a key. + * + * @param key Key to retrieve int64 value for. + * @param value Int buffer to store output. + * @return True on success, false otherwise. + */ + public bool GetInt64(const char[] key, int value[2]) + { + return this.Data.GetArray(key, value, 2); + } + #endif + + /** + * Retrieves the JSON object stored at a key. + * + * @param key Key to retrieve object value for. + * @param default_value Value to return if the key does not exist. + * @return Value stored at key. + */ + public JSON_Object GetObject( + const char[] key, + JSON_Object default_value = null + ) { + return view_as(this.GetHandle(key, default_value)); + } + + /** + * @section Setters + */ + + /** + * Sets the string stored at a key. + * + * @param key Key to set to string value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetString(const char[] key, const char[] value) + { + return this.TrackKey(key, JSON_Type_String) + && this.Super.SetString(key, value) + && this.SetMeta(key, JSON_Meta_Size, strlen(value) + 1); + } + + /** + * Sets the int stored at a key. + * + * @param key Key to set to int value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetInt(const char[] key, int value) + { + return this.TrackKey(key, JSON_Type_Int) + && this.Super.SetInt(key, value); + } + + #if SM_INT64_SUPPORTED + /** + * Sets the int64 stored at a key. + * + * @param key Key to set to int64 value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetInt64(const char[] key, int value[2]) + { + return this.TrackKey(key, JSON_Type_Int64) + && this.Data.SetArray(key, value, 2); + } + #endif + + /** + * Sets the float stored at a key. + * + * @param key Key to set to float value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetFloat(const char[] key, float value) + { + return this.TrackKey(key, JSON_Type_Float) + && this.Super.SetFloat(key, value); + } + + /** + * Sets the bool stored at a key. + * + * @param key Key to set to bool value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetBool(const char[] key, bool value) + { + return this.TrackKey(key, JSON_Type_Bool) + && this.Super.SetBool(key, value); + } + + /** + * Sets the JSON object stored at a key. + * + * @param key Key to set to object value. + * @param value Value to set. + * @return True on success, false otherwise. + */ + public bool SetObject(const char[] key, JSON_Object value) + { + return this.TrackKey(key, JSON_Type_Object) + && this.Super.SetHandle(key, value); + } + + /** + * @section Misc + */ + + /** + * Removes an item from the object by key. + * + * @param key Key of object to remove. + * @return True on success, false if the value was never set. + */ + public bool Remove(const char[] key) + { + return this.UntrackKey(key) && this.Super.Remove(key); + } + + /** + * Renames the key of an existing item in the object. + * + * @param from Existing key to rename. + * @param to New key. + * @param replace Should the 'to' key should be replaced if it exists? + * @return True on success, false otherwise. + */ + public bool Rename( + const char[] from, + const char[] to, + bool replace = true + ) { + JSONCellType type = this.GetType(from); + if (type == JSON_Type_Invalid) { + return false; + } + + if (StrEqual(from, to, true)) { + return true; + } + + bool toExists = this.HasKey(to); + if (toExists) { + if (! replace) { + return false; + } + + this.Remove(to); + } + + switch (type) { + case JSON_Type_String: { + int length = this.GetSize(from); + char[] value = new char[length]; + this.GetString(from, value, length); + this.SetString(to, value); + } + case JSON_Type_Int: { + this.SetInt(to, this.GetInt(from)); + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + int value[2]; + this.GetInt64(from, value); + this.SetInt64(to, value); + } + #endif + case JSON_Type_Float: { + this.SetFloat(to, this.GetFloat(from)); + } + case JSON_Type_Bool: { + this.SetBool(to, this.GetBool(from)); + } + case JSON_Type_Object: { + this.SetObject(to, this.GetObject(from)); + } + } + + this.SetHidden(to, this.GetHidden(from)); + + this.Remove(from); + + return true; + } + + /** + * Merges in the entries from the specified object, + * optionally replacing existing entries with the same key. + * + * @param from Object to merge entries from. + * @param options Bitwise combination of `JSON_MERGE_*` options. + * @return True on success, false otherwise. + * @error If the object being merged is an array, + * an error will be thrown. + */ + public bool Merge(JSON_Object from, int options = JSON_MERGE_REPLACE) + { + if (this.IsArray || from.IsArray) { + json_set_last_error("attempted to merge using an array"); + + return false; + } + + bool replace = (options & JSON_MERGE_REPLACE) > 0; + bool autocleanup = (options & JSON_MERGE_CLEANUP) > 0; + + int json_size = from.Length; + int key_length = 0; + for (int i = 0; i < json_size; i += 1) { + key_length = from.GetKeySize(i); + char[] key = new char[key_length]; + from.GetKey(i, key, key_length); + + // skip already existing keys if we aren't in replace mode + bool key_already_exists = this.HasKey(key); + if (! replace && key_already_exists) { + continue; + } + + JSONCellType type = from.GetType(key); + // skip keys of unknown type + if (type == JSON_Type_Invalid) { + continue; + } + + // merge value onto structure + switch (type) { + case JSON_Type_String: { + int length = from.GetSize(key); + char[] value = new char[length]; + from.GetString(key, value, length); + + this.SetString(key, value); + } + case JSON_Type_Int: { + this.SetInt(key, from.GetInt(key)); + } + #if SM_INT64_SUPPORTED + case JSON_Type_Int64: { + int value[2]; + from.GetInt64(key, value); + this.SetInt64(key, value); + } + #endif + case JSON_Type_Float: { + this.SetFloat(key, from.GetFloat(key)); + } + case JSON_Type_Bool: { + this.SetBool(key, from.GetBool(key)); + } + case JSON_Type_Object: { + JSON_Object value = from.GetObject(key); + + if (autocleanup && key_already_exists) { + JSON_Object existing = this.GetObject(key); + if (existing != value) { + json_cleanup_and_delete(existing); + } + } + + this.SetObject(key, value); + } + } + + this.SetHidden(key, from.GetHidden(key)); + } + + return true; + } + + /** + * @section json.inc Aliases + */ + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_encode_size + */ + public int EncodeSize(int options = JSON_NONE) + { + return json_encode_size(this, options); + } + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_encode + */ + public void Encode(char[] output, int max_size, int options = JSON_NONE) + { + json_encode(this, output, max_size, options); + } + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_write_to_file + */ + public bool WriteToFile(const char[] path, int options = JSON_NONE) + { + return json_write_to_file(this, path, options); + } + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_copy_deep + */ + public JSON_Object ShallowCopy() + { + return json_copy_shallow(this); + } + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_copy_deep + */ + public JSON_Object DeepCopy() + { + return json_copy_deep(this); + } + + /** + * Makes a global call with this + * instance passed as the object. + * + * @see json_cleanup + */ + public void Cleanup() + { + json_cleanup(this); + } + + /** + * @section Constructor + */ + + /** + * Creates a new JSON_Object. + * + * @return A new JSON_Object. + */ + public JSON_Object() + { + return view_as(new MetaStringMap()); + } +}; diff --git a/scripting/include/jutils.inc b/scripting/include/jutils.inc new file mode 100644 index 0000000..8d32ef5 --- /dev/null +++ b/scripting/include/jutils.inc @@ -0,0 +1,967 @@ +#if defined _jutils_included + #endinput +#endif +#define _jutils_included + +#define MODEL_FRANCIS "models/survivors/survivor_biker.mdl" +#define MODEL_LOUIS "models/survivors/survivor_manager.mdl" +#define MODEL_ZOEY "models/survivors/survivor_teenangst.mdl" +#define MODEL_BILL "models/survivors/survivor_namvet.mdl" +#define MODEL_NICK "models/survivors/survivor_gambler.mdl" +#define MODEL_COACH "models/survivors/survivor_coach.mdl" +#define MODEL_ELLIS "models/survivors/survivor_mechanic.mdl" +#define MODEL_ROCHELLE "models/survivors/survivor_producer.mdl" +#define MODEL_MINIGUN "models/w_models/weapons/w_minigun.mdl" + +/** Gets a location horizontally X units away from the origin point. Ignores Z-axis. + * @noreturn + */ +stock void GetHorizontalPositionFromOrigin(const float pos[3], const float ang[3], float units, float finalPosition[3]) { + float theta = DegToRad(ang[1]); + finalPosition[0] = units * Cosine(theta) + pos[0]; + finalPosition[1] = units * Sine(theta) + pos[1]; + finalPosition[2] = pos[2]; +} +stock void GetHorizontalPositionFromClient(int client, float units, float finalPosition[3]) { + float pos[3], ang[3]; + GetClientEyeAngles(client, ang); + GetClientAbsOrigin(client, pos); + + float theta = DegToRad(ang[1]); + pos[0] += units * Cosine(theta); + pos[1] += units * Sine(theta); + finalPosition = pos; +} +stock void GetOffsetPosition(float pos[3], const float ang[3], float forwardBack, float leftRight, float upDown) { + float theta = DegToRad(ang[1]); + pos[0] = forwardBack * Cosine(theta) + pos[0]; + pos[1] = forwardBack * Sine(theta) + pos[1]; + pos[2] = pos[2] + upDown; +} + // Gets velocity of an entity (ent) toward new origin with speed (fSpeed) - thanks Ryan + stock bool GetVelocityToOrigin(int entity, const float destination[3], const float fSpeed, float outVelocity[3]) { + float srcOrigin[3]; + GetEntPropVector(entity, Prop_Data, "m_vecVelocity", srcOrigin); + // Velocity = Distance / Time + + float fDistance[3]; + fDistance[0] = destination[0] - srcOrigin[0]; + fDistance[1] = destination[1] - srcOrigin[1]; + fDistance[2] = destination[2] - srcOrigin[2]; + + float fTime = (GetVectorDistance(srcOrigin, destination) / fSpeed); + + outVelocity[0] = (destination[0] - srcOrigin[0]) / fTime; + outVelocity[1] = (destination[1] - srcOrigin[1]) / fTime; + outVelocity[2] = (destination[2] - srcOrigin[2]) / fTime; + + return (outVelocity[0] && outVelocity[1] && outVelocity[2]); + } + +//Credits to Timocop for the stock :D +/** +* Runs a single line of vscript code. +* NOTE: Dont use the "script" console command, it starts a new instance and leaks memory. Use this instead! +* +* @param sCode The code to run. +* @noreturn +*/ +stock void L4D2_RunScript(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} +stock void ShowDelayedHintToAll(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + static int hintInt = 0; + if(hintInt >= 7) { + PrintHintTextToAll("%s",buffer); + hintInt = 0; + } + hintInt++; +} + +stock int GetSurvivorId(const char[] str, bool isL4D1 = false) { + int possibleNumber = StringToInt(str, 10); + if(strlen(str) == 1) { + if(possibleNumber <= 7 && possibleNumber >= 0) { + return possibleNumber; + } + }else if(possibleNumber == 0) { + int survivorId; + char s = CharToLower(str[0]); + if(s == 'b') { + survivorId = isL4D1 ? 0 : 4; + } else if(s == 'z') { + survivorId = isL4D1 ? 1 : 5; + } else if(s == 'l') { + survivorId = isL4D1 ? 2 : 7; + } else if(s == 'f') { + survivorId = isL4D1 ? 3 : 6; + } else if(s == 'n') { + survivorId = 0; + } else if(s == 'r') { + survivorId = 1; + } else if(s == 'e') { + survivorId = 3; + } else if(s == 'c') { + survivorId = 2; + } + return survivorId; + } + return -1; +} +stock int GetL4D2SurvivorId(const char str[16]) { + int possibleNumber = StringToInt(str, 10); + if(strlen(str) == 1) { + if(possibleNumber <= 7 && possibleNumber >= 0) { + return possibleNumber; + } + }else if(possibleNumber == 0) { + if(StrEqual(str, "nick", false)) return 0; + else if(StrEqual(str, "rochelle", false)) return 1; + else if(StrEqual(str, "coach", false)) return 2; + else if(StrEqual(str, "ellis", false)) return 3; + else if(StrEqual(str, "bill", false)) return 0; + else if(StrEqual(str, "zoey", false)) return 5; + else if(StrEqual(str, "francis", false)) return 3; + else if(StrEqual(str, "louis", false)) return 2; + } + return -1; +} +stock bool GetSurvivorModel(int character, char[] model, int modelStrSize) { + switch(character) { + case 0: strcopy(model, modelStrSize, MODEL_NICK); + case 1: strcopy(model, modelStrSize, MODEL_ROCHELLE); + case 2: strcopy(model, modelStrSize, MODEL_COACH); + case 3: strcopy(model, modelStrSize, MODEL_ELLIS); + case 4: strcopy(model, modelStrSize, MODEL_BILL); + case 5: strcopy(model, modelStrSize, MODEL_ZOEY); + case 6: strcopy(model, modelStrSize, MODEL_FRANCIS); + case 7: strcopy(model, modelStrSize, MODEL_LOUIS); + default: return false; + } + return true; +} +stock bool FindSurvivorModel(const char str[16], char[] model, int modelStrSize) { + int possibleNumber = StringToInt(str, 10); + if(strlen(str) == 1 && possibleNumber <= 7 && possibleNumber >= 0) { + switch(possibleNumber) { + case 0: strcopy(model, modelStrSize, MODEL_NICK); + case 1: strcopy(model, modelStrSize, MODEL_ROCHELLE); + case 2: strcopy(model, modelStrSize, MODEL_COACH); + case 3: strcopy(model, modelStrSize, MODEL_ELLIS); + case 4: strcopy(model, modelStrSize, MODEL_BILL); + case 5: strcopy(model, modelStrSize, MODEL_ZOEY); + case 6: strcopy(model, modelStrSize, MODEL_FRANCIS); + case 7: strcopy(model, modelStrSize, MODEL_LOUIS); + default: return false; + } + return true; + }else{ + if(possibleNumber == 0) { + //try to parse str + if(StrEqual(str, "bill", false)) + strcopy(model, modelStrSize, MODEL_BILL); + else if(StrEqual(str, "zoey", false)) + strcopy(model, modelStrSize, MODEL_ZOEY); + else if(StrEqual(str, "francis", false)) + strcopy(model, modelStrSize, MODEL_FRANCIS); + else if(StrEqual(str, "louis", false)) + strcopy(model, modelStrSize, MODEL_LOUIS); + else if(StrEqual(str, "nick", false)) + strcopy(model, modelStrSize, MODEL_NICK); + else if(StrEqual(str, "ellis", false)) + strcopy(model, modelStrSize, MODEL_ELLIS); + else if(StrEqual(str, "rochelle", false)) + strcopy(model, modelStrSize, MODEL_ROCHELLE); + else if(StrEqual(str, "coach", false)) + strcopy(model, modelStrSize, MODEL_COACH); + else + return false; + return true; + } + } + return false; +} +//returns true if model found +stock bool GetSurvivorName(int client, char[] buffer, int length) { + + char modelName[38]; + GetClientModel(client, modelName, sizeof(modelName)); + if(StrContains(modelName,"biker",false) > -1) { + strcopy(buffer, length, "Francis"); + }else if(StrContains(modelName,"teenangst",false) > -1) { + strcopy(buffer, length, "Zoey"); + }else if(StrContains(modelName,"namvet",false) > -1) { + strcopy(buffer, length, "Bill"); + }else if(StrContains(modelName,"manager",false) > -1) { + strcopy(buffer, length, "Louis"); + }else if(StrContains(modelName,"coach",false) > -1) { + strcopy(buffer, length, "Coach"); + }else if(StrContains(modelName,"producer",false) > -1) { + strcopy(buffer, length, "Rochelle"); + }else if(StrContains(modelName,"gambler",false) > -1) { + strcopy(buffer, length, "Nick"); + }else if(StrContains(modelName,"mechanic",false) > -1) { + strcopy(buffer, length, "Ellis"); + }else{ + return false; + } + return true; +} + +stock int GetSurvivorType(const char[] modelName) { + if(StrContains(modelName,"biker",false) > -1) { + return 6; + }else if(StrContains(modelName,"teenangst",false) > -1) { + return 5; + }else if(StrContains(modelName,"namvet",false) > -1) { + return 4; + }else if(StrContains(modelName,"manager",false) > -1) { + return 7; + }else if(StrContains(modelName,"coach",false) > -1) { + return 2; + }else if(StrContains(modelName,"producer",false) > -1) { + return 1; + }else if(StrContains(modelName,"gambler",false) > -1) { + return 0; + }else if(StrContains(modelName,"mechanic",false) > -1) { + return 3; + }else{ + return false; + } +} +stock bool TraceFilter(int entity, int contentsMask) { + if( entity <= MaxClients ) + return false; + return true; +} +stock bool GetGround(int client, float vPos[3], float vAng[3]) { + GetClientAbsOrigin(client, vPos); + vAng = vPos; + vAng[2] += 5.0; + vPos[2] -= 500.0; + + Handle trace = TR_TraceRayFilterEx(vAng, vPos, MASK_SOLID, RayType_EndPoint, TraceFilter); + if(!TR_DidHit(trace)) { + delete trace; + return false; + } + TR_GetEndPosition(vPos, trace); + delete trace; + + GetClientAbsAngles(client, vAng); + return true; +} + +stock int GiveClientWeaponLasers(int client, const char[] wpnName) { + int entity = GiveClientWeapon(client, wpnName); + if(entity != -1) { + SetEntProp(entity, Prop_Send, "m_upgradeBitVec", 4); + } + return entity; +} + +stock int GiveClientWeapon(int client, const char[] wpnName) { + static char sTemp[64]; + float pos[3]; + GetClientAbsOrigin(client, pos); + Format(sTemp, sizeof(sTemp), "weapon_%s", wpnName); + + int entity = CreateEntityByName(sTemp); + if( entity != -1 ) { + DispatchSpawn(entity); + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + + EquipPlayerWeapon(client, entity); + return entity; + }else{ + return -1; + } +} +stock int GetNearestEntity(int client, char[] classname) +{ + int nearestEntity = -1; + float clientVecOrigin[3], entityVecOrigin[3]; + + //Get the distance between the first entity and client + float distance, nearestDistance = -1.0; + + //Find all the entity and compare the distances + int entity = -1; + while ((entity = FindEntityByClassname(entity, classname)) != -1) + { + GetEntPropVector(entity, Prop_Data, "m_vecOrigin", entityVecOrigin); + distance = GetVectorDistance(clientVecOrigin, entityVecOrigin, true); + + if (distance < nearestDistance || nearestDistance == -1.0) + { + nearestEntity = entity; + nearestDistance = distance; + } + } + return nearestEntity; +} + +stock bool IsValidPlayer(int i) { + return IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i); +} +stock bool IsValidTeamPlayer(int i, int team) { + return IsValidPlayer(i) && GetClientTeam(i) == team; +} +stock int GetPrimaryAmmo(int client) { + int weapon = GetPlayerWeaponSlot(client, 0); + if(weapon > -1) + return GetEntProp(weapon, Prop_Send, "m_iClip1"); + else + return -1; +} +stock int GetSecondaryAmmo(int client, int weapon) { + int activeWpn = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"); + if(activeWpn == weapon) { + int offset = GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); + return GetEntProp(client, Prop_Send, "m_iAmmo", _, offset); + } else { + return GetEntProp(activeWpn, Prop_Send, "m_iExtraPrimaryAmmo"); + } +} + +stock void SetSecondaryAmmo(int client, int weapon, int ammo) { + int activeWpn = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"); + if(activeWpn == weapon) { + int offset = GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); + SetEntProp(client, Prop_Send, "m_iAmmo", ammo, _, offset); + } else { + SetEntProp(activeWpn, Prop_Send, "m_iExtraPrimaryAmmo", ammo); + } +} +stock void CheatCommand(int client, const char[] command, const char[] argument1, const char[] argument2) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s %s", command, argument1, argument2); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} +//entity abs origin code from here +//http://forums.alliedmods.net/showpost.php?s=e5dce96f11b8e938274902a8ad8e75e9&p=885168&postcount=3 +stock void GetEntityAbsOrigin(int entity, float origin[3]) { + if (entity && IsValidEntity(entity) + && (GetEntSendPropOffs(entity, "m_vecOrigin") != -1) + && (GetEntSendPropOffs(entity, "m_vecMins") != -1) + && (GetEntSendPropOffs(entity, "m_vecMaxs") != -1)) + { + float mins[3], maxs[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", origin); + GetEntPropVector(entity, Prop_Send, "m_vecMins", mins); + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", maxs); + + origin[0] += (mins[0] + maxs[0]) * 0.5; + origin[1] += (mins[1] + maxs[1]) * 0.5; + origin[2] += (mins[2] + maxs[2]) * 0.5; + } +} +stock bool IsPrimaryWeapon(const char[] wpnName) { + return StrContains(wpnName, "rifle") > -1 + || StrContains(wpnName, "smg") > -1 + || StrContains(wpnName, "weapon_grenade_launcher") > -1 + || StrContains(wpnName, "sniper") > -1 + || StrContains(wpnName, "shotgun") > -1; +} +stock int GetClientWeaponEntIndex(int client, int slot) { + if(slot >= 0 && slot <= 5) { + int wpnRef = GetPlayerWeaponSlot(client, slot); + if(wpnRef != -1) { + int wpn = EntRefToEntIndex(wpnRef); + if(wpn != INVALID_ENT_REFERENCE) { + return wpn; + }else{ + return -1; + } + }else{ + return -1; + } + }else{ + ThrowError("Slot must be a number between 0 and 5"); + return -1; + } +} +stock int GetClientSecondaryWeapon(int client) { + return GetClientWeaponEntIndex(client, 1); +} +stock bool GetClientWeaponName(int client, int slot, char[] name, int nameSize) { + int wpn = GetClientWeaponEntIndex(client, slot); + if(wpn > 0) { + GetEntityClassname(wpn, name, nameSize); + return true; + }else{ + return false; + } +} +stock bool GetClientWeaponNameSmart(int client, int slot, char[] name, int nameSize) { + int wpn = GetPlayerWeaponSlot(client, slot); + if(wpn > 0) { + GetEntityClassname(wpn, name, nameSize); + if(slot == 1 && StrEqual(name, "weapon_melee")) { + GetEntPropString(wpn, Prop_Data, "m_strMapSetScriptName", name, nameSize); + } + return true; + } + return false; +} + +stock int GetClientWeaponNameSmart2(int client, int slot, char[] name, int nameSize) { + int wpn = GetPlayerWeaponSlot(client, slot); + if(wpn > 0) { + GetEntityClassname(wpn, name, nameSize); + if(slot == 1 && StrEqual(name, "weapon_melee")) { + GetEntPropString(wpn, Prop_Data, "m_strMapSetScriptName", name, nameSize); + } else { + Format(name, nameSize, "%s", name[7]); + } + return wpn; + } + return -1; +} + + +stock bool DoesClientHaveWeapon(int client, int slot, const char[] name) { + char wpn[32]; + if(GetClientWeaponName(client, slot, wpn, sizeof(wpn))) { + return StrEqual(wpn, name, false); + }else{ + return false; + } +} + +stock bool DoesClientHaveMelee(int client) { + int wpnEnt = GetClientSecondaryWeapon(client); + if(wpnEnt > -1) { + char wpn[16]; + GetEdictClassname(wpnEnt, wpn, sizeof(wpn)); + return StrEqual(wpn, "weapon_melee"); + }else{ + return false; + } +} + +stock bool IsValidClient(int client, int checkTeam = 0) { + int team = checkTeam > 0 ? GetClientTeam(client) : 0; + return IsClientConnected(client) && IsClientInGame(client) && IsPlayerAlive(client) && team == checkTeam; +} + +stock bool IsClientInSightRange(int client, int target, float angle = 90.0, float distance = 0.0, bool heightcheck = true, bool negativeangle = false) { + if(angle > 360.0 || angle < 0.0) + ThrowError("Angle Max : 360 & Min : 0. %d isn't proper angle.", angle); + else if(!IsValidClient(client)) + ThrowError("Client is not Alive."); + else if(!IsValidClient(target)) + ThrowError("Target is not Alive."); + + float clientPos[3], targetPos[3], angleVector[3], targetVector[3], resultAngle, resultDistance; + + GetClientEyeAngles(client, angleVector); + angleVector[0] = angleVector[2] = 0.0; + GetAngleVectors(angleVector, angleVector, NULL_VECTOR, NULL_VECTOR); + NormalizeVector(angleVector, angleVector); + if(negativeangle) + NegateVector(angleVector); + + GetClientAbsOrigin(client, clientPos); + GetClientAbsOrigin(target, targetPos); + if(heightcheck && distance > 0) + resultDistance = GetVectorDistance(clientPos, targetPos); + clientPos[2] = targetPos[2] = 0.0; + MakeVectorFromPoints(clientPos, targetPos, targetVector); + NormalizeVector(targetVector, targetVector); + + resultAngle = RadToDeg(ArcCosine(GetVectorDotProduct(targetVector, angleVector))); + + if(resultAngle <= angle/2) + { + if(distance > 0) + { + if(!heightcheck) + resultDistance = GetVectorDistance(clientPos, targetPos); + + return distance >= resultDistance; + } + else return true; + } + else return false; +} + +/// Checks if entity is in sight of client. Angle is the FOV, distance to be squared +stock bool IsEntityInSightRange(int client, int target, float angle = 90.0, float distance = 0.0, bool heightcheck = true, bool negativeangle = false) { + if(angle > 360.0 || angle < 0.0) + ThrowError("Angle Max : 360 & Min : 0. %d isn't proper angle.", angle); + else if(!IsClientConnected(client) || !IsClientInGame(client)) + ThrowError("Client is not Alive."); + else if(target <= MaxClients || !IsValidEntity(target)) + ThrowError("Target is not valid entity."); + + + float clientPos[3], targetPos[3], angleVector[3], targetVector[3], resultAngle, resultDistance; + + GetClientEyeAngles(client, angleVector); + angleVector[0] = angleVector[2] = 0.0; + GetAngleVectors(angleVector, angleVector, NULL_VECTOR, NULL_VECTOR); + NormalizeVector(angleVector, angleVector); + if(negativeangle) + NegateVector(angleVector); + + GetClientAbsOrigin(client, clientPos); + GetEntPropVector(target, Prop_Send, "m_vecOrigin", targetPos); + if(heightcheck && distance > 0) + resultDistance = GetVectorDistance(clientPos, targetPos, true); + clientPos[2] = targetPos[2] = 0.0; + MakeVectorFromPoints(clientPos, targetPos, targetVector); + NormalizeVector(targetVector, targetVector); + + resultAngle = RadToDeg(ArcCosine(GetVectorDotProduct(targetVector, angleVector))); + + if(resultAngle <= angle/2) + { + if(distance > 0) + { + if(!heightcheck) + resultDistance = GetVectorDistance(clientPos, targetPos, true); + + return distance >= resultDistance; + } + else return true; + } + else return false; +} +stock void PrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToChat(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} +#if defined _multicolors_included +stock void CPrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + CPrintToChat(i, "%s", buffer); + } + } + } + CPrintToServer("%s", buffer); +} +#endif +stock bool IsValidAdmin(int client, const char[] flags) { + int ibFlags = ReadFlagString(flags); + if ((GetUserFlagBits(client) & ibFlags) == ibFlags) { + return true; + }else if (GetUserFlagBits(client) & ADMFLAG_ROOT) { + return true; + } + return false; +} + +stock float GetNearestEntityDistance(int originEntity, char[] classname) { + float compareVec[3], entityVecOrigin[3]; + GetEntPropVector(originEntity, Prop_Send, "m_vecOrigin", compareVec); + + //Get the distance between the first entity and client + float distance, nearestDistance = -1.0; + + int entity = -1, closest; + while ((entity = FindEntityByClassname(entity, classname)) != -1) + { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", entityVecOrigin); + distance = GetVectorDistance(compareVec, entityVecOrigin); + // PrintDebug(DEBUG_SPAWNLOGIC, "Comparing %s (id %d) (%.2f,%.2f,%.2f) distance to entity %d (%.2f,%.2f,%.2f) is %.4f", classname, entity, entityVecOrigin[0], entityVecOrigin[1], entityVecOrigin[2], originEntity, compareVec[0], compareVec[1], compareVec[2], distance); + + if (distance < nearestDistance || nearestDistance == -1.0) + { + nearestDistance = distance; + closest = entity; + } + } + return closest > 0 ? nearestDistance : -1.0; +} + +stock int FindNearestEntityInRange(int originEntity, char[] classname, float range) { + float compareVec[3], entityVecOrigin[3]; + GetEntPropVector(originEntity, Prop_Send, "m_vecOrigin", compareVec); + + //Get the distance between the first entity and client + float distance, nearestDistance = -1.0; + + int entity = -1, closest = -1; + while ((entity = FindEntityByClassname(entity, classname)) != -1) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", entityVecOrigin); + distance = GetVectorDistance(compareVec, entityVecOrigin); + + if (distance <= range && (distance < nearestDistance || nearestDistance == -1.0)) { + // PrintDebug(DEBUG_SPAWNLOGIC, "Comparing %s (id %d) (%.2f,%.2f,%.2f) distance to entity %d (%.2f,%.2f,%.2f) is %.4f", classname, entity, entityVecOrigin[0], entityVecOrigin[1], entityVecOrigin[2], originEntity, compareVec[0], compareVec[1], compareVec[2], distance); + nearestDistance = distance; + closest = entity; + } + } + return closest; +} + +stock void MakeEntityGlow(int entity, const int color[3], float distance = 1500.0) { + SetEntProp(entity, Prop_Send, "m_iGlowType", 3); + SetEntProp(entity, Prop_Send, "m_nGlowRange", distance); + SetEntProp(entity, Prop_Send, "m_glowColorOverride", color[0] + (color[1] * 256) + (color[2] * 65536)); +} + +//Unless I'm dumb, this does not exist +stock void StringToLower(char[] str) { + int len = strlen(str); + for(int i = 0; i < len; i++) { + str[i] = CharToLower(str[i]); + } +} +stock void StringToUpper(char[] str) { + int len = strlen(str); + for(int i = 0; i < len; i++) { + str[i] = CharToUpper(str[i]); + } +} + +stock int GetRealClient(int client) { + if(IsFakeClient(client)) { + int realPlayer = GetClientOfUserId(GetEntProp(client, Prop_Send, "m_humanSpectatorUserID")); + return realPlayer > 0 ? realPlayer : -1; + }else{ + return client; + } +} + +stock int FindIdleBot(int client) { + for(int i = 1; i <= MaxClients; i++ ) { + if(IsClientConnected(i) && IsClientInGame(i) && HasEntProp(i, Prop_Send, "m_humanSpectatorUserID")) { + int realPlayer = GetClientOfUserId(GetEntProp(i, Prop_Send, "m_humanSpectatorUserID")); + if(realPlayer == client) { + return i; + } + } + } + return -1; +} + +stock void SetParent(int child, int parent) { + SetVariantString("!activator"); + AcceptEntityInput(child, "SetParent", parent); +} + +stock void SetParentAttachment(int child, const char[] attachment, bool withOffset = false) { + SetVariantString(attachment); + if(withOffset) + AcceptEntityInput(child, "SetParentAttachmentMaintainOffset"); + else + AcceptEntityInput(child, "SetParentAttachment"); +} + +stock void ClearParent(int child) { + AcceptEntityInput(child, "ClearParent"); +} + +stock void GetForwardVector(float vPos[3], float vAng[3], float vReturn[3], float fDistance) { + float vDir[3]; + GetAngleVectors(vAng, vDir, NULL_VECTOR, NULL_VECTOR); + ScaleVector(vDir, fDistance); + AddVectors(vPos, vDir, vReturn); +} + +stock void GetDirectionVector(float pos1[3], float angle[3], float rVec[3], float distance, float force) { + float endPos[3]; + GetForwardVector(pos1, angle, endPos, distance); + + MakeVectorFromPoints(pos1, endPos, rVec); + NormalizeVector(rVec, rVec); + + ScaleVector(rVec, force); +} + +// Taken from https://gist.github.com/Aeldrion/48c82912f632eec4c8b9da7394b89c5d +stock void HSVToRGB(const float vec[3], float out[3]) { + // Translates HSV color to RGB color + // H: 0.0 - 360.0, S: 0.0 - 100.0, V: 0.0 - 100.0 + // R, G, B: 0.0 - 1.0 + + float hue = vec[0]; + float saturation = vec[1]; + float value = vec[2]; + + float c = (value / 100.0) * (saturation / 100.0); + float x = c * (1.0 - FloatAbs(float(RoundToFloor(hue / 60) % 2) - 1)); + float m = (value / 100.0) - c; + + if (hue >= 0 && hue < 60.0) { + out[0] = c; + out[1] = x; + out[2] = 0.0; + } else if (hue >= 60.0 && hue < 120.0) { + out[0] = x; + out[1] = c; + out[2] = 0.0; + } else if (hue >= 120.0 && hue < 180.0) { + out[0] = 0.0; + out[1] = c; + out[2] = x; + } else if (hue >= 180.0 && hue < 240.0) { + out[0] = 0.0; + out[1] = x; + out[2] = c; + } else if (hue >= 240.0 && hue < 300.0) { + out[0] = x; + out[1] = 0.0; + out[2] = c; + } else if (hue >= 300.0 && hue < 360.0) { + out[0] = c; + out[1] = 0.0; + out[2] = x; + } + + out[0] += m; + out[1] += m; + out[2] += m; + + out[0] * 255.0; + out[1] * 255.0; + out[2] * 255.0; +} +stock void HSVToRGBInt(const float vec[3], int out[3]) { + // Don't initialize memory, just use the existing memory as int out[3], just tell it that is a float + HSVToRGB(vec, view_as(out)); + // Convert float to int: + out[0] = RoundToFloor(view_as(out[0])); + out[1] = RoundToFloor(view_as(out[1])); + out[2] = RoundToFloor(view_as(out[2])); +} + +stock bool GetCursorLocation(int client, float outPos[3]) { + float angle[3]; + GetClientEyePosition(client, outPos); + GetClientEyeAngles(client, angle); + TR_TraceRayFilter(outPos, angle, MASK_SOLID, RayType_Infinite, Filter_IgnorePlayer, client); + if(TR_DidHit()) { + TR_GetEndPosition(outPos); + return true; + } else { + return false; + } +} + +bool Filter_IgnorePlayer(int entity, int mask, int data) { + return entity > 0 && entity != data; +} + +bool Filter_World(int entity, int mask, int data) { + return entity == 0; +} + +// Gets a position from where the cursor is upto distance away (basically <= distance, going against walls) +stock bool GetCursorLimited(int client, float distance, float endPos[3], TraceEntityFilter filter) +{ + if (client > 0 && client <= MaxClients && IsClientInGame(client)) { + float clientEye[3], clientAngle[3], direction[3]; + GetClientEyePosition(client, clientEye); + GetClientEyeAngles(client, clientAngle); + + GetAngleVectors(clientAngle, direction, NULL_VECTOR, NULL_VECTOR); + ScaleVector(direction, distance); + AddVectors(clientEye, direction, endPos); + + TR_TraceRayFilter(clientEye, endPos, MASK_OPAQUE, RayType_EndPoint, filter, client); + if (TR_DidHit(INVALID_HANDLE)) { + TR_GetEndPosition(endPos); + } + return true; + } + + return false; +} + +stock void SetWeaponDelay(int client, float delay) { + int pWeapon = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"); + if (pWeapon > -1) { + SetEntPropFloat(pWeapon, Prop_Send, "m_flNextPrimaryAttack", GetGameTime() + delay); + SetEntPropFloat(pWeapon, Prop_Send, "m_flNextSecondaryAttack", GetGameTime() + delay); + } +} + + +// Sends client a menu selecting a player, see COMMAND_FILTER_* for flags, idPrefix is appended to menu item's id +stock void QueryPlayer(int client, MenuHandler handler, int flags = COMMAND_FILTER_NO_IMMUNITY, const char[] title = "Select a player", const char[] idPrefix = "", int time = 0) { + Menu menu = new Menu(handler); + menu.SetTitle(title, client); + char id[32], display[32]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && (IsClientInGame(i) || flags & COMMAND_FILTER_CONNECTED)) { + if(flags & COMMAND_FILTER_NO_BOTS && IsFakeClient(i)) continue; + if(flags & COMMAND_FILTER_ALIVE && !IsPlayerAlive(i)) continue; + if(flags & COMMAND_FILTER_DEAD && IsPlayerAlive(i)) continue; + if(~flags & COMMAND_FILTER_NO_IMMUNITY && !CanUserTarget(client, i)) continue; + + Format(id, sizeof(id), "%s%d", idPrefix, GetClientUserId(i)); + if(IsFakeClient(i)) { + int realPlayer = GetRealClient(i); + if(realPlayer > 0) { + if(IsPlayerAlive(i)) { + Format(display, sizeof(display), "%N (Idle)", realPlayer); + } else { + Format(display, sizeof(display), "%N (Idle)(Dead)", realPlayer); + } + } else if(IsPlayerAlive(i)) { + Format(display, sizeof(display), "%N", i); + } else { + Format(display, sizeof(display), "%N (dead)", i); + } + } else if(IsPlayerAlive(i)) { + Format(display, sizeof(display), "%N", i); + } else { + Format(display, sizeof(display), "%N (dead)", i); + } + + menu.AddItem(id, display); + } + } + + menu.Display(client, time); +} +stock bool IsNearGround(int ref, float distFromGround = 15.0) { + static float sPos[3], ePos[3]; + GetEntPropVector(ref, Prop_Send, "m_vecOrigin", sPos); + ePos[0] = sPos[0]; + ePos[1] = sPos[1]; + ePos[2] = sPos[2] -= 15.0; + TR_TraceRayFilter(sPos, ePos, MASK_SOLID, RayType_EndPoint, Filter_IgnorePlayer, ref); + if(TR_DidHit()) { + return true; + } + return false; +} + +stock bool IsAreaClear(const float pos[3], const float ang[3], const float minBound[3], const float maxBound[3]) { + + TR_TraceHullFilter(pos, pos, minBound, maxBound, MASK_SOLID, Filter_World); + if(TR_DidHit()) { + return false; + } + return true; +} + +stock Action Timer_KillEntity(Handle h, int entity) { + RemoveEntity(entity); + return Plugin_Handled; +} + +stock int GetSinglePlayer(int client, const char[] input, int flags = 0) { + flags |= COMMAND_FILTER_NO_MULTI; + char buf[2]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + input, + client, + target_list, + 1, + flags, + buf, + 2, + tn_is_ml)) <= 0 + ) { + ReplyToTargetError(client, target_count); + return -1; + } + return target_list[0]; +} + +#if defined _l4dh_included +static int _glowColor[3] = { 255, 255, 255 }; + +stock void GlowPoint(const float pos[3], float lifetime = 5.0) { + PrecacheModel("models/props_fortifications/orange_cone001_reference.mdl"); + int entity = CreateEntityByName("prop_dynamic"); + DispatchKeyValue(entity, "disableshadows", "1"); + DispatchKeyValue(entity, "model", "models/props_fortifications/orange_cone001_reference.mdl"); + TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(entity); + L4D2_SetEntityGlow(entity, L4D2Glow_Constant, 10000, 0, _glowColor, false); + CreateTimer(lifetime, Timer_KillEntity, entity); +} + +stock void GlowEntity(int entity, float lifetime = 10.0, int glowColor[3] = _glowColor) { + L4D2_SetEntityGlow(entity, L4D2Glow_Constant, 10000, 0, glowColor, false); + if(lifetime > 0.0) + CreateTimer(lifetime, Timer_ClearGlow, EntIndexToEntRef(entity)); +} + +Action Timer_ClearGlow(Handle h, int ref) { + L4D2_RemoveEntityGlow(ref); + return Plugin_Handled; +} +#endif + +stock bool CompareVector(const float a[3], const float b[3], float delta) { + return a[0] < b[0] + delta && a[0] > b[0] - delta && + a[1] < b[1] + delta && a[1] > b[1] - delta && + a[2] < b[2] + delta && a[2] > b[2] - delta +} + +stock void CalculateWorldPosition(int entity, float pos[3]) { + float mins[3], maxs[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + GetEntPropVector(entity, Prop_Send, "m_vecMins", mins); + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", maxs); + pos[0] = pos[0] + (mins[0] + maxs[0]) * 0.5; + pos[1] = pos[1] + (mins[1] + maxs[1]) * 0.5; + pos[2] = pos[2] + (mins[2] + maxs[2]) * 0.5; +} +#if defined _l4dh_included +/// Displays either: Username, Username (AFK), Username (Dead), Userame (AFK/Dead) +stock void GetMenuDisplayName(int client, char[] display, int maxlen) { + int realPlayer = L4D_GetIdlePlayerOfBot(client); + // Incase player is idle, grab their bot instead of them + if(realPlayer > 0 && IsClientConnected(realPlayer)) { + if(IsPlayerAlive(client)) + Format(display, maxlen, "%N (AFK)", realPlayer); + else + Format(display, maxlen, "%N (AFK/Dead)", realPlayer); + } else if(!IsPlayerAlive(client)) + Format(display, maxlen, "%N (Dead)", client); + else { + GetClientName(client, display, maxlen); + } +} +#endif + +stock int MathMax(int a, int b) { + return a > b ? a : b; +} + +stock int MathMin(int a, int b) { + return a < b ? a : b; +} \ No newline at end of file diff --git a/scripting/include/l4d2.inc b/scripting/include/l4d2.inc new file mode 100644 index 0000000..ddf75da --- /dev/null +++ b/scripting/include/l4d2.inc @@ -0,0 +1,499 @@ +/** +* ___ _______ _______ _______ _ ___ ______ _______ _______ ______ +* | | | || || | | | | | | | | || _ || | +* | | | ___|| ___||_ _| | |_| | | _ || ___|| |_| || _ | +* | | | |___ | |___ | | | | | | | || |___ | || | | | +* | |___ | ___|| ___| | | |___ | | |_| || ___|| || |_| | +* | || |___ | | | | | | | || |___ | _ || | +* |_______||_______||___| |___| |___| |______| |_______||__| |__||______| +* +* This include contains a ton of useful stocks and functions you can use for Left 4 Dead (2). +* Author: Keith Warren (Drixevel) +* https://github.com/Drixevel +* +* NOTE: The best way to use this include is to copy and paste into your projects manually. +* Credits: +**/ + +#if defined _misc_l4d_included + #endinput +#endif +#define _misc_l4d_included + +enum L4DGame +{ + L4DGame_L4D = 0, + L4DGame_L4D2 = 1 +} + +enum L4DTeam +{ + L4DTeam_Unassigned = 0, + L4DTeam_Spectator = 1, + L4DTeam_Survivors = 2, + L4DTeam_Infected = 3 +} + +enum L4DSurvivor +{ + L4DSurvivor_Bill = 0, + L4DSurvivor_Zoey = 1, + L4DSurvivor_Louis = 2, + L4DSurvivor_Francis = 3 +} + +enum L4D2Survivor +{ + L4D2Survivor_Nick = 0, + L4D2Survivor_Rochelle = 1, + L4D2Survivor_Coach = 2, + L4D2Survivor_Ellis = 3 +} + +enum L4DInfected +{ + L4DInfected_None = 0, + L4DInfected_Smoker = 1, + L4DInfected_Boomer = 2, + L4DInfected_Hunter = 3, + L4DInfected_Witch = 4, + L4DInfected_Tank = 5 +} + +enum L4D2Infected +{ + L4D2Infected_None = 0, + L4D2Infected_Smoker = 1, + L4D2Infected_Boomer = 2, + L4D2Infected_Hunter = 3, + L4D2Infected_Spitter = 4, + L4D2Infected_Jockey = 5, + L4D2Infected_Charger = 6, + L4D2Infected_Witch = 7, + L4D2Infected_Tank = 8 +} + +/** + * Gets a client's current team. + * + * @param client Client index. + * @return Current L4DTeam of client. + * @error Invalid client index. + */ +stock L4DTeam L4D_GetClientTeam(int client) +{ + return view_as(GetClientTeam(client)); +} + +/** + * Gets the current group of survivors assigned to the map. + * @return L4DGame enum index. + */ +stock L4DGame L4D_GetSurvivorGroup() +{ + int entity = -1; char sCharacter[32]; + while ((entity = FindEntityByClassname(entity, "info_survivor_position")) != -1) + { + GetEntPropString(entity, Prop_Data, "m_iszSurvivorName", sCharacter, sizeof(sCharacter)); + + if (strlen(sCharacter) > 0 && (StrEqual(sCharacter, "Bill") || StrEqual(sCharacter, "Zoey") || StrEqual(sCharacter, "Louis") || StrEqual(sCharacter, "Francis"))) + return L4DGame_L4D; + } + + return L4DGame_L4D2; +} + +/** + * Checks if the survivor is incapped. + * + * @param client Players index. + * @return True if player is incapacitated, false otherwise. + */ +stock bool L4D_IsClientIncapacitated(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isIncapacitated")); +} + +stock bool L4D_IsClientIncapped(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isIncapacitated")); +} + +/** + * Checks if the survivor is capped. + * + * @param client Players index. + * @return True if the player is capped, false otherwise. + */ +stock bool L4D_IsPlayerCapped(int client) +{ + if(GetEntPropEnt(client, Prop_Send, "m_pummelAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_carryAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_pounceAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_jockeyAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_pounceAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_tongueOwner") > 0) + return true; + return false; +} + +/*********************************************************************/ +/*********************************************************************/ +//Survivors +/*********************************************************************/ +/*********************************************************************/ + +/** + * Retrieves the survivor ID of the client for L4D. + * + * @param client Players index. + * @return Index of the survivor, -1 otherwise. + */ +stock L4DSurvivor L4D_GetClientSurvivorId(int client) +{ + int offset = FindSendPropInfo("CTerrorPlayer", "m_survivorCharacter"); + return view_as(GetEntData(client, offset, 1)); +} + +/** + * Retrieves the survivor ID of the client for L4D2. + * + * @param client Players index. + * @return Index of the survivor, -1 otherwise. + */ +stock L4D2Survivor L4D2_GetClientSurvivorId(int client) +{ + int offset = FindSendPropInfo("CTerrorPlayer", "m_survivorCharacter"); + return view_as(GetEntData(client, offset, 1)); +} + +/** + * Retrieves the survivor name of the client for L4D. + * + * @param client Players index. + * @return True if found, false otherwise. + */ +stock bool L4D_GetClientSurvivorName(int client, char[] name, int size) +{ + return L4D_GetSurvivorName(L4D_GetClientSurvivorId(client), name, size); +} + +/** + * Retrieves the survivor name of the client for L4D2. + * + * @param client Players index. + * @return True if found, false otherwise. + */ +stock bool L4D2_GetClientSurvivorName(int client, char[] name, int size) +{ + return L4D2_GetSurvivorName(L4D2_GetClientSurvivorId(client), name, size); +} + +/** + * Retrieves the ID of any of the L4D survivors. + * + * @param name Name of the survivor. + * @return The ID of the survivor, -1 for not found. + */ +stock L4DSurvivor L4D_GetSurvivorID(const char[] name) +{ + if (StrEqual(name, "bill", false)) + return L4DSurvivor_Bill; + else if (StrEqual(name, "zoey", false)) + return L4DSurvivor_Zoey; + else if (StrEqual(name, "louis", false)) + return L4DSurvivor_Louis; + else if (StrEqual(name, "francis", false)) + return L4DSurvivor_Francis; + + return -1; +} + +/** + * Retrieves the ID of any of the L4D2 survivors. + * + * @param name Name of the survivor. + * @return The ID of the survivor, -1 for not found. + */ +stock L4D2Survivor L4D2_GetSurvivorID(const char[] name) +{ + if (StrEqual(name, "nick", false)) + return L4D2Survivor_Nick; + else if (StrEqual(name, "rochelle", false)) + return L4D2Survivor_Rochelle; + else if (StrEqual(name, "coach", false)) + return L4D2Survivor_Coach; + else if (StrEqual(name, "ellis", false)) + return L4D2Survivor_Ellis; + + return -1; +} + +/** + * Retrieves the name of any of the L4D survivors. + * + * @param id ID of the survivor. + * @return True if found and buffer filled, false otherwise. + */ +stock bool L4D_GetSurvivorName(L4DSurvivor id, char[] name, int size, bool capitalize = false) +{ + switch (id) + { + case L4DSurvivor_Bill: + { + strcopy(name, size, capitalize ? "Bill" : "bill"); + return true; + } + case L4DSurvivor_Zoey: + { + strcopy(name, size, capitalize ? "Zoey" : "zoey"); + return true; + } + case L4DSurvivor_Louis: + { + strcopy(name, size, capitalize ? "Louis" : "louis"); + return true; + } + case L4DSurvivor_Francis: + { + strcopy(name, size, capitalize ? "Francis" : "francis"); + return true; + } + } + + return false; +} + +/** + * Retrieves the name of any of the L4D2 survivors. + * + * @param id ID of the survivor. + * @return True if found and buffer filled, false otherwise. + */ +stock bool L4D2_GetSurvivorName(L4D2Survivor id, char[] name, int size, bool capitalize = false) +{ + switch (id) + { + case L4D2Survivor_Nick: + { + strcopy(name, size, capitalize ? "Nick" : "nick"); + return true; + } + case L4D2Survivor_Rochelle: + { + strcopy(name, size, capitalize ? "Rochelle" : "rochelle"); + return true; + } + case L4D2Survivor_Coach: + { + strcopy(name, size, capitalize ? "Coach" : "coach"); + return true; + } + case L4D2Survivor_Ellis: + { + strcopy(name, size, capitalize ? "Ellis" : "ellis"); + return true; + } + } + + return false; +} + +/*********************************************************************/ +/*********************************************************************/ +//Infected +/*********************************************************************/ +/*********************************************************************/ + +/** + * Retrieves the infected ID of the client for L4D. + * + * @param client Players index. + * @return Index of the infected, -1 otherwise. + */ +stock L4DInfected L4D_GetClientInfectedId(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_zombieClass")); +} + +/** + * Retrieves the infected ID of the client for L4D2. + * + * @param client Players index. + * @return Index of the infected, -1 otherwise. + */ +stock L4D2Infected L4D2_GetClientInfectedId(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_zombieClass")); +} + +/** + * Retrieves the infected name of the client for L4D. + * + * @param client Players index. + * @return True if found, false otherwise. + */ +stock bool L4D_GetClientInfectedName(int client, char[] name, int size) +{ + return L4D_GetInfectedName(L4D_GetClientInfectedId(client), name, size); +} + +/** + * Retrieves the infected name of the client for L4D2. + * + * @param client Players index. + * @return True if found, false otherwise. + */ +stock bool L4D2_GetClientInfectedName(int client, char[] name, int size) +{ + return L4D2_GetInfectedName(L4D2_GetClientInfectedId(client), name, size); +} + +/** + * Retrieves the ID of any of the L4D infected. + * + * @param name Name of the infected. + * @return The ID of the infected, -1 for not found. + */ +stock L4DInfected L4D_GetInfectedID(const char[] name) +{ + if (StrEqual(name, "smoker", false)) + return L4DInfected_Smoker; + else if (StrEqual(name, "boomer", false)) + return L4DInfected_Boomer; + else if (StrEqual(name, "hunter", false)) + return L4DInfected_Hunter; + else if (StrEqual(name, "witch", false)) + return L4DInfected_Witch; + else if (StrEqual(name, "tank", false)) + return L4DInfected_Tank; + + return L4DInfected_None; +} + +/** + * Retrieves the ID of any of the L4D2 infected. + * + * @param name Name of the infected. + * @return The ID of the infected, -1 for not found. + */ +stock L4D2Infected L4D2_GetInfectedID(const char[] name) +{ + if (StrEqual(name, "smoker", false)) + return L4D2Infected_Smoker; + else if (StrEqual(name, "boomer", false)) + return L4D2Infected_Boomer; + else if (StrEqual(name, "hunter", false)) + return L4D2Infected_Hunter; + else if (StrEqual(name, "spitter", false)) + return L4D2Infected_Spitter; + else if (StrEqual(name, "charger", false)) + return L4D2Infected_Charger; + else if (StrEqual(name, "jockey", false)) + return L4D2Infected_Jockey; + else if (StrEqual(name, "witch", false)) + return L4D2Infected_Witch; + else if (StrEqual(name, "tank", false)) + return L4D2Infected_Tank; + + return L4D2Infected_None; +} + +/** + * Retrieves the name of any of the L4D infected. + * + * @param id ID of the infected. + * @return True if found and buffer filled, false otherwise. + */ +stock bool L4D_GetInfectedName(L4DInfected id, char[] name, int size, bool capitalize = false) +{ + switch (id) + { + case L4DInfected_None: + return false; + case L4DInfected_Smoker: + { + strcopy(name, size, capitalize ? "Smoker" : "smoker"); + return true; + } + case L4DInfected_Boomer: + { + strcopy(name, size, capitalize ? "Boomer" : "boomer"); + return true; + } + case L4DInfected_Hunter: + { + strcopy(name, size, capitalize ? "Hunter" : "hunter"); + return true; + } + case L4DInfected_Witch: + { + strcopy(name, size, capitalize ? "Witch" : "witch"); + return true; + } + case L4DInfected_Tank: + { + strcopy(name, size, capitalize ? "Tank" : "tank"); + return true; + } + } + + return false; +} + +/** + * Retrieves the name of any of the L4D2 infected. + * + * @param id ID of the infected. + * @return True if found and buffer filled, false otherwise. + */ +stock bool L4D2_GetInfectedName(L4D2Infected id, char[] name, int size, bool capitalize = false) +{ + switch (id) + { + case L4D2Infected_None: + return false; + case L4D2Infected_Smoker: + { + strcopy(name, size, capitalize ? "Smoker" : "smoker"); + return true; + } + case L4D2Infected_Boomer: + { + strcopy(name, size, capitalize ? "Boomer" : "boomer"); + return true; + } + case L4D2Infected_Hunter: + { + strcopy(name, size, capitalize ? "Hunter" : "hunter"); + return true; + } + case L4D2Infected_Spitter: + { + strcopy(name, size, capitalize ? "Spitter" : "spitter"); + return true; + } + case L4D2Infected_Jockey: + { + strcopy(name, size, capitalize ? "Jockey" : "jockey"); + return true; + } + case L4D2Infected_Charger: + { + strcopy(name, size, capitalize ? "Charger" : "charger"); + return true; + } + case L4D2Infected_Witch: + { + strcopy(name, size, capitalize ? "Witch" : "witch"); + return true; + } + case L4D2Infected_Tank: + { + strcopy(name, size, capitalize ? "Tank" : "tank"); + return true; + } + } + + return false; +} \ No newline at end of file diff --git a/scripting/include/l4d2_behavior.inc b/scripting/include/l4d2_behavior.inc new file mode 100644 index 0000000..a52134f --- /dev/null +++ b/scripting/include/l4d2_behavior.inc @@ -0,0 +1,337 @@ +#if defined _behavior_included + #endinput +#endif + +#define _behavior_included + +enum IAssignment +{ + WITCH_QUERY = 0, + INFECTED_QUERY, + SURVIVOR_QUERY, + SPECIAL_QUERY +}; + +//enum IBehaviorProperties: (+= 0x4) +enum IActionProperties +{ + m_behavior = 0x8, + m_parent = 0xC, + m_child = 0x10, + m_buriedUnderMe = 0x14, + m_coveringMe = 0x18, + m_type = 0x1C, + m_action = 0x20, + m_priority = 0x2C, + m_isStarted = 0x30, + m_isSuspended = 0x31 +}; + +enum ActionResultType +{ + CONTINUE, // continue executing this action next frame - nothing has changed + CHANGE_TO, // change actions next frame + SUSPEND_FOR, // put the current action on hold for the new action + DONE, // this action has finished, resume suspended action + SUSTAIN, // for use with event handlers - a way to say "It's important to keep doing what I'm doing" +}; + +enum EventResultPriorityType +{ + RESULT_NONE, // no result + RESULT_TRY, // use this result, or toss it out, either is ok + RESULT_IMPORTANT, // try extra-hard to use this result + RESULT_CRITICAL // this result must be used - emit an error if it can't be +}; + +enum BehaviorAction +{ + INVALID_ACTION +}; + +enum struct IActionResult +{ + ActionResultType m_type; + BehaviorAction m_action; + EventResultPriorityType m_priority; + + Address retn; + + void FromAddr (Address retn) + { + this.retn = retn; + + this.m_type = view_as(RDereference(retn, 0)); + this.m_action = view_as(RDereference(retn, 4)); + this.m_priority = view_as(RDereference(retn, 12)); + } + + void Init (ActionResultType typea, BehaviorAction action, EventResultPriorityType priority = RESULT_TRY) + { + this.m_type = typea; + this.m_action = action; + this.m_priority = priority; + } + + void Set (Address retn) + { + StoreToAddress(retn + view_as
(4), view_as(this.m_action), NumberType_Int32); + StoreToAddress(retn + view_as
(12), view_as(this.m_priority), NumberType_Int32); + + StoreToAddress(retn, view_as(this.m_type), NumberType_Int32); + } + + void ForAction (BehaviorAction action) + { + StoreToAddress(view_as
(action) + view_as
(view_as(m_action) + 4), view_as(this.m_action), NumberType_Int32); + StoreToAddress(view_as
(action) + view_as
(view_as(m_type) + 4), view_as(this.m_type), NumberType_Int32); + StoreToAddress(view_as
(action) + view_as
(view_as(m_priority) + 4), view_as(this.m_priority), NumberType_Int32); + } + + void ToAction (BehaviorAction action) + { + this.ForAction(action); + } + + void Apply () + { + this.Set(this.retn); + } + + void GetTypeName ( char[] buffer, int length ) + { + switch ( this.m_type ) + { + case CHANGE_TO: strcopy(buffer, length, "CHANGE_TO"); + case SUSPEND_FOR: strcopy(buffer, length, "SUSPEND_FOR"); + case DONE: strcopy(buffer, length, "DONE"); + case SUSTAIN: strcopy(buffer, length, "SUSTAIN"); + + default: strcopy(buffer, length, "CONTINUE"); + } + } +} + +enum struct IContext +{ + int survivor; + int special; + int witch; + int infected; +} + +static IContext context; + +methodmap Behavior +{ + public static Behavior ToBehavior(Address entity, IAssignment assign) + { + if ( !context.survivor ) + { + GameData data = new GameData("l4d2_behavior"); + + context.special = data.GetOffset("g_iSpecial"); + context.survivor = data.GetOffset("g_iSurvivor"); + context.witch = data.GetOffset("g_iWitch"); + context.infected = data.GetOffset("g_iInfected"); + + delete data; + } + + static const int byte[] = + { + 0, 0x1C + }; + + int offs; + + switch(assign) + { + case WITCH_QUERY: offs = context.witch; + case INFECTED_QUERY: offs = context.infected; + case SURVIVOR_QUERY: offs = context.survivor; + case SPECIAL_QUERY: offs = context.special; + } + + Address behavior = view_as
(offs) + entity; + + for (int i; i < sizeof byte; i++) + behavior = RDereference(behavior, byte[i]); + + return view_as(behavior); + } + + public Behavior (int entity, IAssignment assign) + { + return Behavior.ToBehavior(GetEntityAddress(entity), assign); + } + + property Address ToAddress + { + public get() + { + return view_as
(this); + } + } + + property Address AsAddress + { + public get() + { + return this.ToAddress; + } + } + + property bool Valid + { + public get() + { + return this.ToAddress != Address_Null; + } + } + + property BehaviorAction CurrentAction + { + public get() + { + return view_as(RDereference(this.AsAddress, view_as(m_behavior))); + } + } +} + +methodmap BehaviorAction < Behavior +{ + public Address GetProperty (IActionProperties propertie, NumberType type = NumberType_Int32) + { + return RDereference(this.ToAddress, view_as(propertie), type); + } + + public void SetProperty (IActionProperties propertie, any value, NumberType type = NumberType_Int32) + { + StoreToAddress(this.ToAddress, value, type); + } + + property BehaviorAction Next + { + public get() + { + return view_as(this.GetProperty(m_child)); + } + } + + property BehaviorAction Prev + { + public get() + { + return view_as(this.GetProperty(m_parent)); + } + } + + property BehaviorAction Under + { + public get() + { + return view_as(this.GetProperty(m_buriedUnderMe)); + } + } + + property BehaviorAction Above + { + public get() + { + return view_as(this.GetProperty(m_coveringMe)); + } + } + + property Behavior Contain + { + public get() + { + return view_as(this.GetProperty(m_behavior)); + } + } + + property BehaviorAction Last + { + public get() + { + BehaviorAction action = this; + + while ( action.Next.Valid ) + action = action.Next; + + return action; + } + } + + property BehaviorAction First + { + public get() + { + BehaviorAction action = this; + + while ( action.Prev.Valid ) + action = action.Prev; + + return action; + } + } + + public void SetAction (IActionResult result) + { + this.SetProperty(m_action, result.m_action); + this.SetProperty(m_priority, result.m_priority); + this.SetProperty(m_type, result.m_type); + } + + public void GetName(char[] destination, int length) + { + static Handle call; + + if ( !call ) + { + int idx = (context.special == 17176 ? 41 : 40); + + StartPrepSDKCall(SDKCall_Raw); + PrepSDKCall_SetVirtual(idx); + PrepSDKCall_SetReturnInfo(SDKType_String, SDKPass_Pointer); + call = EndPrepSDKCall(); + } + + SDKCall(call, this, destination, length); + } + + public void GetFullName(char[] destination, int length) + { + static Handle call; + + if ( !call ) + { + int idx = (context.special == 17176 ? 43 : 42); + + StartPrepSDKCall(SDKCall_Raw); + PrepSDKCall_SetVirtual(idx); + PrepSDKCall_SetReturnInfo(SDKType_String, SDKPass_Pointer); + call = EndPrepSDKCall(); + } + + SDKCall(call, this, destination, length); + } +} + +/** + * Allocates memory + * + * @param size allocation size in bytes + * @return allocation address + */ +native Address AllocateMemory (int size); + +/** + * Deallocates memory + * + * @param mem allocation address + */ +native void DeallocateMemory (Address mem); + +stock Address RDereference (Address ptr, int offset = 0, NumberType type = NumberType_Int32) { return view_as
(LoadFromAddress(ptr + view_as
(offset), type)); } \ No newline at end of file diff --git a/scripting/include/l4d2_behavior_components.inc b/scripting/include/l4d2_behavior_components.inc new file mode 100644 index 0000000..ffe064e --- /dev/null +++ b/scripting/include/l4d2_behavior_components.inc @@ -0,0 +1,70 @@ +#if defined _behavior_components_included + #endinput +#endif + +#define _behavior_components_included + +#define E9_LEN 5 + +enum struct IHookHandler +{ + bool hooked; + + int hooklen; + int memlen; + + int original[12]; + + Address func; + Address detouraddr; + Address allocate; + + DynamicDetour detour; + + void Hook (Address _func, int _hooklen, int _memlen, int offs = 0) + { + this.memlen = _memlen; + this.allocate = AllocateMemory(this.memlen + offs); + this.func = _func; + this.hooklen = _hooklen; + this.detouraddr = this.allocate + view_as
(this.memlen - E9_LEN - _hooklen + offs); + + int i; + + for (;i < this.memlen + offs; i++) + { + StoreToAddress(this.allocate + view_as
(i), 0x90, NumberType_Int8); + } + + for (i = 0; i < this.hooklen; i++) + { + this.original[i] = view_as(RDereference(this.func, i, NumberType_Int8)); + StoreToAddress(this.func + view_as
(i), 0x90, NumberType_Int8); + StoreToAddress(this.detouraddr + view_as
(i), this.original[i], NumberType_Int8); + } + + this.hooked = true; + } + + void Unhook() + { + if ( this.hooked ) + { + for (int i = 0; i < this.hooklen; i++) + { + StoreToAddress(this.func + view_as
(i), this.original[i], NumberType_Int8); + } + + DeallocateMemory(this.allocate); + this.hooked = false; + } + } +} + +/** + * Hooks action handler + * + * @param func event handler address + * @param out IHookHandler struct + */ +native void HookActionEvent (Address func, any[] out); \ No newline at end of file diff --git a/scripting/include/l4d2_detections.inc b/scripting/include/l4d2_detections.inc new file mode 100644 index 0000000..b3b7593 --- /dev/null +++ b/scripting/include/l4d2_detections.inc @@ -0,0 +1,10 @@ +// Called when a player takes two kits +forward void OnDoubleKit(int client); +// Called when a bile is thrown when no zombies around +forward void OnNoHordeBileWaste(int client, int commons); + +// Called when a door is closed within range of another player. +// Victim will be the closest victim to the door, may be incorrect. +forward void OnDoorCloseInFace(int client, int victim); +// Called on saferoom doors, with a count. Resets after 20s of no door opening. +forward void OnDoorCloseInFaceSaferoom(int client, int victim, int count); \ No newline at end of file diff --git a/scripting/include/l4d2_perms.inc b/scripting/include/l4d2_perms.inc new file mode 100644 index 0000000..cb0df49 --- /dev/null +++ b/scripting/include/l4d2_perms.inc @@ -0,0 +1,6 @@ +enum ReserveMode { + Reserve_None = 0, + Reserve_Watch, + Reserve_AdminOnly, + Reserve_Private +} \ No newline at end of file diff --git a/scripting/include/l4d2_skill_detect.inc b/scripting/include/l4d2_skill_detect.inc new file mode 100644 index 0000000..99cc6c5 --- /dev/null +++ b/scripting/include/l4d2_skill_detect.inc @@ -0,0 +1,294 @@ +#if defined _skilldetect_included_ + #endinput +#endif +#define _skilldetect_included_ + + +/** + * CarAlarmTriggerReason: the 'reason' parameter in OnCarAlarmTriggered() forward + */ +enum CarAlarmTriggerReason { + CarAlarmTrigger_Unknown, + CarAlarmTrigger_Hit, + CarAlarmTrigger_Touched, + CarAlarmTrigger_Explosion, + CarAlarmTrigger_Boomer +}; + + +/** + * Called whenever a true skeet with shotgun is done. + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + */ +forward void OnSkeet( int survivor, int hunter ); + +/** + * Called whenever a true melee-skeet is done. + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + */ +forward void OnSkeetMelee( int survivor, int hunter ); + +/** + * Called whenever a direct grenade launcher hit on a hunter connects. + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + */ +forward void OnSkeetGL( int survivor, int hunter ); + +/** + * Called whenever a true skeeting sniper headshot landed. + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + */ +forward void OnSkeetSniper( int survivor, int hunter ); + +/** + * Called whenever a pouncing hunter got killed with shotgun + * when it wasn't a true skeet (chipped hunter). + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + * @param int damage damage done in the killing hit + * @param bool isOverKill true if it would've been a skeet if the hunter hadn't been chipped + */ +forward void OnSkeetHurt( int survivor, int hunter, int damage, bool isOverkill ); + +/** + * Called whenever a pouncing hunter got killed with melee + * when it wasn't a true skeet (chipped hunter). + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + * @param int damage damage done in the killing hit + * @param bool isOverKill true if it would've been a skeet if the hunter hadn't been chipped + */ +forward void OnSkeetMeleeHurt( int survivor, int hunter, int damage, bool isOverkill ); + +/** + * Called whenever a pouncing hunter got killed with a sniper headshot + * when it wasn't a true skeet (chipped hunter). + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + * @param int damage damage done in the killing hit + * @param bool isOverKill true if it would've been a skeet if the hunter hadn't been chipped + */ +forward void OnSkeetSniperHurt( int survivor, int hunter, int damage, bool isOverkill ); + +/** + * Called whenever a hunter is deadstopped (pouncing => m2'd). + * + * @param int survivor the survivor client that performed the feat + * @param int hunter the infected client that underwent it + */ +forward void OnHunterDeadstop( int survivor, int hunter ); + +/** + * Called whenever a boomer is killed that didn't land on anyone, + * and didn't explode on anyone either. + * + * @param int survivor the survivor client that killed the boomer + * @param int boomer the infected client that got popped + * @param int shoveCount the amount of times the boomer got shoved, if any + * @param Float timeAlive the time, in seconds, that the boomer lived + */ +forward void OnBoomerPop( int survivor, int oomer, int hoveCount, float timeAlive ); + +/** + * Called whenever a charger is fully melee-leveled (no chip). + * This is also called when the melee hit would've leveled if not chipped! + * + * @param int survivor the survivor client that performed the feat + * @param int charger the infected client that underwent it + */ +forward void OnChargerLevel( int survivor, int charger ); + +/** + * Called whenever a charger is melee-leveled after being chipped. + * Only called when the melee wouldn't have killed an unchipped charger. + * + * @param int survivor the survivor client that performed the feat + * @param int charger the infected client that underwent it + * @param int damage damage done in the killing hit + */ +forward void OnChargerLevelHurt( int survivor, int charger, int damage ); + +/** + * Called whenever a witch was crowned without her being angered first. + * + * @param int survivor the survivor client that performed the feat + * @param int damage damage done in the killing hit + */ +forward void OnWitchCrown( int survivor, int damage ); + +/** + * Called whenever a witch gets crowned after she got angered/triggered. + * This is referred to (depending on the community) as a 'draw crown' or 'remote'. + * + * @param int survivor the survivor client that performed the feat + * @param int damage damage done in the killing hit + * @param int chipdamage damage done to the witch before she got crowned + */ +forward void OnWitchCrownHurt( int survivor, int damage, int chipdamage ); + +/** + * Called whenever a survivor melee-cuts a smoker tongue that was aimed for them. + * + * @param int survivor the survivor client that performed the feat + * @param int smoker the infected client that underwent it + */ +forward void OnTongueCut( int survivor, int smoker ); + +/** + * Called whenever a survivor frees himself from a smoker that grabbed them, + * either by killing it or by shoving. + * + * @param int survivor the survivor client that performed the feat + * @param int smoker the infected client that underwent it + * @param bool withShove true if the self-clear was by a shove/m2 + */ +forward void OnSmokerSelfClear( int survivor, int smoker, bool withShove ); + +/** + * Called whenever a survivor shoots/melees a tank rock out of the air. + * + * Note: the tank param might be unreliable due to the nature of the + * tracking. Don't do anything srs bsns with it. + * + * @param int survivor the survivor client that performed the feat + * @param int tank the infected client that underwent it + */ +forward void OnTankRockSkeeted( int survivor, int tank ); + +/** + * Called whenever a tank lands a rock on a survivor. + * + * Note: the tank param might be unreliable due to the nature of the + * tracking. Don't do anything srs bsns with it. + * + * @param int tank the infected client that performed the feat + * @param int survivor the survivor client that underwent it + */ +forward void OnTankRockEaten( int tank, int survivor ); + +/** + * Called whenever a hunter lands a high-pounce on a survivor. + * + * @param int hunter the infected client that performed the feat + * @param int survivor the survivor client that underwent it + * @param int actualDamage the actual damage the pounce did to the survivor + * @param Float calculatedDamage how much damage (going by pounceannounce parameters) the pounce would be expected to do + * @param Float height the vertical distance between the pounce origin and its landing + * @param bool reportedHigh whether skill_detect considers it a high pounce for reporting purposes + */ +forward void OnHunterHighPounce( int hunter, int survivor, int actualDamage, float calculatedDamage, float height, bool reportedHigh ); + +/** + * Called whenever a jockey lands a high-pounce on a survivor. + * + * Note: due to the nature of the tracking, it only gets the height right if a jockey actually + * jumped or pounced from his perch. If they simple walk off and land, it may be incorrect. + * + * @param int jockey the infected client that performed the feat + * @param int survivor the survivor client that underwent it + * @param Float height the vertical distance between the pounce origin and its landing + * @param bool reportedHigh whether skill_detect considers it a high pounce for reporting purposes + */ +forward void OnJockeyHighPounce( int jockey, int victim, float height, bool reportedHigh ); + +/** + * Called whenever a charger lands a death-charge on a survivor. + * This is called for killing the grabbed survivor, but also the ones that get impact-bumped + * and fall to their deaths. + * + * Note: due to the nature of the tracking, there may be places that are technically death- + * charge spots, but not detected by the plugin. Example: the sidewalk next to the fence near + * the lower roof on Dead Air 1; the Death Toll 4 out-of-map deathcharge near the start + * saferoom. + * + * @param int charger the infected client that performed the feat + * @param int survivor the survivor client that underwent it + * @param Float height the vertical distance between the grab and the survivor's death spot + * @param Float distance the full vector distance between the grab and the survivor's death spot + * @param bool wasCarried true if the survivor was the one that the charger grabbed + */ +forward void OnDeathCharge( int charger, int survivor, float height, float distance, bool wasCarried ); + +/** + * Called whenever a survivor clears a teammate from a special infected pin. + * + * Note: timeB is only appliccable for smokers and chargers. For smokers it shows the + * time from the tongue connecting to the clear. For chargers from the charge-grab to + * the clear. For jockeys and hunters, timeB will always be -1.0. + * + * timeA is the time, for charger, from start of pummeling till clear (-1.0 if they + * never started pummeling). For smokers, this is the time from the survivor being + * fully reigned in to the smoker (-1.0 if the tongue was broken before that). + * + * @param int clearer the survivor client that performed the clear + * @param int pinner the pinning infected client that got cleared (shoved off or killed) + * @param int pinvictim the pinned survivor that was saved + * @param int zombieClass the class (ZC_SMOKER - ZC_CHARGER) of the pinner + * @param Float timeA time from pin till clear in seconds, -1 if never + * @param Float timeB for charger/smoker: time from grab/tongue connect to clear + * @param bool withShove true if the clear was done by shove/m2 + */ +forward void OnSpecialClear( int clearer, int pinner, int pinvictim, int zombieClass, float timeA, float timeB, bool withShove ); + +/** + * Called whenever a boomer is done vomiting, and landed his vomit on one + * or more survivors. + * + * Note: this does not include or fire for boomers exploding, only vomits. + * + * @param int boomer the infected client that performed the feat + * @param int amount the amount of survivors vomited on + */ +forward void OnBoomerVomitLanded( int boomer, int amount ); + +/** + * Called whenever a survivor shoves a special infected (any kind). + * + * @param int survivor the survivor client that performed the feat + * @param int infected the infected client that underwent it + * @param int zombieClass the class type of the infected shoved + */ +forward void OnSpecialShoved( int survivor, int infected, int zombieClass ); + +/** + * Called whenever a survivor lands any number of bunnyhops in a row. Called + * afterwards. + * + * @param int survivor the survivor client that performed the feat + * @param int streak the amount of hops in a row + * @param Float maxVelocity the highest speed during any jump or jump apex + */ +forward void OnBunnyHopStreak( int survivor, int streak, float maxVelocity ); + +/** + * Called whenever a car alarm is triggered (by a survivor). + * + * @param int survivor the survivor client that triggered the alarm (-1 or 0 if unknown) + * @param int infected if > 0: the infected client that assisted in triggering it (boomer, smoker, jockey or charger) + * @param int reason the reason for triggering (see CarAlarmTriggerType) + */ +forward void OnCarAlarmTriggered( int survivor, int infected, CarAlarmTriggerReason reason ); + + +public SharedPlugin __pl_skilldetect = +{ + name = "skill_detect", + file = "l4d2_skill_detect.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + diff --git a/scripting/include/l4d2_usermsg.inc b/scripting/include/l4d2_usermsg.inc new file mode 100644 index 0000000..261db0f --- /dev/null +++ b/scripting/include/l4d2_usermsg.inc @@ -0,0 +1,57 @@ +enum PZDamage_Type { + PZDamage_Killed, //0 + PZDamage_Incapped, + PZDamage_Killed2, //2 + PZDamage_Revived, + PZDamage_Progress, + PZDamage_DestroyedCan, + PZDamage_AssistedAgainst, + PZDamage_HitAssisted, + PZDamage_Hit, + PZDamage_PushedAssisted, + PZDamage_Pushed, + PZDamage_Pounced, + PZDamage_Incapped2, + PZDamage_Saved, + PZDamage_GaveHealth, + PZDamage_GaveAdrendaline, + PZDamage_Protected, + PZDamage_Rescued, + PZDamage_Healed, + PZDamage_EarnedBronze, + PZDamage_EarnedSilver, + PZDamage_EarnedGold +} + +GlobalForward PlayersConnectedForward; +public void InitalizeUserMessageForwards() { + PlayersConnectedForward = CreateGlobalForward("GameStartedAllReady", ET_Ignore); + HookUserMessage(GetUserMessageId("PlayersConnectedForward"), Hook_GameStartedAllReady, false); + +} + +Action Hook_GameStartedAllReady(UserMsg msg_id, BfRead msg, const int[] players, int playersNum, bool reliable, bool init) { + Call_StartForward(PlayersConnectedForward); + Call_Finish(); + return Plugin_Continue; +} + +stock void SendPZDamage(int reciever, PZDamage_Type type, int client, int target = -1) { + Handle msg = StartMessageOne("PZDmgMsg", reciever); + BfWriteByte(msg, view_as(type)); + BfWriteShort(msg, client); + BfWriteShort(msg, target); + BfWriteShort(msg, 0); + BfWriteShort(msg, 0); + EndMessage(); +} + +stock void SendPZDamageToAll(PZDamage_Type type, int client, int target = -1) { + Handle msg = StartMessageAll("PZDmgMsg"); + BfWriteByte(msg, view_as(type)); + BfWriteShort(msg, client); + BfWriteShort(msg, target); + BfWriteShort(msg, 0); + BfWriteShort(msg, 0); + EndMessage(); +} \ No newline at end of file diff --git a/scripting/include/l4d2_weapon_stocks.inc b/scripting/include/l4d2_weapon_stocks.inc new file mode 100644 index 0000000..ba89b64 --- /dev/null +++ b/scripting/include/l4d2_weapon_stocks.inc @@ -0,0 +1,580 @@ +#if defined l4d2_weapons_inc_ + #endinput +#endif +#define l4d2_weapons_inc_ + +// Weapon ID enumerations. +// These values are *NOT* arbitrary! +// They are used in game as the weaponid for weapon_spawn entities +enum WeaponId { + WEPID_NONE, // 0 + WEPID_PISTOL, // 1 + WEPID_SMG, // 2 + WEPID_PUMPSHOTGUN, // 3 + WEPID_AUTOSHOTGUN, // 4 + WEPID_RIFLE, // 5 + WEPID_HUNTING_RIFLE, // 6 + WEPID_SMG_SILENCED, // 7 + WEPID_SHOTGUN_CHROME, // 8 + WEPID_RIFLE_DESERT, // 9 + WEPID_SNIPER_MILITARY, // 10 + WEPID_SHOTGUN_SPAS, // 11 + WEPID_FIRST_AID_KIT, // 12 + WEPID_MOLOTOV, // 13 + WEPID_PIPE_BOMB, // 14 + WEPID_PAIN_PILLS, // 15 + WEPID_GASCAN, // 16 + WEPID_PROPANE_TANK, // 17 + WEPID_OXYGEN_TANK, // 18 + WEPID_MELEE, // 19 + WEPID_GRENADE_LAUNCHER, // 21 + WEPID_AMMO_PACK, // 22 + WEPID_ADRENALINE, // 23 + WEPID_DEFIBRILLATOR, // 24 + WEPID_VOMITJAR, // 25 + WEPID_RIFLE_AK47, // 26 + WEPID_GNOME_CHOMPSKI, // 27 + WEPID_COLA_BOTTLES, // 28 + WEPID_FIREWORKS_BOX, // 29 + WEPID_INCENDIARY_AMMO, // 30 + WEPID_FRAG_AMMO, // 31 + WEPID_PISTOL_MAGNUM, // 32 + WEPID_SMG_MP5, // 33 + WEPID_RIFLE_SG552, // 34 + WEPID_SNIPER_AWP, // 35 + WEPID_SNIPER_SCOUT, // 36 + WEPID_RIFLE_M60, // 37 + WEPID_TANK_CLAW, // 38 + WEPID_HUNTER_CLAW, // 39 + WEPID_CHARGER_CLAW, // 40 + WEPID_BOOMER_CLAW, // 41 + WEPID_SMOKER_CLAW, // 42 + WEPID_SPITTER_CLAW, // 43 + WEPID_JOCKEY_CLAW, // 44 + WEPID_MACHINEGUN, // 45 + WEPID_VOMIT, // 46 + WEPID_SPLAT, // 47 + WEPID_POUNCE, // 48 + WEPID_LOUNGE, // 49 + WEPID_PULL, // 50 + WEPID_CHOKE, // 51 + WEPID_ROCK, // 52 + WEPID_PHYSICS, // 53 + WEPID_AMMO, // 54 + WEPID_UPGRADE_ITEM, // 55 + WEPID_COUNT +}; + +// These values are arbitrary +enum MeleeWeaponId +{ + WEPID_MELEE_NONE, + WEPID_KNIFE, + WEPID_BASEBALL_BAT, + WEPID_CHAINSAW, + WEPID_CRICKET_BAT, + WEPID_CROWBAR, + WEPID_DIDGERIDOO, + WEPID_ELECTRIC_GUITAR, + WEPID_FIREAXE, + WEPID_FRYING_PAN, + WEPID_GOLF_CLUB, + WEPID_KATANA, + WEPID_MACHETE, + WEPID_RIOT_SHIELD, + WEPID_TONFA, + WEPID_MELEE_COUNT +}; + +// Weapon names for each of the weapons, used in identification. +char WeaponNames[56][] = { + "weapon_none", "weapon_pistol", "weapon_smg", // 0 + "weapon_pumpshotgun", "weapon_autoshotgun", "weapon_rifle", // 3 + "weapon_hunting_rifle", "weapon_smg_silenced", "weapon_shotgun_chrome", // 6 + "weapon_rifle_desert", "weapon_sniper_military", "weapon_shotgun_spas", // 9 + "weapon_first_aid_kit", "weapon_molotov", "weapon_pipe_bomb", // 12 + "weapon_pain_pills", "weapon_gascan", "weapon_propanetank", // 15 + "weapon_oxygentank", "weapon_melee", "weapon_chainsaw", // 18 + "weapon_grenade_launcher", "weapon_ammo_pack", "weapon_adrenaline", // 21 + "weapon_defibrillator", "weapon_vomitjar", "weapon_rifle_ak47", // 24 + "weapon_gnome", "weapon_cola_bottles", "weapon_fireworkcrate", // 27 + "weapon_upgradepack_incendiary", "weapon_upgradepack_explosive", "weapon_pistol_magnum", // 30 + "weapon_smg_mp5", "weapon_rifle_sg552", "weapon_sniper_awp", // 33 + "weapon_sniper_scout", "weapon_rifle_m60", "weapon_tank_claw", // 36 + "weapon_hunter_claw", "weapon_charger_claw", "weapon_boomer_claw", // 39 + "weapon_smoker_claw", "weapon_spitter_claw", "weapon_jockey_claw", // 42 + "weapon_machinegun", "vomit", "splat", // 45 + "pounce", "lounge", "pull", // 48 + "choke", "rock", "physics", // 51 + "ammo", "upgrade_item" // 54 +}; + +// Long weapon names +char LongWeaponNames[56][] = { + "None", "Pistol", "Uzi", // 0 + "Pump", "Autoshotgun", "M-16", // 3 + "Hunting Rifle", "Mac", "Chrome", // 6 + "Desert Rifle", "Military Sniper", "SPAS Shotgun", // 9 + "First Aid Kit", "Molotov", "Pipe Bomb", // 12 + "Pills", "Gascan", "Propane Tank", // 15 + "Oxygen Tank", "Melee", "Chainsaw", // 18 + "Grenade Launcher", "Ammo Pack", "Adrenaline", // 21 + "Defibrillator", "Bile Bomb", "AK-47", // 24 + "Gnome", "Cola Bottles", "Fireworks", // 27 + "Incendiary Ammo Pack", "Explosive Ammo Pack", "Deagle", // 30 + "MP5", "SG552", "AWP", // 33 + "Scout", "M60", "Tank Claw", // 36 + "Hunter Claw", "Charger Claw", "Boomer Claw", // 39 + "Smoker Claw", "Spitter Claw", "Jockey Claw", // 42 + "Turret", "vomit", "splat", // 45 + "pounce", "lounge", "pull", // 48 + "choke", "rock", "physics", // 51 + "ammo", "upgrade_item" // 54 +}; + +// Internal names for melee weapons +char MeleeWeaponNames[WEPID_MELEE_COUNT][] = +{ + "", + "knife", + "baseball_bat", + "chainsaw", + "cricket_bat", + "crowbar", + "didgeridoo", + "electric_guitar", + "fireaxe", + "frying_pan", + "golfclub", + "katana", + "machete", + "riotshield", + "tonfa" +}; + +// Long melee weapon names +char LongMeleeWeaponNames[WEPID_MELEE_COUNT][] = +{ + "None", + "Knife", + "Baseball Bat", + "Chainsaw", + "Cricket Bat", + "Crowbar", + "didgeridoo", // derp + "Guitar", + "Axe", + "Frying Pan", + "Golf Club", + "Katana", + "Machete", + "Riot Shield", + "Tonfa" +}; + +// World weapon models for each of the weapons. Useful for making new weapon spawns. +// Some models are left blank because no single model can be given, the model is known or none exist. +char WeaponModels[56][] = { + "", + "/w_models/weapons/w_pistol_B.mdl", + "/w_models/weapons/w_smg_uzi.mdl", + "/w_models/weapons/w_shotgun.mdl", + "/w_models/weapons/w_autoshot_m4super.mdl", + "/w_models/weapons/w_rifle_m16a2.mdl", + "/w_models/weapons/w_sniper_mini14.mdl", + "/w_models/weapons/w_smg_a.mdl", + "/w_models/weapons/w_pumpshotgun_a.mdl", + "/w_models/weapons/w_desert_rifle.mdl", // "/w_models/weapons/w_rifle_b.mdl" + "/w_models/weapons/w_sniper_military.mdl", + "/w_models/weapons/w_shotgun_spas.mdl", + "/w_models/weapons/w_eq_medkit.mdl", + "/w_models/weapons/w_eq_molotov.mdl", + "/w_models/weapons/w_eq_pipebomb.mdl", + "/w_models/weapons/w_eq_painpills.mdl", + "/props_junk/gascan001a.mdl", + "/props_junk/propanecanister001.mdl", + "/props_equipment/oxygentank01.mdl", + "", + "/weapons/melee/w_chainsaw.mdl", + "/w_models/weapons/w_grenade_launcher.mdl", + "", + "/w_models/weapons/w_eq_adrenaline.mdl", + "/w_models/weapons/w_eq_defibrillator.mdl", + "/w_models/weapons/w_eq_bile_flask.mdl", + "/w_models/weapons/w_rifle_ak47.mdl", + "/props_junk/gnome.mdl", + "/w_models/weapons/w_cola.mdl", + "/props_junk/explosive_box001.mdl", + "/w_models/weapons/w_eq_incendiary_ammopack.mdl", + "/w_models/weapons/w_eq_explosive_ammopack.mdl", + "/w_models/weapons/w_desert_eagle.mdl", + "/w_models/weapons/w_smg_mp5.mdl", + "/w_models/weapons/w_rifle_sg552.mdl", + "/w_models/weapons/w_sniper_awp.mdl", + "/w_models/weapons/w_sniper_scout.mdl", + "/w_models/weapons/w_m60.mdl", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" +}; + +char MeleeWeaponModels[15][] = +{ + "", + "/w_models/weapons/w_knife_t.mdl", + "/weapons/melee/w_bat.mdl", + "/weapons/melee/w_chainsaw.mdl", + "/weapons/melee/w_cricket_bat.mdl", + "/weapons/melee/w_crowbar.mdl", + "/weapons/melee/w_didgeridoo.mdl", + "/weapons/melee/w_electric_guitar.mdl", + "/weapons/melee/w_fireaxe.mdl", + "/weapons/melee/w_frying_pan.mdl", + "/weapons/melee/w_golfclub.mdl", + "/weapons/melee/w_katana.mdl", + "/weapons/melee/w_machete.mdl", + "/weapons/melee/w_riotshield.mdl", + "/weapons/melee/w_tonfa.mdl" +}; + +int WeaponSlots[56] = { + -1, // WEPID_NONE + 1, // WEPID_PISTOL + 0, // WEPID_SMG + 0, // WEPID_PUMPSHOTGUN + 0, // WEPID_AUTOSHOTGUN + 0, // WEPID_RIFLE + 0, // WEPID_HUNTING_RIFLE + 0, // WEPID_SMG_SILENCED + 0, // WEPID_SHOTGUN_CHROME + 0, // WEPID_RIFLE_DESERT + 0, // WEPID_SNIPER_MILITARY + 0, // WEPID_SHOTGUN_SPAS + 3, // WEPID_FIRST_AID_KIT + 2, // WEPID_MOLOTOV + 2, // WEPID_PIPE_BOMB + 4, // WEPID_PAIN_PILLS + -1, // WEPID_GASCAN + -1, // WEPID_PROPANE_TANK + -1, // WEPID_OXYGEN_TANK + 1, // WEPID_MELEE + 1, // WEPID_CHAINSAW + 0, // WEPID_GRENADE_LAUNCHER + 3, // WEPID_AMMO_PACK + 4, // WEPID_ADRENALINE + 3, // WEPID_DEFIBRILLATOR + 2, // WEPID_VOMITJAR + 0, // WEPID_RIFLE_AK47 + -1, // WEPID_GNOME_CHOMPSKI + -1, // WEPID_COLA_BOTTLES + -1, // WEPID_FIREWORKS_BOX + 3, // WEPID_INCENDIARY_AMMO + 3, // WEPID_FRAG_AMMO + 1, // WEPID_PISTOL_MAGNUM + 0, // WEPID_SMG_MP5 + 0, // WEPID_RIFLE_SG552 + 0, // WEPID_SNIPER_AWP + 0, // WEPID_SNIPER_SCOUT + 0, // WEPID_RIFLE_M60 + -1, // WEPID_TANK_CLAW + -1, // WEPID_HUNTER_CLAW + -1, // WEPID_CHARGER_CLAW + -1, // WEPID_BOOMER_CLAW + -1, // WEPID_SMOKER_CLAW + -1, // WEPID_SPITTER_CLAW + -1, // WEPID_JOCKEY_CLAW + -1, // WEPID_MACHINEGUN + -1, // WEPID_FATAL_VOMIT + -1, // WEPID_EXPLODING_SPLAT + -1, // WEPID_LUNGE_POUNCE + -1, // WEPID_LOUNGE + -1, // WEPID_FULLPULL + -1, // WEPID_CHOKE + -1, // WEPID_THROWING_ROCK + -1, // WEPID_TURBO_PHYSICS + -1, // WEPID_AMMO + -1 // WEPID_UPGRADE_ITEM +}; + +enum L4D2WeaponSlot +{ + L4D2WeaponSlot_Primary, + L4D2WeaponSlot_Secondary, + L4D2WeaponSlot_Throwable, + L4D2WeaponSlot_HeavyHealthItem, + L4D2WeaponSlot_LightHealthItem +}; + +static Handle hWeaponNamesTrie = INVALID_HANDLE; +static Handle hMeleeWeaponNamesTrie = INVALID_HANDLE; +static Handle hMeleeWeaponModelsTrie = INVALID_HANDLE; + +stock void InitWeaponNamesTrie() { + hWeaponNamesTrie = CreateTrie(); + for(int i = 0; i < view_as(WEPID_COUNT); i++) { + SetTrieValue(hWeaponNamesTrie, WeaponNames[i], i); + } + + hMeleeWeaponNamesTrie = CreateTrie(); + hMeleeWeaponModelsTrie = CreateTrie(); + for (int i = 0; i < view_as(WEPID_MELEE_COUNT); ++i) + { + SetTrieValue(hMeleeWeaponNamesTrie, MeleeWeaponNames[i], i); + SetTrieString(hMeleeWeaponModelsTrie, MeleeWeaponModels[i], MeleeWeaponNames[i]); + } +} + +/** + * Performs bounds checking to determine if a WeaponId is valid + * @remark Simple check to see if wepid has a garbage value + * + * @param wepid WeaponId to check for validity + * @return True if wepid is valid, false otherwise. + */ +stock bool IsValidWeaponId(WeaponId wepid){ + return wepid != WEPID_NONE; +} + +stock bool IsValidMeleeWeaponId(MeleeWeaponId wepid) { + return wepid >= WEPID_MELEE_NONE && wepid < WEPID_MELEE_COUNT; +} + +/** + * Get the player weapon slot used by the given WeaponId. + * + * @param wepid WeaponId to get the slot for. + * @return Slot number (0-4) or -1 for invalid WeaponId or no slot + */ +stock int GetSlotFromWeaponId(WeaponId wepid) { + return IsValidWeaponId(wepid) ? WeaponSlots[wepid] : -1; +} + +/** + * Checks to see if a given weaponid has a known WeaponModel in this file's model array + * @remark Some weapons (like weapon_melee) have multiple valid models, and this will report false for them. + * + * @param wepid WeaponId to check for a known weapon model for. + * @return True if a valid weapon model exists for wepid, false otherwise. + */ +stock bool HasValidWeaponModel(WeaponId wepid) { + return IsValidWeaponId(wepid) && WeaponModels[wepid][0] != '\0'; +} + +stock bool HasValidMeleeWeaponModel(MeleeWeaponId wepid) { + return IsValidMeleeWeaponId(wepid) && MeleeWeaponModels[wepid][0] != '\0'; +} + +/** + * Tries to look up a WeaponId for a given Weapon Name. + * + * @param weaponName Weapon name string to look up Id from + * @return The corresponding WeaponId if found, else WEPID_NONE + */ +stock WeaponId WeaponNameToId(const char[] weaponName) { + int id; + if(hWeaponNamesTrie == INVALID_HANDLE) { + InitWeaponNamesTrie(); + } + if(GetTrieValue(hWeaponNamesTrie, weaponName, id)) { + return view_as(id); + } + return WEPID_NONE; +} + +/** + * Tries to look up L4D2's internal weapon name for a given WeaponId. + * + * @param wepid WeaponId To get name of. + * @param nameBuffer String buffer to write the weapon name to. + * @param length Max length which can be written to the buffer. + * @return Number of bytes written to buffer, or 0 for invalid weaponId. + */ +stock int GetWeaponName(WeaponId wepid, char[] nameBuffer, int length) { + return IsValidWeaponId(wepid) ? strcopy(nameBuffer, length, WeaponNames[wepid]) : 0; +} + +stock int GetMeleeWeaponName(MeleeWeaponId wepid, char[] nameBuffer, int length) { + return IsValidMeleeWeaponId(wepid) ? strcopy(nameBuffer, length, MeleeWeaponNames[wepid]) : 0; +} + +/** + * Tries to look up L4D2's internal weapon name for a given WeaponId. + * + * @param wepid WeaponId To get name of. + * @param nameBuffer String buffer to write the weapon name to. + * @param length Max length which can be written to the buffer. + * @return Number of bytes written to buffer, or 0 for invalid weaponId. + */ +stock int GetLongWeaponName(WeaponId wepid, char[] nameBuffer, int length) { + if(!IsValidWeaponId(wepid)) return 0; + return strcopy(nameBuffer, length, LongWeaponNames[wepid]); +} + +stock int GetLongMeleeWeaponName(MeleeWeaponId wepid, char[] nameBuffer, int length) { + if(!IsValidMeleeWeaponId(wepid)) return 0; + return strcopy(nameBuffer, length, LongMeleeWeaponNames[wepid]); +} + +/** + * Tries to look up the weapon model for a given WeaponId. + * @remarks You should use HasValidWeaponModel to make sure the WeaponId you're looking up has a valid model associated with it. + * + * @param wepid WeaponId To get name of. + * @param nameBuffer String buffer to write the weapon name to. + * @param length Max length which can be written to the buffer. + * @return Number of bytes written to buffer, or 0 for invalid weaponid or no weapon model available. + */ +stock int GetWeaponModel(WeaponId wepid, char[] modelBuffer, int length) { + if(!HasValidWeaponModel(wepid)) return 0; + return strcopy(modelBuffer, length, WeaponModels[wepid]); +} + +stock int GetMeleeWeaponModel(MeleeWeaponId wepid, char[] modelBuffer, int length) { + if(!HasValidMeleeWeaponModel(wepid)) return 0; + return strcopy(modelBuffer, length, MeleeWeaponModels[wepid]); +} + +/** + * Identifies a weapon spawn or weapon entity as a WeaponID + * @remark Should work on most weapon ents--even spawns, singles, held, etc. + * + * @param entity Index of entity to identify + * @return WeaponID for the entity if it is a weapon, WEPID_NONE otherwise + */ +stock WeaponId IdentifyWeapon(int entity) { + if(!entity || !IsValidEntity(entity) || !IsValidEdict(entity)) { + return WEPID_NONE; + } + static char class[64]; + if(!GetEdictClassname(entity, class, sizeof(class))) { + return WEPID_NONE; + } + + if(StrEqual(class, "weapon_spawn")) { + return view_as(GetEntProp(entity ,Prop_Send, "m_weaponID")); + } + + int len = strlen(class); + if(len-6 > 0 && StrEqual(class[len-6], "_spawn")) { + class[len-6]='\0'; + return WeaponNameToId(class); + } + + return WeaponNameToId(class); +} + +// Helper function used for getting an entity's internal melee name +stock bool GetMeleeWeaponNameFromEntity(int entity, char[] buffer, int length) { + static char classname[64]; + if (!GetEdictClassname(entity, classname, sizeof(classname))) { + return false; + } + + if (StrEqual(classname, "weapon_melee_spawn")) { + if (hMeleeWeaponModelsTrie == INVALID_HANDLE) { + InitWeaponNamesTrie(); + } + + static char sModelName[128]; + GetEntPropString(entity, Prop_Data, "m_ModelName", sModelName, sizeof(sModelName)); + + // Strip models directory + if (strncmp(sModelName, "models/", 7, false) == 0) { + strcopy(sModelName, sizeof(sModelName), sModelName[6]); + } + + return GetTrieString(hMeleeWeaponModelsTrie, sModelName, buffer, length) + } else if (StrEqual(classname, "weapon_melee")) { + GetEntPropString(entity, Prop_Data, "m_strMapSetScriptName", buffer, length); + return true; + } + return false; +} + +/** + * Identifies a melee weapon spawn or weapon entity as a MeleeWeaponId + * @remark Should work on most weapon ents--even spawns, singles, held, etc. + * + * @param entity Index of entity to identify + * @return MeleeWeaponId for the entity if it is a weapon, WEPID_MELEE_NONE otherwise + */ +stock MeleeWeaponId IdentifyMeleeWeapon(int entity) { + if (IdentifyWeapon(entity) != WEPID_MELEE) { + return WEPID_MELEE_NONE; + } + + static char sName[128]; + if (! GetMeleeWeaponNameFromEntity(entity, sName, sizeof(sName))) { + return WEPID_MELEE_NONE; + } + + if (hMeleeWeaponNamesTrie == INVALID_HANDLE) { + InitWeaponNamesTrie(); + } + + int id; + if(GetTrieValue(hMeleeWeaponNamesTrie, sName, id)) { + return view_as(id); + } + return WEPID_MELEE_NONE; +} + +/** + * Attempts to convert a weapon spawn entity to a given weapon spawn + * @remark Truthfully, this will work on any entity with origin/rotation. + * Also, requires the weapon to either have a Valid weapon model or have one provided + * + * @param entity Index of entity to convert to weapon spawn + * @param wepid WeaponId of the weapon to have the spawner hold + * @param count Weapon count for the spawner (default 5) + * @param model World model to use for the weapon spawn + * @return entity of the new weapon spawn, or -1 on errors. + */ +stock int ConvertWeaponSpawn(int entity, WeaponId wepid, int count = 5, const char[] model = "") +{ + if(!IsValidEntity(entity)) return -1; + if(!IsValidWeaponId(wepid)) return -1; + if(model[0] == '\0' && !HasValidWeaponModel(wepid)) return -1; + + + float origins[3], angles[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", origins); + GetEntPropVector(entity, Prop_Send, "m_angRotation", angles); + + AcceptEntityInput(entity, "kill"); + + entity = CreateEntityByName("weapon_spawn"); + if(!IsValidEntity(entity)) return -1; + + SetEntProp(entity, Prop_Send, "m_weaponID", wepid); + + char buf[64]; + if(model[0] == '\0') { + SetEntityModel(entity, model); + } else { + GetWeaponModel(wepid, buf, sizeof(buf)); + SetEntityModel(entity, buf); + } + IntToString(count, buf, sizeof(buf)); + DispatchKeyValue(entity, "count", buf); + + TeleportEntity(entity, origins, angles, NULL_VECTOR); + DispatchSpawn(entity); + SetEntityMoveType(entity,MOVETYPE_NONE); + return entity; +} diff --git a/scripting/include/l4d2_weapons.inc b/scripting/include/l4d2_weapons.inc new file mode 100644 index 0000000..f39af4d --- /dev/null +++ b/scripting/include/l4d2_weapons.inc @@ -0,0 +1,71 @@ +const char WEAPON_GUN_GROUPS = [][] { + "rifle", + "sniper", + "smg", + "shotgun" +} +enum WEAPON_TYPES { + Weapon_Rifle, + Weapon_Sniper, + Weapon_SMG, + Weapon_Shotgun +} + +const char WEAPONS_RIFLE = [] + + +stock bool IsPrimaryWeapon(const char[] wpnName) { + return StrContains(wpnName, "rifle") > -1 + || StrContains(wpnName, "smg") > -1 + || StrContains(wpnName, "weapon_grenade_launcher") > -1 + || StrContains(wpnName, "sniper") > -1 + || StrContains(wpnName, "shotgun") > -1; +} +stock int GetClientWeaponEntIndex(int client, int slot) { + if(slot >= 0 && slot <= 4) { + int wpnRef = GetPlayerWeaponSlot(client, slot); + if(wpnRef != -1) { + int wpn = EntRefToEntIndex(wpnRef); + if(wpn != INVALID_ENT_REFERENCE) { + return wpn; + }else{ + return -1; + } + }else{ + return -1; + } + }else{ + return -1; + } +} +stock int GetClientSecondaryWeapon(int client) { + return GetClientWeaponEntIndex(client, 1); +} +stock bool GetClientWeaponName(int client, int slot, char[] name, int nameSize) { + int wpn = GetClientWeaponEntIndex(client, slot); + if(wpn > -1) { + GetEntityClassname(wpn, name, nameSize); + return true; + }else{ + return false; + } +} +stock bool DoesClientHaveWeapon(int client, int slot, const char[] name) { + char wpn[32]; + if(GetClientWeaponName(client, slot, wpn, sizeof(wpn))) { + return StrEqual(wpn, name, false); + }else{ + return false; + } +} + +stock bool DoesClientHaveMelee(int client) { + int wpnEnt = GetClientSecondaryWeapon(client); + if(wpnEnt > -1) { + char wpn[16]; + GetEdictClassname(wpnEnt, wpn, sizeof(wpn)); + return StrEqual(wpn, "weapon_melee"); + }else{ + return false; + } +} \ No newline at end of file diff --git a/scripting/include/l4d2hud.inc b/scripting/include/l4d2hud.inc new file mode 100644 index 0000000..6977e4b --- /dev/null +++ b/scripting/include/l4d2hud.inc @@ -0,0 +1,218 @@ +//Sourcemod Wrapper around the L4D2 EMS Hud System +//Created by https://github.com/Jackzmc +//See it here: https://github.com/Jackzmc/sourcemod-plugins/blob/master/scripting/include/l4d2hud.inc + +enum hudPosition { + HUD_POSITION_FAR_LEFT, + HUD_POSITION_FAR_RIGHT, + HUD_POSITION_RIGHT_TOP, + HUD_POSITION_RIGHT_BOT, + HUD_POSITION_MID_TOP, + HUD_POSITION_MID_BOT, + HUD_POSITION_LEFT_TOP, + HUD_POSITION_LEFT_BOT, + HUD_POSITION_TICKER, + HUD_POSITION_MID_BOX, + HUD_POSITION_SCORE_TITLE, + HUD_POSITION_SCORE_1, + HUD_POSITION_SCORE_2, + HUD_POSITION_SCORE_3, + HUD_POSITION_SCORE_4 +}; + +char hudPositions[17][] = { + "FAR_LEFT", + "RIGHT_TOP", + "RIGHT_BOT", + "MID_TOP", + "MID_BOT", + "SCORE_3", + "LEFT_TOP", + "LEFT_BOT", + "TICKER", + "MID_BOX", + "FAR_LEFT", + "FAR_RIGHT", + "SCORE_TITLE", + "SCORE_1", + "SCORE_2", + "SCORE_3", + "SCORE_4" +}; + +enum hudFlag { + HUD_FLAG_PRESTR = 1, + HUD_FLAG_POSTSTR = 2, + HUD_FLAG_BEEP = 4, + HUD_FLAG_BLINK = 8, + HUD_FLAG_COUNTDOWN_WARN = 16, + HUD_FLAG_NOBG = 32, + HUD_FLAG_ALLOWNEGTIMER = 64, + HUD_FLAG_SHOW_TIME = 128, + HUD_FLAG_NOTVISIBLE = 256, + HUD_FLAG_ALIGN_LEFT = 512, + HUD_FLAG_ALIGN_CENTER = 1024, + HUD_FLAG_ALIGN_RIGHT = 2048, + HUD_FLAG_TEAM_SURVIVORS = 4096, + HUD_FLAG_TEAM_INFECTED = 8192, + HUD_FLAG_AS_TIME = 16384, + HUD_FLAG_TEAM_MASK = 32768 +}; + +char hudFlags[16][16] = { + "PRESTR", + "POSTSTR", + "BEEP", + "BLINK", + "COUNTDOWN_WARN", + "NOBG", + "ALLOWNEGTIMER", + "SHOW_TIME", + "NOTVISIBLE", + "ALIGN_LEFT", + "ALIGN_CENTER", + "ALIGN_RIGHT", + "TEAM_SURVIVORS", + "TEAM_INFECTED", + "AS_TIME", + "TEAM_MASK", +}; + +char huds[15][1024]; + +void SetupHUD(hudPosition position, int flags, float x, float y, float w, float h) { + if(x > 1.0 || x < 0.0) { + ThrowError("HUD X Coordinate must be between 0.0 - 1.0"); + }else if(y > 1.0 || y < 0.0) { + ThrowError("HUD Y Coordinate must be between 0.0 - 1.0"); + }else if(w > 1.0 || w < 0.0) { + ThrowError("HUD Width must be between 0.0 - 1.0"); + }else if(h > 1.0 || h < 0.0) { + ThrowError("HUD Height must be between 0.0 - 1.0"); + } + + char buffer[256]; + if(flags > 0) { + ArrayList flagStrings = new ArrayList(ByteCountToCells(16)); + + for(int i = 0; i < sizeof(hudFlags); i++) { + int flag = RoundFloat(Pow(2.0, float(i))); + if(flags & flag == flag) { + flagStrings.PushString(hudFlags[i]); + } + } + + + char flagBuffer[16]; + for(int i = 0; i < flagStrings.Length; i++) { + flagStrings.GetString(i, flagBuffer, sizeof(flagBuffer)); + PrintToServer("flag[%d] = %s", i, flagBuffer); + if(i == flagStrings.Length - 1) { + Format(buffer, sizeof(buffer), "%s g_ModeScript.HUD_FLAG_%s", buffer, flagBuffer); + } else { + Format(buffer, sizeof(buffer), "%s g_ModeScript.HUD_FLAG_%s |", buffer, flagBuffer); + } + } + delete flagStrings; + + Format(buffer, sizeof(buffer), "flags = %s,", buffer); + } + + + int id = view_as(position); + Format(huds[id], 1024, "SMHud%d <- { Fields = { players = { slot = g_ModeScript.HUD_%s, dataval = \"%%s\", %s name = \"smhud%d\" } } }; HUDSetLayout( SMHud%d ); HUDPlace( g_ModeScript.HUD_%s, %f, %f, %f, %f )", id, hudPositions[id], buffer, id, id, hudPositions[id], x, y, w, h); + L4D2_RunScript(huds[id], ""); +} + +void SetHUDText(hudPosition position, const char[] format, any ...) { + if(huds[view_as(position)][0] == '\0') { + ThrowError("HUD at position was not setup."); + } + static char sBuffer[1024]; + VFormat(sBuffer, sizeof(sBuffer), format, 3); + + L4D2_RunScript(huds[view_as(position)], sBuffer); +} + +bool IsHUDSetup(hudPosition position) { + return huds[view_as(position)][0] != '\0'; +} + +void DeleteHUD(hudPosition position) { + L4D2_RunVScript("SMHud%d <- { Fields = { } }; HUDSetLayout(SMHud%d); HUDPlace( g_ModeScript.HUD_%s, 0.0, 0.0, 0.0, 0.0 ); g_ModeScript", view_as(position), view_as(position), hudPositions[positions]); + huds[view_as(position)][0] = '\0'; +} + +void GetHUDFormatString(hudPosition position, char[] buffer, int buffersize) { + strcopy(buffer, buffersize, huds[view_as(position)]); +} + +#define MAX_MESSAGES 6 +#define MESSAGE_DURATION 40 +#define MAX_MESSAGE_LENGTH 64 +#define MESSAGE_UPDATE_INTERVAL 0.8 +//This is hard coded into engine: +#define MAX_HUD_LENGTH 1023 + +hudPosition MSG_HUD_POS; + +char messages[MAX_MESSAGES][MAX_MESSAGE_LENGTH]; +char lastMsgFull[]; +int msgExpiresTime; +Handle msgTimer; + +void SetupMessageHud(hudPosition position) { + MSG_HUD_POS = position; + SetupHUD(MSG_HUD_POS, HUD_FLAG_ALIGN_LEFT | HUD_FLAG_NOBG | HUD_FLAG_TEAM_SURVIVORS, 0.0, 0.0, 1.0, 1.0); + msgTimer = CreateTimer(MESSAGE_UPDATE_INTERVAL, Timer_ProcessMessages, _, TIMER_REPEAT); +} + +void CloseMessageHud() { + if(msgTimer != null) + CloseHandle(msgTimer); + ClearMessages(); +} +//TODO: Replace repeat timer, just use one-time delay, only add one +//Internally process and print all messages +void Timer_ProcessMessages(Handle h) { + if(GetGameTime() > msgExpiresTime) { + messages.Erase(0); + msgExpiresTime = GetGameTime() + MESSAGE_DURATION; + } + char buffer[MAX_HUD_LENGTH]; + for(int i = 0; i < messages.Length; i++) { + ImplodeStrings(messages, MAX_MESSAGES, "\\n", buffer, sizeof(buffer)); + } + SetHUDText(MSG_HUD_POS, buffer); +} + +//Adds a message to the message queue +void AddMessageToHud(const char msg[MAX_MESSAGE_LENGTH]) { + for(int i = 1; i < MAX_MESSAGES - 1; i++) { + strcopy(messages[i], MAX_MESSAGE_LENGTH, messages[i+1]); + } + strcopy(messages[MAX_MESSAGES-1], MAX_MESSAGE_LENGTH, msg); +} +//Clears all messages +void ClearMessageHud() { + for(int i = 0; i < MAX_MESSAGES; i++) { + messages[i][0] = '\0'; + } +} + +stock void L4D2_RunVScript(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} \ No newline at end of file diff --git a/scripting/include/l4d_anti_rush.inc b/scripting/include/l4d_anti_rush.inc new file mode 100644 index 0000000..81eea9e --- /dev/null +++ b/scripting/include/l4d_anti_rush.inc @@ -0,0 +1 @@ +forward Action OnAntiRush(int client, int &type, float distance); \ No newline at end of file diff --git a/scripting/include/l4d_info_editor.inc b/scripting/include/l4d_info_editor.inc new file mode 100644 index 0000000..0bce55b --- /dev/null +++ b/scripting/include/l4d_info_editor.inc @@ -0,0 +1,54 @@ +#if defined _info_editor_included + #endinput +#endif +#define _info_editor_included + + + +/** + * Retrieves the value of a specified key from the games mission info keyvalue system. "N/A" is returned when not found. + * + * @param pThis Enter the pThis value from OnGetMissionInfo/OnGetWeaponsInfo. Can specify 0 when reading Mission data. + * @param keyname Key name to check. + * @param dest Destination string buffer to copy to. + * @param destLen Destination buffer length (includes null terminator). + * + * @noreturn + */ +native void InfoEditor_GetString(int pThis, const char[] keyname, char[] dest, int destLen); + +/** + * Sets the value of a specified key from the games mission info keyvalue system. + * + * @param pThis Enter the pThis value from OnGetMissionInfo/OnGetWeaponsInfo. Can specify 0 when writing Mission data. + * @param keyname Key name to set. + * @param value Value to set. + * @param create Optionally create the keyvalue if it doesn't exist. + * + * @noreturn + */ +native void InfoEditor_SetString(int pThis, const char[] keyname, const char[] value, bool create = false); + +/** + * Reloads the mission and weapons data configs and forces the game to reload them. + * + * @noreturn + */ +native void InfoEditor_ReloadData(); + + + +/** + * @brief Fired multiple times when the mission info data is parsed. + * + * @param pThis This pointer used for InfoEditor_GetString/InfoEditor_SetString. + */ +forward void OnGetMissionInfo(int pThis); + +/** + * Fired multiple times when the weapon info data is parsed for a specific weapon classname. + * + * @param pThis This pointer used for InfoEditor_GetString/InfoEditor_SetString. + * @param classname Classname of the weapon being parsed. + */ +forward void OnGetWeaponsInfo(int pThis, const char[] classname); \ No newline at end of file diff --git a/scripting/include/l4d_survivor_identity_fix.inc b/scripting/include/l4d_survivor_identity_fix.inc new file mode 100644 index 0000000..53802f5 --- /dev/null +++ b/scripting/include/l4d_survivor_identity_fix.inc @@ -0,0 +1,27 @@ +enum Character { + Character_Nick, + Character_Ellis, + Character_Rochelle, + Character_Coach, + Character_Bill, + Character_Francis, + Character_Zoey, + Character_Louis +} +native int IdentityFix_SetPlayerModel(int client, int args, bool keep = false); + + +static bool nativeAvailable, nativeTested; +bool UpdatePlayerIdentity(int client, Character character, bool keep = false) { + if(!nativeTested) { + nativeTested = true; + nativeAvailable = GetFeatureStatus(FeatureType_Native, "IdentityFix_SetPlayerModel") == FeatureStatus_Available; + } + if(nativeAvailable) { + int result = IdentityFix_SetPlayerModel(client, view_as(character), keep); + return result == 0; + }else{ + return false; + } +} + diff --git a/scripting/include/left4dhooks.inc b/scripting/include/left4dhooks.inc new file mode 100644 index 0000000..5f9d215 --- /dev/null +++ b/scripting/include/left4dhooks.inc @@ -0,0 +1,6193 @@ +/** + * vim set ts=4 + * ============================================================================= + * + * Left 4 Downtown 2 SourceMod Extension + * Copyright (C) 2010 Michael "ProdigySim" Busby + * + * Left 4 Downtown SourceMod Extension + * Copyright (C) 2009 Igor "Downtown1" Smirnov + * + * Left 4 Downtown 2 Extension updates + * Copyright (C) 2012-2015 "Visor" + * + * Left 4 Downtown 2 Extension updates + * Copyright (C) 2015 "Attano" + * + * Left 4 Downtown 2 Extension updates + * Copyright (C) 2017 "Accelerator74" + * + * Left 4 DHooks Direct SourceMod plugin + * Copyright (C) 2023 "SilverShot" / "Silvers" + * + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + * + * Version $Id$ + */ + +#if defined _l4dh_included + #endinput +#endif +#define _l4dh_included + +#include +#include +#include +#include + + + +// Natives: 256 (including 3 for L4D1 only) +// L4D1 = 31 [left4downtown] + 47 [l4d_direct] + 16 [l4d2addresses] + 61 [silvers - mine!] + 4 [anim] = 159 +// L4D2 = 61 [left4downtown] + 59 [l4d_direct] + 31 [l4d2addresses] + 98 [silvers - mine!] + 4 [anim] = 253 + +// Forwards: 195 (including 5 for L4D1 only) +// L4D1 = 135 +// L4D2 = 190 + +// Stocks: 169 (L4D1 = 112, L4D2 = 165) +// left4dhooks_silver 46 stocks (L4D1 = 39, L4D2 = 53) +// left4dhooks_stocks 83 stocks (L4D1 = 44, L4D2 = 79) +// left4dhooks_lux_library 34 stocks (L4D1 = 30, L4D2 = 34) + + + + + +public SharedPlugin __pl_l4dh = +{ + name = "left4dhooks", + file = "left4dhooks.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_l4dh_SetNTVOptional() +{ + // ========================= + // Silvers Natives + // ========================= + MarkNativeAsOptional("AnimHookEnable"); + MarkNativeAsOptional("AnimHookDisable"); + MarkNativeAsOptional("AnimGetActivity"); + MarkNativeAsOptional("AnimGetFromActivity"); + + MarkNativeAsOptional("L4D_GetGameModeType"); + MarkNativeAsOptional("L4D_Deafen"); + MarkNativeAsOptional("L4D_GetTempHealth"); + MarkNativeAsOptional("L4D_SetTempHealth"); + MarkNativeAsOptional("L4D_GetReserveAmmo"); + MarkNativeAsOptional("L4D_SetReserveAmmo"); + MarkNativeAsOptional("L4D_PlayMusic"); + MarkNativeAsOptional("L4D_StopMusic"); + MarkNativeAsOptional("L4D_Dissolve"); + MarkNativeAsOptional("L4D_OnITExpired"); + MarkNativeAsOptional("L4D_EstimateFallingDamage"); + MarkNativeAsOptional("L4D_GetEntityWorldSpaceCenter"); + MarkNativeAsOptional("L4D_AngularVelocity"); + MarkNativeAsOptional("L4D_GetRandomPZSpawnPosition"); + MarkNativeAsOptional("L4D_GetNearestNavArea"); + MarkNativeAsOptional("L4D_GetLastKnownArea"); + MarkNativeAsOptional("L4D2_GetFurthestSurvivorFlow"); + MarkNativeAsOptional("L4D2_GetFirstSpawnClass"); + MarkNativeAsOptional("L4D2_SetFirstSpawnClass"); + MarkNativeAsOptional("L4D_FindRandomSpot"); + MarkNativeAsOptional("L4D2_IsVisibleToPlayer"); + MarkNativeAsOptional("L4D_HasAnySurvivorLeftSafeArea"); + MarkNativeAsOptional("L4D_IsAnySurvivorInStartArea"); + MarkNativeAsOptional("L4D_IsAnySurvivorInCheckpoint"); + MarkNativeAsOptional("L4D_AreAllSurvivorsInFinaleArea"); + MarkNativeAsOptional("L4D_IsInFirstCheckpoint"); + MarkNativeAsOptional("L4D_IsInLastCheckpoint"); + MarkNativeAsOptional("L4D_IsPositionInFirstCheckpoint"); + MarkNativeAsOptional("L4D_IsPositionInLastCheckpoint"); + MarkNativeAsOptional("L4D_GetCheckpointFirst"); + MarkNativeAsOptional("L4D_GetCheckpointLast"); + MarkNativeAsOptional("L4D2_IsReachable"); + MarkNativeAsOptional("L4D_HasPlayerControlledZombies"); + MarkNativeAsOptional("L4D_DetonateProjectile"); + MarkNativeAsOptional("L4D_TankRockPrj"); + MarkNativeAsOptional("L4D_PipeBombPrj"); + MarkNativeAsOptional("L4D_MolotovPrj"); + MarkNativeAsOptional("L4D2_VomitJarPrj"); + MarkNativeAsOptional("L4D2_GrenadeLauncherPrj"); + + MarkNativeAsOptional("L4D_GetPointer"); + MarkNativeAsOptional("L4D_GetClientFromAddress"); + MarkNativeAsOptional("L4D_GetEntityFromAddress"); + MarkNativeAsOptional("L4D_ReadMemoryString"); + MarkNativeAsOptional("L4D_GetServerOS"); + MarkNativeAsOptional("Left4DHooks_Version"); + MarkNativeAsOptional("L4D2_GetScriptScope"); + MarkNativeAsOptional("L4D2_GetVScriptEntity"); + MarkNativeAsOptional("L4D2_ExecVScriptCode"); + MarkNativeAsOptional("L4D2_GetVScriptOutput"); + MarkNativeAsOptional("L4D2_SpitterPrj"); + MarkNativeAsOptional("L4D2_UseAdrenaline"); + MarkNativeAsOptional("L4D_RespawnPlayer"); + MarkNativeAsOptional("L4D_SetHumanSpec"); + MarkNativeAsOptional("L4D_TakeOverBot"); + MarkNativeAsOptional("L4D_CanBecomeGhost"); + MarkNativeAsOptional("L4D_SetBecomeGhostAt"); + MarkNativeAsOptional("L4D2_AreWanderersAllowed"); + MarkNativeAsOptional("L4D2_GetCurrentFinaleStage"); + MarkNativeAsOptional("L4D2_ForceNextStage"); + MarkNativeAsOptional("L4D_ForceVersusStart"); + MarkNativeAsOptional("L4D_ForceSurvivalStart"); + MarkNativeAsOptional("L4D2_ForceScavengeStart"); + MarkNativeAsOptional("L4D2_IsTankInPlay"); + MarkNativeAsOptional("L4D2_GetDirectorScriptScope"); + MarkNativeAsOptional("L4D2_GetScriptValueInt"); + MarkNativeAsOptional("L4D2_GetScriptValueFloat"); + // MarkNativeAsOptional("L4D2_GetScriptValueString"); + MarkNativeAsOptional("L4D2_NavAreaTravelDistance"); + MarkNativeAsOptional("L4D2_NavAreaBuildPath"); + MarkNativeAsOptional("L4D2_CommandABot"); + MarkNativeAsOptional("L4D2_GetSurvivorSetMod"); + MarkNativeAsOptional("L4D2_GetSurvivorSetMap"); + MarkNativeAsOptional("L4D2_HasConfigurableDifficultySetting"); + MarkNativeAsOptional("L4D2_IsGenericCooperativeMode"); + MarkNativeAsOptional("L4D_IsFinaleEscapeInProgress"); + MarkNativeAsOptional("L4D_IsCoopMode"); + MarkNativeAsOptional("L4D2_IsRealismMode"); + MarkNativeAsOptional("L4D_IsSurvivalMode"); + MarkNativeAsOptional("L4D2_IsScavengeMode"); + MarkNativeAsOptional("L4D_IsVersusMode"); + + MarkNativeAsOptional("L4D2_VScriptWrapper_GetMapNumber"); + MarkNativeAsOptional("L4D2_VScriptWrapper_HasEverBeenInjured"); + MarkNativeAsOptional("L4D2_VScriptWrapper_GetAliveDuration"); + MarkNativeAsOptional("L4D2_VScriptWrapper_IsDead"); + MarkNativeAsOptional("L4D2_VScriptWrapper_IsDying"); + MarkNativeAsOptional("L4D2_VScriptWrapper_UseAdrenaline"); + MarkNativeAsOptional("L4D2_VScriptWrapper_ReviveByDefib"); + MarkNativeAsOptional("L4D2_VScriptWrapper_ReviveFromIncap"); + MarkNativeAsOptional("L4D2_VScriptWrapper_GetSenseFlags"); + MarkNativeAsOptional("L4D2_VScriptWrapper_NavAreaBuildPath"); + MarkNativeAsOptional("L4D2_VScriptWrapper_NavAreaTravelDistance"); + + + + // ========================= + // left4downtown.inc + // ========================= + MarkNativeAsOptional("L4D_RestartScenarioFromVote"); + MarkNativeAsOptional("L4D_IsFirstMapInScenario"); + MarkNativeAsOptional("L4D_IsMissionFinalMap"); + MarkNativeAsOptional("L4D_NotifyNetworkStateChanged"); + MarkNativeAsOptional("L4D_StaggerPlayer"); + MarkNativeAsOptional("L4D2_SendInRescueVehicle"); + MarkNativeAsOptional("L4D_ReplaceTank"); + MarkNativeAsOptional("L4D2_SpawnTank"); + MarkNativeAsOptional("L4D2_SpawnSpecial"); + MarkNativeAsOptional("L4D2_SpawnWitch"); + MarkNativeAsOptional("L4D2_GetTankCount"); + MarkNativeAsOptional("L4D2_GetWitchCount"); + MarkNativeAsOptional("L4D_GetCurrentChapter"); + MarkNativeAsOptional("L4D_GetMaxChapters"); + MarkNativeAsOptional("L4D_GetAllNavAreas"); + MarkNativeAsOptional("L4D_GetNavAreaID"); + MarkNativeAsOptional("L4D_GetNavAreaByID"); + MarkNativeAsOptional("L4D_GetNavAreaPos"); + MarkNativeAsOptional("L4D_GetNavAreaCenter"); + MarkNativeAsOptional("L4D_GetNavAreaSize"); + MarkNativeAsOptional("L4D_NavArea_IsConnected"); + MarkNativeAsOptional("L4D_GetNavArea_SpawnAttributes"); + MarkNativeAsOptional("L4D_SetNavArea_SpawnAttributes"); + MarkNativeAsOptional("L4D_GetNavArea_AttributeFlags"); + MarkNativeAsOptional("L4D_SetNavArea_AttributeFlags"); + + MarkNativeAsOptional("L4D_ScavengeBeginRoundSetupTime"); + MarkNativeAsOptional("L4D_ResetMobTimer"); + MarkNativeAsOptional("L4D_GetPlayerSpawnTime"); + MarkNativeAsOptional("L4D_SetPlayerSpawnTime"); + MarkNativeAsOptional("L4D_GetVersusMaxCompletionScore"); + MarkNativeAsOptional("L4D_SetVersusMaxCompletionScore"); + MarkNativeAsOptional("L4D_GetTeamScore"); + MarkNativeAsOptional("L4D_GetMobSpawnTimerRemaining"); + MarkNativeAsOptional("L4D_GetMobSpawnTimerDuration"); + MarkNativeAsOptional("L4D2_ChangeFinaleStage"); + MarkNativeAsOptional("L4D2_SpawnWitchBride"); + MarkNativeAsOptional("L4D_LobbyUnreserve"); + MarkNativeAsOptional("L4D_LobbyIsReserved"); + MarkNativeAsOptional("L4D_GetLobbyReservation"); + MarkNativeAsOptional("L4D_SetLobbyReservation"); + + // l4d2weapons.inc + MarkNativeAsOptional("L4D_GetWeaponID"); + MarkNativeAsOptional("L4D2_IsValidWeapon"); + MarkNativeAsOptional("L4D2_GetIntWeaponAttribute"); + MarkNativeAsOptional("L4D2_GetFloatWeaponAttribute"); + MarkNativeAsOptional("L4D2_SetIntWeaponAttribute"); + MarkNativeAsOptional("L4D2_SetFloatWeaponAttribute"); + MarkNativeAsOptional("L4D2_GetMeleeWeaponIndex"); + MarkNativeAsOptional("L4D2_GetIntMeleeAttribute"); + MarkNativeAsOptional("L4D2_GetFloatMeleeAttribute"); + MarkNativeAsOptional("L4D2_GetBoolMeleeAttribute"); + MarkNativeAsOptional("L4D2_SetIntMeleeAttribute"); + MarkNativeAsOptional("L4D2_SetFloatMeleeAttribute"); + MarkNativeAsOptional("L4D2_SetBoolMeleeAttribute"); + + // l4d2timers.inc + MarkNativeAsOptional("L4D2_CTimerReset"); + MarkNativeAsOptional("L4D2_CTimerStart"); + MarkNativeAsOptional("L4D2_CTimerInvalidate"); + MarkNativeAsOptional("L4D2_CTimerHasStarted"); + MarkNativeAsOptional("L4D2_CTimerIsElapsed"); + MarkNativeAsOptional("L4D2_CTimerGetElapsedTime"); + MarkNativeAsOptional("L4D2_CTimerGetRemainingTime"); + MarkNativeAsOptional("L4D2_CTimerGetCountdownDuration"); + MarkNativeAsOptional("L4D2_ITimerStart"); + MarkNativeAsOptional("L4D2_ITimerInvalidate"); + MarkNativeAsOptional("L4D2_ITimerHasStarted"); + MarkNativeAsOptional("L4D2_ITimerGetElapsedTime"); + + // l4d2director.inc + MarkNativeAsOptional("L4D2_GetVersusCampaignScores"); + MarkNativeAsOptional("L4D2_SetVersusCampaignScores"); + MarkNativeAsOptional("L4D2_GetVersusTankFlowPercent"); + MarkNativeAsOptional("L4D2_SetVersusTankFlowPercent"); + MarkNativeAsOptional("L4D2_GetVersusWitchFlowPercent"); + MarkNativeAsOptional("L4D2_SetVersusWitchFlowPercent"); + + + + // ========================= + // l4d2_direct.inc + // ========================= + MarkNativeAsOptional("L4D2Direct_GetPendingMobCount"); + MarkNativeAsOptional("L4D2Direct_SetPendingMobCount"); + MarkNativeAsOptional("L4D2Direct_GetTankPassedCount"); + MarkNativeAsOptional("L4D2Direct_SetTankPassedCount"); + MarkNativeAsOptional("L4D2Direct_GetVSCampaignScore"); + MarkNativeAsOptional("L4D2Direct_SetVSCampaignScore"); + MarkNativeAsOptional("L4D2Direct_GetVSTankFlowPercent"); + MarkNativeAsOptional("L4D2Direct_SetVSTankFlowPercent"); + MarkNativeAsOptional("L4D2Direct_GetVSTankToSpawnThisRound"); + MarkNativeAsOptional("L4D2Direct_SetVSTankToSpawnThisRound"); + MarkNativeAsOptional("L4D2Direct_GetVSWitchFlowPercent"); + MarkNativeAsOptional("L4D2Direct_SetVSWitchFlowPercent"); + MarkNativeAsOptional("L4D2Direct_GetVSWitchToSpawnThisRound"); + MarkNativeAsOptional("L4D2Direct_SetVSWitchToSpawnThisRound"); + MarkNativeAsOptional("L4D2Direct_GetMapMaxFlowDistance"); + MarkNativeAsOptional("L4D2Direct_GetInvulnerabilityTimer"); + MarkNativeAsOptional("L4D2Direct_GetTankTickets"); + MarkNativeAsOptional("L4D2Direct_SetTankTickets"); + MarkNativeAsOptional("L4D2Direct_GetTerrorNavArea"); + MarkNativeAsOptional("L4D2Direct_GetTerrorNavAreaFlow"); + MarkNativeAsOptional("L4D2Direct_TryOfferingTankBot"); + MarkNativeAsOptional("L4D2Direct_GetFlowDistance"); + MarkNativeAsOptional("L4D2Direct_DoAnimationEvent"); + MarkNativeAsOptional("L4DDirect_GetSurvivorHealthBonus"); + MarkNativeAsOptional("L4DDirect_SetSurvivorHealthBonus"); + MarkNativeAsOptional("L4DDirect_RecomputeTeamScores"); + + MarkNativeAsOptional("L4D2Direct_GetTankCount"); + MarkNativeAsOptional("L4D2Direct_GetMobSpawnTimer"); + MarkNativeAsOptional("L4D2Direct_GetSIClassDeathTimer"); + MarkNativeAsOptional("L4D2Direct_GetSIClassSpawnTimer"); + MarkNativeAsOptional("L4D2Direct_GetVSStartTimer"); + MarkNativeAsOptional("L4D2Direct_GetScavengeRoundSetupTimer"); + MarkNativeAsOptional("L4D2Direct_GetScavengeOvertimeGraceTimer"); + MarkNativeAsOptional("L4D2Direct_GetSpawnTimer"); + MarkNativeAsOptional("L4D2Direct_GetShovePenalty"); + MarkNativeAsOptional("L4D2Direct_SetShovePenalty"); + MarkNativeAsOptional("L4D2Direct_GetNextShoveTime"); + MarkNativeAsOptional("L4D2Direct_SetNextShoveTime"); + MarkNativeAsOptional("L4D2Direct_GetPreIncapHealth"); + MarkNativeAsOptional("L4D2Direct_SetPreIncapHealth"); + MarkNativeAsOptional("L4D2Direct_GetPreIncapHealthBuffer"); + MarkNativeAsOptional("L4D2Direct_SetPreIncapHealthBuffer"); + MarkNativeAsOptional("L4D2Direct_GetInfernoMaxFlames"); + MarkNativeAsOptional("L4D2Direct_SetInfernoMaxFlames"); + MarkNativeAsOptional("L4D2Direct_GetScriptedEventManager"); + + // l4d2d_timers.inc + MarkNativeAsOptional("CTimer_Reset"); + MarkNativeAsOptional("CTimer_Start"); + MarkNativeAsOptional("CTimer_Invalidate"); + MarkNativeAsOptional("CTimer_HasStarted"); + MarkNativeAsOptional("CTimer_IsElapsed"); + MarkNativeAsOptional("CTimer_GetElapsedTime"); + MarkNativeAsOptional("CTimer_GetRemainingTime"); + MarkNativeAsOptional("CTimer_GetCountdownDuration"); + MarkNativeAsOptional("ITimer_Reset"); + MarkNativeAsOptional("ITimer_Start"); + MarkNativeAsOptional("ITimer_Invalidate"); + MarkNativeAsOptional("ITimer_HasStarted"); + MarkNativeAsOptional("ITimer_GetElapsedTime"); + + MarkNativeAsOptional("CTimer_GetDuration"); + MarkNativeAsOptional("CTimer_SetDuration"); + MarkNativeAsOptional("CTimer_GetTimestamp"); + MarkNativeAsOptional("CTimer_SetTimestamp"); + MarkNativeAsOptional("ITimer_GetTimestamp"); + MarkNativeAsOptional("ITimer_SetTimestamp"); + + + + // ========================= + // l4d2addresses.txt + // ========================= + MarkNativeAsOptional("L4D_CTerrorPlayer_OnVomitedUpon"); + MarkNativeAsOptional("L4D2_Charger_ThrowImpactedSurvivor"); + MarkNativeAsOptional("L4D2_Charger_StartCarryingVictim"); + MarkNativeAsOptional("L4D2_Charger_PummelVictim"); + MarkNativeAsOptional("L4D2_Charger_EndPummel"); + MarkNativeAsOptional("L4D2_Jockey_EndRide"); + MarkNativeAsOptional("L4D_CancelStagger"); + MarkNativeAsOptional("L4D_CreateRescuableSurvivors"); + MarkNativeAsOptional("L4D_ReviveSurvivor"); + MarkNativeAsOptional("L4D_GetHighestFlowSurvivor"); + MarkNativeAsOptional("L4D_GetInfectedFlowDistance"); + MarkNativeAsOptional("L4D_CleanupPlayerState"); + MarkNativeAsOptional("L4D_TakeOverZombieBot"); + MarkNativeAsOptional("L4D_ReplaceWithBot"); + MarkNativeAsOptional("L4D_CullZombie"); + MarkNativeAsOptional("L4D_SetClass"); + MarkNativeAsOptional("L4D_MaterializeFromGhost"); + MarkNativeAsOptional("L4D_BecomeGhost"); + MarkNativeAsOptional("L4D_State_Transition"); + MarkNativeAsOptional("L4D_RegisterForbiddenTarget"); + MarkNativeAsOptional("L4D_UnRegisterForbiddenTarget"); + + MarkNativeAsOptional("L4D2_CTerrorPlayer_OnHitByVomitJar"); + MarkNativeAsOptional("L4D2_Infected_OnHitByVomitJar"); + MarkNativeAsOptional("L4D2_CTerrorPlayer_Fling"); + MarkNativeAsOptional("L4D2_GetVersusCompletionPlayer"); + MarkNativeAsOptional("L4D2_SwapTeams"); + MarkNativeAsOptional("L4D2_AreTeamsFlipped"); + MarkNativeAsOptional("L4D2_StartRematchVote"); + MarkNativeAsOptional("L4D2_FullRestart"); + MarkNativeAsOptional("L4D2_HideVersusScoreboard"); + MarkNativeAsOptional("L4D2_HideScavengeScoreboard"); + MarkNativeAsOptional("L4D2_HideScoreboard"); +} +#endif + + + + + +// ==================================================================================================== +// VARIOUS ENUMS +// ==================================================================================================== +// For the game mode native and forward +enum +{ + GAMEMODE_UNKNOWN = 0, + GAMEMODE_COOP = 1, + GAMEMODE_VERSUS = 2, + GAMEMODE_SURVIVAL = 4, + GAMEMODE_SCAVENGE = 8 +}; + +// For the "L4D_GetPointer" native +enum PointerType +{ + POINTER_DIRECTOR = 1, // @TheDirector + POINTER_SERVER = 2, // @sv + POINTER_GAMERULES = 3, // @g_pGameRules + POINTER_NAVMESH = 4, // @TheNavMesh + POINTER_ZOMBIEMANAGER = 5, // @TheZombieManager + POINTER_WEAPONINFO = 6, // @_ZL20m_WeaponInfoDatabase + POINTER_MELEEINFO = 7, // @g_MeleeWeaponInfoStore (L4D2 Only) + POINTER_EVENTMANAGER = 8, // pScriptedEventManager (L4D2 Only) + POINTER_SCAVENGEMODE = 9, // pScavengeMode (L4D2 Only) + POINTER_VERSUSMODE = 10, // pVersusMode + POINTER_SCRIPTVM = 11, // @g_pScriptVM (L4D2 Only) + POINTER_THENAVAREAS = 12 // @TheNavAreas +}; + +// Provided by "BHaType": +// For the "L4D_State_Transition" native +// X -> Y (means X state will become Y state on next frame or some seconds later) +enum +{ + STATE_ACTIVE = 0, + STATE_WELCOME, // -> STATE_PICKING_TEAM + STATE_PICKING_TEAM, + STATE_PICKINGCLASS, // -> STATE_ACTIVE + STATE_DEATH_ANIM, // -> STATE_DEATH_WAIT_FOR_KEY + STATE_DEATH_WAIT_FOR_KEY, // -> STATE_OBSERVER_MODE + STATE_OBSERVER_MODE, + STATE_WAITING_FOR_RESCUE, + STATE_GHOST, + STATE_INTRO_CAMERA +}; + +// From: https://developer.valvesoftware.com/wiki/L4D2_Director_Scripts +// For the "L4D2_ChangeFinaleStage" and "L4D2_GetCurrentFinaleStage" natives and "L4D2_OnChangeFinaleStage" forward +enum +{ + FINALE_GAUNTLET_1 = 0, + FINALE_HORDE_ATTACK_1 = 1, + FINALE_HALFTIME_BOSS = 2, + FINALE_GAUNTLET_2 = 3, + FINALE_HORDE_ATTACK_2 = 4, + FINALE_FINAL_BOSS = 5, + FINALE_HORDE_ESCAPE = 6, + FINALE_CUSTOM_PANIC = 7, + FINALE_CUSTOM_TANK = 8, + FINALE_CUSTOM_SCRIPTED = 9, + FINALE_CUSTOM_DELAY = 10, + FINALE_CUSTOM_CLEAROUT = 11, + FINALE_GAUNTLET_START = 12, + FINALE_GAUNTLET_HORDE = 13, + FINALE_GAUNTLET_HORDE_BONUSTIME = 14, + FINALE_GAUNTLET_BOSS_INCOMING = 15, + FINALE_GAUNTLET_BOSS = 16, + FINALE_GAUNTLET_ESCAPE = 17 +}; + +// Used as the "reason" by the "L4D_OnKnockedDown*" forwards +enum +{ + KNOCKDOWN_HUNTER = 1, + KNOCKDOWN_TANK = 2, + KNOCKDOWN_CHARGER = 3 +}; + +// From: https://developer.valvesoftware.com/wiki/List_of_L4D_Series_Nav_Mesh_Attributes +// Use by "L4D_GetNavArea_AttributeFlags" and "L4D_SetNavArea_AttributeFlags" natives +// NavArea Base Attributes: +enum +{ + NAV_BASE_CROUCH = 1, // (1<<0) + NAV_BASE_JUMP = 2, // (1<<1) + NAV_BASE_PRECISE = 4, // (1<<2) + NAV_BASE_NO_JUMP = 8, // (1<<3) + NAV_BASE_STOP = 16, // (1<<4) + NAV_BASE_RUN = 32, // (1<<5) + NAV_BASE_WALK = 64, // (1<<6) + NAV_BASE_AVOID = 128, // (1<<7) + NAV_BASE_TRANSIENT = 256, // (1<<8) + NAV_BASE_DONT_HIDE = 512, // (1<<9) + NAV_BASE_STAND = 1024, // (1<<10) + NAV_BASE_NO_HOSTAGES = 2048, // (1<<11) + NAV_BASE_STAIRS = 4096, // (1<<12) + NAV_BASE_NO_MERGE = 8192, // (1<<13) + NAV_BASE_OBSTACLE_TOP = 16384, // (1<<14) + NAV_BASE_CLIFF = 32768, // (1<<15) + NAV_BASE_TANK_ONLY = 65536, // (1<<16) + NAV_BASE_MOB_ONLY = 131072, // (1<<17) + NAV_BASE_PLAYERCLIP = 262144, // (1<<18) + NAV_BASE_BREAKABLEWALL = 524288, // (1<<19) + NAV_BASE_FLOW_BLOCKED = 134217728, // (1<<27) + NAV_BASE_OUTSIDE_WORLD = 268435456, // (1<<28) + NAV_BASE_MOSTLY_FLAT = 536870912, // (1<<29) + NAV_BASE_HAS_ELEVATOR = 1073741824, // (1<<30) + NAV_BASE_NAV_BLOCKER = -2147483648 // (1<<31) +}; + +// Use by "L4D_GetNavArea_SpawnAttributes" and "L4D_SetNavArea_SpawnAttributes" natives +// NavArea Spawn Attributes: +enum +{ + NAV_SPAWN_EMPTY = 2, // (1<<0) + NAV_SPAWN_STOP_SCAN = 4, // (1<<1) + NAV_SPAWN_BATTLESTATION = 32, // (1<<5) + NAV_SPAWN_FINALE = 64, // (1<<6) + NAV_SPAWN_PLAYER_START = 128, // (1<<7) + NAV_SPAWN_BATTLEFIELD = 256, // (1<<8) + NAV_SPAWN_IGNORE_VISIBILITY = 512, // (1<<9) + NAV_SPAWN_NOT_CLEARABLE = 1024, // (1<<10) + NAV_SPAWN_CHECKPOINT = 2048, // (1<<11) + NAV_SPAWN_OBSCURED = 4096, // (1<<12) + NAV_SPAWN_NO_MOBS = 8192, // (1<<13) + NAV_SPAWN_THREAT = 16384, // (1<<14) + NAV_SPAWN_RESCUE_VEHICLE = 32768, // (1<<15) + NAV_SPAWN_RESCUE_CLOSET = 65536, // (1<<16) + NAV_SPAWN_ESCAPE_ROUTE = 131072, // (1<<17) + NAV_SPAWN_DESTROYED_DOOR = 262144, // (1<<18) + NAV_SPAWN_NOTHREAT = 524288, // (1<<19) + NAV_SPAWN_LYINGDOWN = 1048576, // (1<<20) + NAV_SPAWN_COMPASS_NORTH = 16777216, // (1<<24) + NAV_SPAWN_COMPASS_NORTHEAST = 33554432, // (1<<25) + NAV_SPAWN_COMPASS_EAST = 67108864, // (1<<26) + NAV_SPAWN_COMPASS_EASTSOUTH = 134217728, // (1<<27) + NAV_SPAWN_COMPASS_SOUTH = 268435456, // (1<<28) + NAV_SPAWN_COMPASS_SOUTHWEST = 536870912, // (1<<29) + NAV_SPAWN_COMPASS_WEST = 1073741824, // (1<<30) + NAV_SPAWN_COMPASS_WESTNORTH = -2147483648 // (1<<31) +}; + +// From: https://developer.valvesoftware.com/wiki/L4D2_Director_Scripts +// Used by "L4D_NavArea_IsConnected" native +// NavArea Spawn Attributes: +enum +{ + NAV_NORTH = 0, + NAV_EAST = 1, + NAV_SOUTH = 2, + NAV_WEST = 3, + NAV_ALL = 4 +}; + +// List provided by "A1m`" taken from: https://github.com/A1mDev/l4d2_structs/blob/master/terror_player_animstate.h +// There are constants that are not used, these constants were already inside the engine, the developers added their own over the existing code +// Some constants from 'l4d2util_contants.inc' +// These are used by the "L4D2Direct_DoAnimationEvent" native and "L4D_OnDoAnimationEvent*" forwards +// L4D1 seems to only have 35 animation events, the names may not be relative to those listed here +enum PlayerAnimEvent_t +{ + // Made by A1m` + + PLAYERANIMEVENT_ATTACK_PRIMARY = 1, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_ATTACK_SECONDARY = 2, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_ATTACK_GRENADE = 3, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_RELOAD = 4, // CMultiPlayerAnimState::DoAnimationEvent, CTerrorGun::SendWeaponAnim + PLAYERANIMEVENT_RELOAD_LOOP = 5, // CMultiPlayerAnimState::DoAnimationEvent, CBaseShotgun::CheckReload->PlayReloadAnim + PLAYERANIMEVENT_RELOAD_END = 6, //CMultiPlayerAnimState::DoAnimationEvent, CBaseShotgun::CheckReload->PlayReloadAnim, CTerrorGun::AbortReload + PLAYERANIMEVENT_JUMP = 7, // CMultiPlayerAnimState::DoAnimationEvent, CTerrorGameMovement::DoJump, CCSGameMovement::CheckJumpButton + PLAYERANIMEVENT_LAND = 8, // CTerrorGameMovement::PlayerRoughLandingEffects + + PLAYERANIMEVENT_SWIM = 9, // Not sure, not used in the game anyway + + PLAYERANIMEVENT_DIE = 10, // CMultiPlayerAnimState::DoAnimationEvent, CTerrorPlayer::StartSurvivorDeathAnim, CTerrorPlayer::OnIncapacitatedAsTank + PLAYERANIMEVENT_FLINCH_CHEST = 11, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_FLINCH_HEAD = 12, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_FLINCH_LEFTARM = 13, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_FLINCH_RIGHTARM = 14, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_FLINCH_LEFTLEG = 15, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_FLINCH_RIGHTLEG = 16, // CMultiPlayerAnimState::DoAnimationEvent + + PLAYERANIMEVENT_DOUBLEJUMP = 17, // Not sure, not used in the game anyway + + PLAYERANIMEVENT_CANCEL_GESTURE_ATTACK_AND_RELOAD = 18, // CTerrorPlayer::OnShovedByPounceLanding, CTerrorPlayer::OnShovedBySurvivor, CTerrorPlayer::OnRideEnded, CTerrorPlayer::OnPounceEnded + + PLAYERANIMEVENT_CANCEL = 19, // Not sure, not used in the game anyway + + PLAYERANIMEVENT_SPAWN = 20, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_SNAP_YAW = 21, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_CUSTOM = 22, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_CUSTOM_GESTURE = 23, // CMultiPlayerAnimState::DoAnimationEvent + PLAYERANIMEVENT_CUSTOM_SEQUENCE = 24, // CMultiPlayerAnimState::DoAnimationEvent + + PLAYERANIMEVENT_CUSTOM_GESTURE_SEQUENCE = 25, // Not sure, not used in the game anyway + + // TF Specific. Here until there's a derived game solution to this + PLAYERANIMEVENT_ATTACK_PRE = 26, // Not sure, not used in the game anyway + PLAYERANIMEVENT_ATTACK_POST = 27, // Not sure, not used in the game anyway + PLAYERANIMEVENT_GRENADE1_DRAW = 28, // Not sure, not used in the game anyway + PLAYERANIMEVENT_GRENADE2_DRAW = 29, // Not sure, not used in the game anyway + PLAYERANIMEVENT_GRENADE1_THROW = 30, // Not sure, not used in the game anyway + PLAYERANIMEVENT_GRENADE2_THROW = 31, // Not sure, not used in the game anyway + PLAYERANIMEVENT_VOICE_COMMAND_GESTURE = 32, // Not sure, not used in the game?. CTerrorPlayerAnimState::DoAnimationEvent + + PLAYERANIMEVENT_HAND_ATTACK = 33, // CClaw::OnSwingStart, CTerrorPlayer::UpdateTankEffects, CTankClaw::OnSwingStart + PLAYERANIMEVENT_HAND_LOW_ATTACK = 34, // CTankClaw::OnSwingStart, CTerrorWeapon::OnSwingStart + PLAYERANIMEVENT_SHOVE_COMMON = 35, // CTerrorWeapon::OnSwingStart + PLAYERANIMEVENT_SHOVE = 36, // CTerrorWeapon::OnSwingStart + PLAYERANIMEVENT_SHOVE_ZOMBIE_STOMP = 37, //CTerrorWeapon::OnSwingStart + PLAYERANIMEVENT_START_RELOADING_SHOTGUN = 38, // CBaseShotgun::Reload->PlayReloadAnim + PLAYERANIMEVENT_START_CHAINSAW = 39, // CChainsaw::Deploy + PLAYERANIMEVENT_PRIMARY_ATTACK = 40, // CTerrorMeleeWeapon::StartMeleeSwing, CBaseBeltItem::PrimaryAttack, FireTerrorBullets, CGrenadeLauncher::PrimaryAttack + PLAYERANIMEVENT_SECONDARY_ATTACK = 41, // CTerrorMeleeWeapon::StartMeleeSwing, CVomit::ActivateAbility, FireTerrorBullets + PLAYERANIMEVENT_HEAL_SELF = 42, + PLAYERANIMEVENT_HEAL_OTHER = 43, + PLAYERANIMEVENT_CROUCH_HEAL_INCAP = 44, // CTerrorPlayer::StartReviving + PLAYERANIMEVENT_CROUCH_HEAL_INCAPACITATED_ABOVE = 45, // CTerrorPlayer::StartReviving + PLAYERANIMEVENT_STOP_USE_ACTION = 46, // CTerrorPlayer::StopRevivingSomeone, CTerrorPlayer::StopBeingRevived, CFirstAidKit::OnStopAction, CItemAmmoPack::OnStopAction, CItemBaseUpgradePack::OnStopAction, CItemDefibrillator::OnStopAction + PLAYERANIMEVENT_PICKUP_START_SUBJECT = 47, // CTerrorPlayer::StartReviving + PLAYERANIMEVENT_PICKUP_STOP_SUBJECT = 48, // CTerrorPlayer::CleanupPlayerState, CTerrorPlayer::StopBeingRevived, CTerrorPlayer::StopRevivingSomeone + PLAYERANIMEVENT_PICKUP_SUCCESS_SUBJECT = 49, // CTerrorPlayer::OnRevived + PLAYERANIMEVENT_DEFIB_START = 50, + PLAYERANIMEVENT_DEFIB_END = 51, + PLAYERANIMEVENT_DEPLOY_AMMO = 52, + PLAYERANIMEVENT_USE_GASCAN_START = 53, + PLAYERANIMEVENT_USE_GASCAN_END = 54, // CGasCan::OnStopAction + PLAYERANIMEVENT_USE_COLA_START = 55, + PLAYERANIMEVENT_USE_COLA_END = 56, // CColaBottles::OnStopAction + PLAYERANIMEVENT_FLINCH_EVENT_SHOVED_BY_TEAMMATE = 57, // CTerrorPlayer::OnTakeDamageInternal->GetFlinchEvent, CTerrorPlayer::OnTakeDamage_Alive->GetFlinchEvent, CTerrorWeapon::OnHit->GetFlinchEvent + PLAYERANIMEVENT_FLINCH_EVENT_TAKE_DAMAGE = 58, // CTerrorPlayer::GetFlinchEvent + PLAYERANIMEVENT_THROW_ITEM_START = 59, // CBaseCSGrenade::PrimaryAttack + + PLAYERANIMEVENT_ROLL_GRENADE = 60, // Not sure, not used in the game anyway + + PLAYERANIMEVENT_THROW_ITEM_FINISH = 61, // CBaseCSGrenade::ItemPostFrame + PLAYERANIMEVENT_THROW_GRENADE = 62, // CCSPlayer::DoAnimationEvent + PLAYERANIMEVENT_THROW_ITEM_HOLSTER = 63, // CBaseCSGrenade::Holster + PLAYERANIMEVENT_PLAYER_USE = 64, // CTerrorPlayer::OnUseEntity + PLAYERANIMEVENT_CHANGE_SLOT = 65, // CWeaponCSBase::DefaultDeploy + + PLAYERANIMEVENT_UNKNOWN_START_GESTURE = 66, // Don't know. Not used in the game? Something like option 32? CTerrorPlayerAnimState::DoAnimationEvent + + PLAYERANIMEVENT_TUG_HANGING_PLAYER = 67, // CTerrorPlayer::StartTug + PLAYERANIMEVENT_STUMBLE = 68, // CTerrorPlayer::UpdateStagger, CTerrorPlayer::OnShovedByPounceLanding, CTerrorPlayer::OnStaggered, CTerrorPlayer::UpdateStagger, CTerrorPlayer::OnShovedBySurvivor + PLAYERANIMEVENT_POUNCE_VICTIM_END = 69, + PLAYERANIMEVENT_SPIT_SPITTING = 70, // CSpitAbility::ActivateAbility + PLAYERANIMEVENT_CHARGER_START_CHARGE = 71, // CCharge::BeginCharge + PLAYERANIMEVENT_CHARGER_END_CHARGE = 72, // CCharge::EndCharge + PLAYERANIMEVENT_CHARGER_PUMMELING_START = 73, + PLAYERANIMEVENT_CHARGER_PUMMELING_END = 74, // ZombieReplacement::Restore, CTerrorPlayer::UpdatePound, ZombieReplacement::Restore + PLAYERANIMEVENT_CHARGER_SLAM_INTO_GROUND = 75, // CTerrorPlayer::OnSlammedSurvivor + PLAYERANIMEVENT_IMPACT_BY_CHARGER = 76, + PLAYERANIMEVENT_CHARGER_PUMMELED = 77, // ThrowImpactedSurvivor->CTerrorPlayer::Fling; CTerrorPlayerAnimState::HandleActivity_Pummeling + PLAYERANIMEVENT_POUNDED_BY_CHARGER = 78, // ZombieReplacement::Restore, CTerrorPlayer::UpdatePound, CTerrorPlayerAnimState::HandleActivity_Pummeling + PLAYERANIMEVENT_CARRIED_BY_CHARGER = 79, // ZombieReplacement::Restore, CTerrorPlayer::OnStartBeingCarried + PLAYERANIMEVENT_STAGGERING = 80, // CTerrorPlayer::OnSlammedSurvivor + PLAYERANIMEVENT_VICTIM_SLAMMED_INTO_GROUND = 81, // CTerrorPlayer::OnSlammedSurvivor + PLAYERANIMEVENT_HUNTER_POUNCING = 82, // ZombieReplacement::Restore, CTerrorPlayer::OnPouncedUpon, ZombieReplacement::Restore + PLAYERANIMEVENT_HUNTER_POUNCE_ON_VICTIM = 83, // CTerrorPlayer::OnPouncedOnSurvivor + PLAYERANIMEVENT_JOCKEY_RIDING = 84, + PLAYERANIMEVENT_JOCKEY_RIDDEN = 85, // ZombieReplacement::Restore + PLAYERANIMEVENT_HUNTER_GETUP = 86, // CTerrorPlayer::OnPouncedUpon, ZombieReplacement::Restore + PLAYERANIMEVENT_TONGUE_LAUNCH_START = 87, // SmokerTongueVictim::OnStart + PLAYERANIMEVENT_TONGUE_LAUNCH_END = 88, // CTongue::OnEnterExtendingState + PLAYERANIMEVENT_TONGUE_REELING_IN = 89, // CTongue::OnEnterAttachedToTargetState + PLAYERANIMEVENT_TONGUE_ATTACKING_START = 90, // CTongue::OnTouch + PLAYERANIMEVENT_TONGUE_ATTACKING_END = 91, // CTerrorPlayer::OnReleasingWithTongue + PLAYERANIMEVENT_VICTIM_PULLED = 92, // ZombieReplacement::Restore, CTerrorPlayer::OnGrabbedByTongue + PLAYERANIMEVENT_ROCK_THROW = 93, // CThrow::ActivateAbility + PLAYERANIMEVENT_TANK_CLIMB = 94, // TankLocomotion::ClimbUpToLedge + PLAYERANIMEVENT_TANK_RAGE = 95, // CTerrorPlayer::OnAttackSuccess, CTerrorPlayer::OnMissionLost, CTerrorPlayer::ClientCommand (dance) + PLAYERANIMEVENT_PLAYERHIT_BY_TANK = 96, // CTankClaw::OnPlayerHit, CTerrorPlayer::OnTakeDamage->Fling, CTerrorPlayer::OnKnockedDown + PLAYERANIMEVENT_PUSH_ENTITY = 97, // CTerrorPlayer::PlayerUse + PLAYERANIMEVENT_FIDGET = 98, // CTerrorPlayerAnimState::UpdateFidgeting + + PLAYERANIMEVENT_COUNT // Total size 99. Function 'CTerrorPlayer::DoAnimationEvent' +}; + + + + + +// ==================================================================================================== +// ANIMATION HOOK +// ==================================================================================================== +/* The PRE hook can utilize the "ACT_*" enum defines from the "include/left4dhooks_anim.inc" include file. */ +typeset AnimHookCallback +{ + /** + * @brief Callback called whenever animation is invoked + * + * @param client Client triggering + * @param sequence The animation "activity" (pre-hook) or "m_nSequence" (post-hook) sequence number being used + * + * @return Plugin_Changed to change animation, Plugin_Continue otherwise + */ + function Action(int client, int &sequence); +} + +/** + * @brief Add a client animation hook + * @remarks All hooks are removed on map change + * + * @param client The client to hook + * @param callback Callback function for your pre-hook (uses "ACT_*" activity numbers) or INVALID_FUNCTION to not use + * @param callbackPost Callback function for your post-hook (uses "m_nSequence" sequence numbers) or INVALID_FUNCTION to not use + * + * @return True on success, false if client invalid + */ +native bool AnimHookEnable(int client, AnimHookCallback callback, AnimHookCallback callbackPost = INVALID_FUNCTION); + +/** + * @brief Remove a client animation hook + * @remarks All hooks are removed on map change + * + * @param client The client to hook + * @param callback Callback function for your pre-hook (uses "ACT_*" activity numbers) or INVALID_FUNCTION if not used + * @param callbackPost Callback function for your post-hook (uses "m_nSequence" sequence numbers) or INVALID_FUNCTION if not used + * + * @return True on success, false if client not hooked + */ +native bool AnimHookDisable(int client, AnimHookCallback callback, AnimHookCallback callbackPost = INVALID_FUNCTION); + +/** + * @brief Retrieves the activity string from it's relative activity number + * @remarks activity numbers are different from a models "m_nSequence" sequence numbers + * @remarks The ACT_* list and values are for Survivor models and differ from other models. Use the "m_nSequence" sequence value in a post hook for Special Infected + * @remarks The "m_nSequence" sequence values for each model can be found using Left4Dead Authoring Tools > Model Viewer + * @remarks The PRE hook can utilize the "ACT_*" enum defines from the "include/left4dhooks_anim.inc" include file instead of using this method of converting them + * + * @param sequence Activity number to retrieve from + * @param activity Destination string to store the activity + * @param maxlength Size of destination string + * + * @return True on success, false on failure to find + */ +native bool AnimGetActivity(int sequence, char[] activity, int maxlength); + +/** + * @brief Retrieves the animation activity number from an activity string + * + * @param activity The activity string to retrieve from + * + * @return Activity number or -1 on failure + */ +native int AnimGetFromActivity(char[] activity); + + + + + +// ==================================================================================================== +// FORWARDS - left4downtown.inc (and new ones by Silvers) +// ==================================================================================================== +/** + * @brief Called whenever ZombieManager::SpawnSpecial(ZombieClassType,Vector&,QAngle&) is invoked + * @remarks Only used for bot special spawns (not players) + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * + * @param zombieClass Zombie class that will be spawned + * @param vecPos Vector coordinate where special will be spawned + * @param vecAng QAngle where special will be facing + * + * @return Plugin_Handled to block special from spawning, + * Plugin_Changed to change the zombie class type to spawn, Plugin_Continue otherwise + */ +forward Action L4D_OnSpawnSpecial(int &zombieClass, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnSpecial(ZombieClassType,Vector&,QAngle&) is invoked + * @remarks Only used for bot special spawns (not players) + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client The client index who spawned. Can be 0 if spawning failed + * @param zombieClass Zombie class that will be spawned + * @param vecPos Vector coordinate where special will be spawned + * @param vecAng QAngle where special will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnSpecial_Post(int client, int zombieClass, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnSpecial(ZombieClassType,Vector&,QAngle&) is invoked + * @remarks Only used for bot special spawns (not players) + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client The client index who spawned. Can be 0 if spawning failed or -1 if blocked + * @param zombieClass Zombie class that will be spawned + * @param vecPos Vector coordinate where special will be spawned + * @param vecAng QAngle where special will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnSpecial_PostHandled(int client, int zombieClass, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnTank(Vector&,QAngle&) is invoked + * @remarks Not invoked if z_spawn tank is used and it gives a ghosted/dead player tank + * + * @param vecPos Vector coordinate where tank is spawned + * @param vecAng QAngle where tank will be facing + * + * @return Plugin_Handled to block tank from spawning, Plugin_Continue otherwise + */ +forward Action L4D_OnSpawnTank(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnTank(Vector&,QAngle&) is invoked + * @remarks Not invoked if z_spawn tank is used and it gives a ghosted/dead player tank + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client The client index who spawned + * @param vecPos Vector coordinate where tank is spawned + * @param vecAng QAngle where tank will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnTank_Post(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnTank(Vector&,QAngle&) is invoked + * @remarks Not invoked if z_spawn tank is used and it gives a ghosted/dead player tank + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client The client index who spawned (can be -1 if blocked in pre hook) + * @param vecPos Vector coordinate where tank is spawned + * @param vecAng QAngle where tank will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnTank_PostHandled(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitch(Vector&,QAngle&) is invoked + * @brief Called when a Witch spawns + * + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @return Plugin_Handled to block witch from spawning, Plugin_Continue otherwise + */ +forward Action L4D_OnSpawnWitch(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitch(Vector&,QAngle&) is invoked + * @brief Called when a Witch spawns + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity Entity index that spawned + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnWitch_Post(int entity, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitch(Vector&,QAngle&) is invoked + * @brief Called when a Witch spawns + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity Entity index that spawned (can be -1 if blocked) + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @noreturn + */ +forward void L4D_OnSpawnWitch_PostHandled(int entity, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitchBride(Vector&,QAngle&) is invoked + * @brief Called when a Witch Bride spawns + * + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @return Plugin_Handled to block witch from spawning, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnSpawnWitchBride(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitchBride(Vector&,QAngle&) is invoked + * @brief Called when a Witch Bride spawns + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity Entity index that spawned + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnSpawnWitchBride_Post(int entity, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever ZombieManager::SpawnWitchBride(Vector&,QAngle&) is invoked + * @brief Called when a Witch Bride spawns + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity Entity index that spawned (can be -1 if blocked) + * @param vecPos Vector coordinate where witch is spawned + * @param vecAng QAngle where witch will be facing + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnSpawnWitchBride_PostHandled(int entity, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Called whenever CDirector::OnMobRushStart(void) is invoked + * @remarks called on random hordes, mini and finale hordes, and boomer hordes, causes Zombies to attack + * Not called on "z_spawn mob", hook the console command and check arguments to catch plugin mobs + * This function is used to reset the Director's natural horde timer + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnMobRushStart(); + +/** + * @brief Called whenever CDirector::OnMobRushStart(void) is invoked + * @remarks called on random hordes, mini and finale hordes, and boomer hordes, causes Zombies to attack + * Not called on "z_spawn mob", hook the console command and check arguments to catch plugin mobs + * This function is used to reset the Director's natural horde timer + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D_OnMobRushStart_Post(); + +/** + * @brief Called whenever CDirector::OnMobRushStart(void) is invoked + * @remarks called on random hordes, mini and finale hordes, and boomer hordes, causes Zombies to attack + * Not called on "z_spawn mob", hook the console command and check arguments to catch plugin mobs + * This function is used to reset the Director's natural horde timer + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D_OnMobRushStart_PostHandled(); + +/** + * @brief Called whenever ZombieManager::SpawnITMob(int) is invoked + * @remarks called on boomer hordes, increases Zombie Spawn Queue + * + * @param amount Amount of Zombies to add to Queue + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D_OnSpawnITMob(int &amount); + +/** + * @brief Called whenever ZombieManager::SpawnITMob(int) is invoked + * @remarks called on boomer hordes, increases Zombie Spawn Queue + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param amount Amount of Zombies to add to Queue + * + * @noreturn + */ +forward void L4D_OnSpawnITMob_Post(int amount); + +/** + * @brief Called whenever ZombieManager::SpawnITMob(int) is invoked + * @remarks called on boomer hordes, increases Zombie Spawn Queue + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param amount Amount of Zombies to add to Queue + * + * @noreturn + */ +forward void L4D_OnSpawnITMob_PostHandled(int amount); + +/** + * @brief Called whenever ZombieManager::SpawnMob(int) is invoked + * @remarks called on natural hordes & z_spawn mob, increases Zombie Spawn + * Queue, triggers player OnMobSpawned (vocalizations), sets horde + * direction, and plays horde music + * + * @param amount Amount of Zombies to add to Queue + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D_OnSpawnMob(int &amount); + +/** + * @brief Called whenever ZombieManager::SpawnMob(int) is invoked + * @remarks called on natural hordes & z_spawn mob, increases Zombie Spawn + * Queue, triggers player OnMobSpawned (vocalizations), sets horde + * direction, and plays horde music + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param amount Amount of Zombies to add to Queue + * + * @noreturn + */ +forward void L4D_OnSpawnMob_Post(int amount); + +/** + * @brief Called whenever ZombieManager::SpawnMob(int) is invoked + * @remarks called on natural hordes & z_spawn mob, increases Zombie Spawn + * Queue, triggers player OnMobSpawned (vocalizations), sets horde + * direction, and plays horde music + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param amount Amount of Zombies to add to Queue + * + * @noreturn + */ +forward void L4D_OnSpawnMob_PostHandled(int amount); + +/** + * @brief Called when a witch has been startled by someone + * + * @param witch The witch entity index + * @param victim Client who harassed the Witch, will be 0 on spawn + * + * @noreturn + **/ +forward void L4D_OnWitchSetHarasser(int witch, int victim); + +/** + * @brief Called when Tank::EnterStasis() is invoked + * @remarks Called when a Tank enters stasis mode in Versus mode + * + * @param tank Client index of the Tank + * + * @noreturn + **/ +forward void L4D_OnEnterStasis(int tank); + +/** + * @brief Called when Tank::LeaveStasis() is invoked + * @remarks Called when a Tank leaves stasis mode in Versus mode + * + * @param tank Client index of the Tank + * + * @noreturn + **/ +forward void L4D_OnLeaveStasis(int tank); + +/** + * @brief Called whenever CTerrorPlayer::OnEnterGhostState(CTerrorPlayer*) is invoked + * @remarks This happens when a player enters ghost mode (or in finales auto-materialized) + * @remarks This forward triggers before the player enters ghost state allowing it to be blocked + * + * @param client the client that has entered ghost mode + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnEnterGhostStatePre(int client); + +/** + * @brief Called whenever CTerrorPlayer::OnEnterGhostState(CTerrorPlayer*) is invoked + * @remarks This happens when a player enters ghost mode (or in finales auto-materialized) + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that has entered ghost mode + * + * @noreturn + */ +forward void L4D_OnEnterGhostState(int client); + +/** + * @brief Called whenever CTerrorPlayer::OnEnterGhostState(CTerrorPlayer*) is invoked + * @remarks This happens when a player enters ghost mode (or in finales auto-materialized) + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that has entered ghost mode + * + * @noreturn + */ +forward void L4D_OnEnterGhostState_PostHandled(int client); + +/** + * @brief Called whenever CTerrorPlayer::TakeOverBot(CTerrorPlayer*) is invoked + * @remarks This happens when player is looking to take over a bot + * + * @param client the client that is looking to take over a bot + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnTakeOverBot(int client); + +/** + * @brief Called whenever CTerrorPlayer::TakeOverBot(CTerrorPlayer*) is invoked + * @remarks This happens when player is looking to take over a bot + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that is looking to take over a bot + * @param success true if the takeover was successful, false otherwise + * + * @noreturn + */ +forward void L4D_OnTakeOverBot_Post(int client, bool success); + +/** + * @brief Called whenever CTerrorPlayer::TakeOverBot(CTerrorPlayer*) is invoked + * @remarks This happens when player is looking to take over a bot + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that is looking to take over a bot + * @param success true if the takeover was successful, false otherwise + * + * @noreturn + */ +forward void L4D_OnTakeOverBot_PostHandled(int client, bool success); + +/** + * @brief Called whenever CTerrorPlayer::MaterializeFromGhost is invoked + * @remarks Called when a Special Infected spawns out of ghost mode + * + * @param victim the client who spawned + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnMaterializeFromGhostPre(int client); + +/** + * @brief Called whenever CTerrorPlayer::MaterializeFromGhost is invoked + * @remarks Called when a Special Infected spawns out of ghost mode + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who spawned + * + * @noreturn + */ +forward void L4D_OnMaterializeFromGhost(int client); + +/** + * @brief Called whenever CTerrorPlayer::MaterializeFromGhost is invoked + * @remarks Called when a Special Infected spawns out of ghost mode + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who spawned + * + * @noreturn + */ +forward void L4D_OnMaterializeFromGhost_PostHandled(int client); + +/** + * @brief Called whenever IsTeamFull is invoked + * @remarks called when bots or players are joining a team + * + * @param team Which team is being checked. 2=Survivors. 3=Special Infected + * + * @return Plugin_Handled to block changing team, Plugin_Continue otherwise + */ +forward Action L4D_OnIsTeamFull(int team, bool &full); + +/** + * @brief Called whenever CTerrorGameRules::ClearTeamScores(bool) is invoked + * @remarks This resets the map score at the beginning of a map, and by checking + * the campaign scores on a small timer you can see if they were reset as well + * + * @param newCampaign if true then this is a new campaign, if false a new chapter. Not used for L4D1 + * + * @return Plugin_Handled to block scores from being cleared, Plugin_Continue otherwise. Does not block reset in L4D1 + */ +forward Action L4D_OnClearTeamScores(bool newCampaign); + +/** + * @brief Called whenever CTerrorGameRules::SetCampaignScores(int,int) is invoked + * @remarks The campaign scores are updated after the 2nd round is completed + * + * @param scoreA score of logical team A + * @param scoreB score of logical team B + * + * @return Plugin_Handled to block campaign scores from being set, Plugin_Continue otherwise + */ +forward Action L4D_OnSetCampaignScores(int &scoreA, int &scoreB); + +/** + * @brief Called whenever CTerrorGameRules::SetCampaignScores(int,int) is invoked + * @remarks The campaign scores are updated after the 2nd round is completed + * + * @param scoreA score of logical team A + * @param scoreB score of logical team B + * + * @noreturn + */ +forward void L4D_OnSetCampaignScores_Post(int scoreA, int scoreB); + +/** + * @brief Called whenever CTerrorPlayer:RecalculateVersusScore(void) is invoked + * @remarks Calculates an individual survivors health bonus from their current health and status + * + * @return Plugin_Handled to block health bonus from being calculated +*/ +// L4D1 only +forward Action L4D_OnRecalculateVersusScore(int client); + +/** + * @brief Called whenever CTerrorPlayer:RecalculateVersusScore(void) is invoked + * @remarks Calculates an individual survivors health bonus from their current health and status + * + * @noreturn +*/ +// L4D1 only +forward void L4D_OnRecalculateVersusScore_Post(int client); + +/** + * @brief Called whenever CDirector::OnFirstSurvivorLeftSafeArea is invoked + * @remarks A versus round is started when survivors leave the safe room, or force started + * after 90 seconds regardless + * + * @param client the survivor that left the safe area first + * + * @return Plugin_Handled to block round from being started, Plugin_Continue otherwise + */ +forward Action L4D_OnFirstSurvivorLeftSafeArea(int client); + +/** + * @brief Called whenever CDirector::OnFirstSurvivorLeftSafeArea is invoked + * @remarks A versus round is started when survivors leave the safe room, or force started + * after 90 seconds regardless + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the survivor that left the safe area first + * + * @noreturn + */ +forward void L4D_OnFirstSurvivorLeftSafeArea_Post(int client); + +/** + * @brief Called whenever CDirector::OnFirstSurvivorLeftSafeArea is invoked + * @remarks A versus round is started when survivors leave the safe room, or force started + * after 90 seconds regardless + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the survivor that left the safe area first + * + * @noreturn + */ +forward void L4D_OnFirstSurvivorLeftSafeArea_PostHandled(int client); + +/** + * @brief Called whenever CDirector::OnForceSurvivorPositions is invoked + * @remarks Triggers after round start when Survivors are forced into starting positions, usually first map and finale escape start, does not trigger on all maps + * + * @noreturn + */ +forward void L4D_OnForceSurvivorPositions_Pre(); + +/** + * @brief Called whenever CDirector::OnForceSurvivorPositions is invoked + * @remarks Triggers after round start when Survivors are forced into starting positions, usually first map and finale escape start, does not trigger on all maps + * + * @noreturn + */ +forward void L4D_OnForceSurvivorPositions(); + +/** + * @brief Called whenever CDirector::OnReleaseSurvivorPositions is invoked + * @remarks Triggers after round start when Survivors are released from the starting positions, usually first map and finale escape start, does not trigger on all maps + * + * @noreturn + */ +forward void L4D_OnReleaseSurvivorPositions(); + +/** + * @brief Called whenever "SpeakResponseConceptFromEntityIO" is invoked + * @remarks Triggers on concept talking + * + * @param entity Entity doing the talking (not always client indexes, might be a func_orator) + * + * @noreturn + */ +forward void L4D_OnSpeakResponseConcept_Pre(int entity); + +/** + * @brief Called whenever "SpeakResponseConceptFromEntityIO" is invoked + * @remarks Triggers on concept talking + * + * @param entity Entity doing the talking (not always client indexes, might be a func_orator) + * + * @noreturn + */ +forward void L4D_OnSpeakResponseConcept_Post(int entity); + +/** + * @brief Called whenever CTerrorPlayer::GetCrouchTopSpeed() is invoked + * @remarks Constantly called to get players max Crouch speed + * + * @param target the client that its being called on (not changeable) + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +forward Action L4D_OnGetCrouchTopSpeed(int target, float &retVal); + +/** + * @brief Called whenever CTerrorPlayer::GetRunTopSpeed() is invoked + * @remarks Constantly called to get players max Run speed + * + * @param target the client that its being called on (not changeable) + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +forward Action L4D_OnGetRunTopSpeed(int target, float &retVal); + +/** + * @brief Called whenever CTerrorPlayer::GetWalkTopSpeed() is invoked + * @remarks Constantly called to get players max Walk speed + * + * @param target the client that its being called on (not changeable) + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +forward Action L4D_OnGetWalkTopSpeed(int target, float &retVal); + +/** + * @brief Called whenever CDirector::GetScriptValue(const char*, int) is invoked + * @remarks A script value is map specific + * @warning This forward may not fire on some keys due to C inline feature. Use L4D2_OnGetScriptValueInt instead to avoid the issue + * + * @param key the script's key name + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnGetScriptValueInt(const char[] key, int &retVal); + +/** + * @brief Called whenever CDirector::GetScriptValue(const char*, float) is invoked + * @remarks A script value is map specific + * @warning This forward may not fire on some keys due to C inline feature. Use L4D2_OnGetScriptValueFloat instead to avoid the issue + * + * @param key the script's key name + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnGetScriptValueFloat(const char[] key, float &retVal); + +/** + * @brief Called whenever CDirector::GetScriptValue(const char*, Vector) is invoked + * @remarks A script value is map specific + * @warning This forward may not fire on some keys due to C inline feature. Use L4D2_OnGetScriptValueVector instead to avoid the issue + * + * @param key the script's key name + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +// Unused, unable to determine if the return value is modified, and potentially different detour setup for linux +// forward Action L4D_OnGetScriptValueVector(const char[] key, float retVal[3]); + +/** + * @brief Called whenever CDirector::GetScriptValue(const char*, const char*, char*, int) is invoked + * @remarks A script value is map specific + * @warning This forward may not fire on some keys due to C inline feature. Use L4D2_OnGetScriptValueString instead to avoid the issue + * + * @param key the script's key name + * @param defaultVal default key return, usually empty + * @param retVal returned string + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnGetScriptValueString(const char[] key, const char[] defaultVal, char retVal[128]); + +// These are used for the "L4D2_OnGetScriptValueVoid" forward, and interally for the other "L4D2_OnGetScriptValue*" forwards: +enum fieldtype_t +{ + FIELD_VOID = 0, // No type or value + FIELD_FLOAT = 1, // Any floating point value + FIELD_VECTOR = 3, // Any vector, QAngle, or AngularImpulse + FIELD_INTEGER = 5, // Any integer or enum + FIELD_BOOLEAN = 6, // boolean, implemented as an int, I may use this as a hint for compression + FIELD_CHARACTER = 8, // a byte + FIELD_CSTRING = 31, + FIELD_UNSIGNED = 38, + FIELD_QANGLE = 40 +}; + +enum struct VariantBuffer +{ + int m_int; + float m_float; + char m_string[256]; + float m_vector[3]; +} + +/** + * @brief Called whenever CSquirrelVM::GetValue() is invoked + * @remarks A script value is map specific + * @remarks This is called when the searching key is not present in the Script VM + * @remarks "retVal" accepts only 2 formats --- int:12345 or float:123.4 + * + * @param key the script's key name + * @param type the data type being set in retVal + * @param retVal what to override the return value with + * @param hScope The script scope (table) this was called from + * Use L4D2_GetDirectorScriptScope() if you want to make sure this was called by CDirector + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnGetScriptValueVoid(const char[] key, fieldtype_t &type, VariantBuffer retVal, int hScope); + +/** + * @brief Called whenever CSquirrelVM::GetValue() is invoked + * @remarks A script value is map specific + * + * @param key the script's key name + * @param retVal what to override the return value with + * @param hScope The script scope (table) this was called from + * Use L4D2_GetDirectorScriptScope() if you want to make sure this was called by CDirector + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnGetScriptValueInt(const char[] key, int &retVal, int hScope); + +/** + * @brief Called whenever CSquirrelVM::GetValue() is invoked + * @remarks A script value is map specific + * + * @param key the script's key name + * @param retVal what to override the return value with + * @param hScope The script scope (table) this was called from + * Use L4D2_GetDirectorScriptScope() if you want to make sure this was called by CDirector + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnGetScriptValueFloat(const char[] key, float &retVal, int hScope); + +/** + * @brief Called whenever CSquirrelVM::GetValue() is invoked + * @remarks A script value is map specific + * + * @param key the script's key name + * @param retVal what to override the return value with + * @param hScope The script scope (table) this was called from + * Use L4D2_GetDirectorScriptScope() if you want to make sure this was called by CDirector + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnGetScriptValueVector(const char[] key, float retVal[3], int hScope); + +/** + * @brief Called whenever CTerrorGameRules::HasConfigurableDifficultySetting() is invoked + * @remarks used to deny/allow difficulty changes in different game modes + * + * @param retVal what to override the return value with. 1 to allow difficulty configuration, 0 to deny + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnHasConfigurableDifficulty(int &retVal); + +/** + * @brief Called whenever CTerrorGameRules::HasConfigurableDifficultySetting() is invoked + * @remarks used to deny/allow difficulty changes in different game modes + * + * @param retVal what to override the return value with. 1 to allow difficulty configuration, 0 to deny + * + * @noreturn + */ +// L4D2 only +forward void L4D_OnHasConfigurableDifficulty_Post(int retVal); + +/** + * @brief Called whenever CTerrorGameRules::GetSurvivorSet(void) is invoked + * @remarks Constantly called to get the survivor character set + * + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnGetSurvivorSet(int &retVal); + +/** + * @brief Called whenever CTerrorGameRules::FastGetSurvivorSet(void) is invoked + * @remarks Constantly called to get the survivor character set + * + * @param retVal what to override the return value with + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnFastGetSurvivorSet(int &retVal); + +/** + * @brief Called whenever CDirectorVersusMode::GetMissionVersusBossSpawning() is invoked + * @remarks Passed values are from the map's Mission Keyvalues. If those keyvalues don't exist, they are from cvar and other globals + * + * @param spawn_pos_min Minimum spawn position (percent of flow distance) for bosses + * @param spawn_pos_max Maximum spawn position (percent of flow distance) for bosses + * @param tank_chance Chance for a tank to spawn on this map + * @param witch_chance Chance for a witch to spawn on this map + * + * @return Plugin_Handled to block reading map data, Plugin_Changed to use overwritten values from plugin, Plugin_Continue to continue to read from mission data + */ +forward Action L4D_OnGetMissionVSBossSpawning(float &spawn_pos_min, float &spawn_pos_max, float &tank_chance, float &witch_chance); + +/** + * @brief Called whenever CDirectorVersusMode::GetMissionVersusBossSpawning() is invoked + * @remarks Passed values are from the map's Mission Keyvalues. If those keyvalues don't exist, they are from cvar and other globals + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param spawn_pos_min Minimum spawn position (percent of flow distance) for bosses + * @param spawn_pos_max Maximum spawn position (percent of flow distance) for bosses + * @param tank_chance Chance for a tank to spawn on this map + * @param witch_chance Chance for a witch to spawn on this map + * + * @noreturn + */ +forward void L4D_OnGetMissionVSBossSpawning_Post(float spawn_pos_min, float spawn_pos_max, float tank_chance, float witch_chance); + +/** + * @brief Called whenever CDirectorVersusMode::GetMissionVersusBossSpawning() is invoked + * @remarks Passed values are from the map's Mission Keyvalues. If those keyvalues don't exist, they are from cvar and other globals + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param spawn_pos_min Minimum spawn position (percent of flow distance) for bosses + * @param spawn_pos_max Maximum spawn position (percent of flow distance) for bosses + * @param tank_chance Chance for a tank to spawn on this map + * @param witch_chance Chance for a witch to spawn on this map + * + * @noreturn + */ +forward void L4D_OnGetMissionVSBossSpawning_PostHandled(float spawn_pos_min, float spawn_pos_max, float tank_chance, float witch_chance); + +/** + * @brief Called whenever ZombieManager::ReplaceTank(CTerrorPlayer *,CTerrorPlayer *) is invoked + * @remarks When a player loses tank control and is replaced by another player. Not invoked if tank is bot + * + * @param tank the player who was a tank + * @param newtank a player who has become a new tank + * + * @noreturn + */ +forward void L4D_OnReplaceTank(int tank, int newtank); + +/** + * @brief Called whenever CTankClaw::DoSwing(CTankClaw *this) is invoked + * @remarks When a tank is swinging to punch + * + * @param tank tank client index + * @param claw the claw entity index + * + * @noreturn + */ +forward void L4D_TankClaw_DoSwing_Pre(int tank, int claw); + +/** + * @brief Called whenever CTankClaw::DoSwing(CTankClaw *this) is invoked + * @remarks When a tank is swinging to punch + * + * @param tank tank client index + * @param claw the claw entity index + * + * @noreturn + */ +forward void L4D_TankClaw_DoSwing_Post(int tank, int claw); + +/** + * @brief Called whenever CTankClaw::GroundPound() is invoked + * @remarks When hitting the ground (maybe only when hitting an incapped player) + * @remarks The forwards "L4D_TankClaw_OnPlayerHit_Pre" and "L4D_TankClaw_OnPlayerHit_Post" trigger after this, allowing identification of victim + * @remarks The forwards "L4D_TankClaw_DoSwing_Pre" and "L4D_TankClaw_DoSwing_Post" can trigger after this + * + * @param tank tank client index + * @param claw the claw entity index + * + * @noreturn + */ +forward void L4D_TankClaw_GroundPound_Pre(int tank, int claw); + +/** + * @brief Called whenever CTankClaw::GroundPound() is invoked + * @remarks When hitting the ground (maybe only when hitting an incapped player) + * @remarks The forwards "L4D_TankClaw_OnPlayerHit_Pre" and "L4D_TankClaw_OnPlayerHit_Post" trigger before this + * @remarks The forwards "L4D_TankClaw_DoSwing_Pre" and "L4D_TankClaw_DoSwing_Post" can trigger after this + * + * @param tank tank client index + * @param claw the claw entity index + * + * @noreturn + */ +forward void L4D_TankClaw_GroundPound_Post(int tank, int claw); + +/** + * @brief Called whenever CTankClaw::OnPlayerHit(CTerrorPlayer*, bool) is invoked + * @remarks When a tank swings and punches a player + * + * @param tank tank client index + * @param claw the claw entity index + * @param player the player being hit + * + * @return Plugin_Handled to block the target player from being stumbled, Plugin_Continue otherwise + */ +forward Action L4D_TankClaw_OnPlayerHit_Pre(int tank, int claw, int player); + +/** + * @brief Called whenever CTankClaw::OnPlayerHit(CTerrorPlayer*, bool) is invoked + * @remarks When a tank swings and punches a player + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param tank tank client index + * @param claw the claw entity index + * @param player the player being hit + * + * @noreturn + */ +forward void L4D_TankClaw_OnPlayerHit_Post(int tank, int claw, int player); + +/** + * @brief Called whenever CTankClaw::OnPlayerHit(CTerrorPlayer*, bool) is invoked + * @remarks When a tank swings and punches a player + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param tank tank client index + * @param rock the claw entity index + * @param player the player being hit + * + * @noreturn + */ +forward void L4D_TankClaw_OnPlayerHit_PostHandled(int tank, int claw, int player); + +/** + * @brief Called whenever CTankRock::Detonate() is invoked + * @remarks When a tank rock hits something and explodes + * + * @param tank tank client index + * @param rock the rock entity index + * + * @noreturn + */ +forward void L4D_TankRock_OnDetonate(int tank, int rock); + +/** + * @brief Called whenever CTankRock::OnRelease(Vector const&, QAngle const&, Vector const&, Vector const&) is invoked + * @remarks When a tank rock is thrown + * + * @param tank tank client index (can be -1 if the rock was created by the native "L4D_TankRockPrj" or the "env_rock_launcher" entity) + * @param rock the rock entity index + * @param vecPos the position vector of the rock + * @param vecAng the angle vector of the rock + * @param vecVel the velocity vector of the rock + * @param vecRot the rotation vector of the rock + * + * @return Plugin_Changed to modify the vector values, Plugin_Continue otherwise + */ +forward Action L4D_TankRock_OnRelease(int tank, int rock, float vecPos[3], float vecAng[3], float vecVel[3], float vecRot[3]); + +/** + * @brief Called whenever CTankRock::OnRelease(Vector const&, QAngle const&, Vector const&, Vector const&) is invoked + * @remarks When a tank rock is thrown + * @remarks Forward shows the final values that may have been changed from the relative pre-hook + * + * @param tank tank client index (can be -1 if the rock was created by the native "L4D_TankRockPrj" or the "env_rock_launcher" entity) + * @param rock the rock entity index + * @param vecPos the position vector of the rock + * @param vecAng the angle vector of the rock + * @param vecVel the velocity vector of the rock + * @param vecRot the rotation vector of the rock + * + * @noreturn + */ +forward void L4D_TankRock_OnRelease_Post(int tank, int rock, const float vecPos[3], const float vecAng[3], const float vecVel[3], const float vecRot[3]); + +/** + * @brief Called whenever CDirector::TryOfferingTankBot is invoked + * @remarks Is used for displaying the "X gets Tank" window and transferring Tank control + * + * @param tank_index Client index of the tank + * @param enterStasis Is the tank in stasis + * + * @return Plugin_Handled to block window from showing and to keep Tank Bot, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D_OnTryOfferingTankBot(int tank_index, bool &enterStasis); + +/** + * @brief Called whenever CDirector::TryOfferingTankBot is invoked + * @remarks Is used for displaying the "X gets Tank" window and transferring Tank control + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param tank_index Client index of the tank + * @param enterStasis Is the tank in stasis + * + * @noreturn + */ +forward void L4D_OnTryOfferingTankBot_Post(int tank_index, bool enterStasis); + +/** + * @brief Called whenever CDirector::TryOfferingTankBot is invoked + * @remarks Is used for displaying the "X gets Tank" window and transferring Tank control + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param tank_index Client index of the tank (can be -1 when blocked) + * @param enterStasis Is the tank in stasis + * + * @noreturn + */ +forward void L4D_OnTryOfferingTankBot_PostHandled(int tank_index, bool enterStasis); + +/** + * @brief Called whenever CThrow::ActivateAbility(void) is invoked + * @remarks Called when a tank throws a rock. Blocking this call will keep the tank from throwing a rock + * + * @param ability ability_throw entity index + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnCThrowActivate(int ability); + +/** + * @brief Called whenever CThrow::ActivateAbility(void) is invoked + * @remarks Called when a tank throws a rock. Blocking this call will keep the tank from throwing a rock + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param ability ability_throw entity index + * + * @noreturn + */ +forward void L4D_OnCThrowActivate_Post(int ability); + +/** + * @brief Called whenever CThrow::ActivateAbility(void) is invoked + * @remarks Called when a tank throws a rock. Blocking this call will keep the tank from throwing a rock + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param ability ability_throw entity index + * + * @noreturn + */ +forward void L4D_OnCThrowActivate_PostHandled(int ability); + +/** + * @brief Called when CBaseAnimating::SelectWeightedSequence(int Activity) is invoked with tank attack activity + * @remarks Called whenever a tank uses his primary (punch) or secondary (throw) attack (uses ACT_* activity numbers) + * + * This detour uses activity sequence numbers + * + * @param client the client that is playing as tank + * @param sequence current selected activity for attack, option to override the return value with it + * + * L4D2: + * ACT_HULK_THROW 761 + * ACT_TANK_OVERHEAD_THROW 762 + * ACT_HULK_ATTACK_LOW 763 + * ACT_TERROR_ATTACK_MOVING 790 + * + * L4D1: + * ACT_HULK_THROW 1254 + * ACT_TANK_OVERHEAD_THROW 1255 + * ACT_HULK_ATTACK_LOW 1256 + * ACT_TERROR_ATTACK_MOVING 1282 + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +forward Action L4D2_OnSelectTankAttackPre(int client, int &sequence); + +/** + * @brief Called when CBaseAnimating::SelectWeightedSequence(int Activity) is invoked with tank attack activity + * @remarks Called whenever a tank uses his primary (punch) or secondary (throw) attack (uses m_nSequence animation numbers) + * + * This detour uses models m_nSequence numbers + * + * @param client the client that is playing as tank + * @param sequence current selected activity for attack, option to override the return value with it + * + * @remarks sequences, for L4D1: + * @remarks sequences(punches) 38 (uppercut), 41 (right hook), 43 (left hook), 44 and 45 (pounding the ground) + * @remarks sequences(throws) 46 (undercut), 47 (1handed overhand), 48 (throw from the hip), 49 (2handed overhand) + * + * @remarks sequences, for L4D2: + * @remarks sequences(punches) 40 uppercut), 43 (right hook), 45 (left hook), 46 and 47 (pounding the ground) + * @remarks sequences(throws) 48 undercut), 49 (1handed overhand), 50 (throw from the hip), 51 (2handed overhand) + * + * @return Plugin_Handled to override return value, Plugin_Continue otherwise + */ +forward Action L4D2_OnSelectTankAttack(int client, int &sequence); + +/** + * @brief Called whenever CTerrorMeleeWeapon::StartMeleeSwing(CTerrorPlayer *, bool) is invoked + * @remarks Called when a player uses his melee weapons primary attack. This is before the game + * reads the melee weapon data (model etc) and decides if he CAN attack at all + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D_OnStartMeleeSwing(int client, bool boolean); + +/** + * @brief Called whenever CTerrorMeleeWeapon::StartMeleeSwing(CTerrorPlayer *, bool) is invoked + * @remarks Called when a player uses his melee weapons primary attack. This is before the game + * reads the melee weapon data (model etc) and decides if he CAN attack at all + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +// L4D2 only +forward void L4D_OnStartMeleeSwing_Post(int client, bool boolean); + +/** + * @brief Called whenever CTerrorMeleeWeapon::StartMeleeSwing(CTerrorPlayer *, bool) is invoked + * @remarks Called when a player uses his melee weapons primary attack. This is before the game + * reads the melee weapon data (model etc) and decides if he CAN attack at all + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +// L4D2 only +forward void L4D_OnStartMeleeSwing_PostHandled(int client, bool boolean); + +/** + * @brief Called whenever CTerrorMeleeWeapon::GetDamageForVictim() is invoked + * @remarks Called to calculate the damage when a melee weapon hits something + * @remarks A headshot on Common Infected will still kill them + * @remarks Could maybe set the weapon attribute "L4D2BoolMeleeWeapon_Decapitates" to avoid killing on headshot. Please report success if you try + * + * @param client the client swinging the melee weapon + * @param weapon the weapon entity index + * @param victim the victim being hit by the melee weapon + * @param damage the amount of damage to inflict on the victim + * + * @return Plugin_Handled to block, Plugin_Changed to change damage, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_MeleeGetDamageForVictim(int client, int weapon, int victim, float &damage); + +/** + * @brief Called whenever CTerrorPlayer::DoAnimationEvent is invoked + * @note The event argument is NOT the same as the sequence numbers found in the model viewer + * @note You can get the number for your animation by looking at the disasm for virtual calls to DoAnimationEvent + * + * @return Plugin_Handled to block, Plugin_Changed to modify value, Plugin_Continue otherwise + */ +forward Action L4D_OnDoAnimationEvent(int client, int &event, int &variant_param); + +/** + * @brief Called whenever CTerrorPlayer::DoAnimationEvent is invoked + * @note The event argument is NOT the same as the sequence numbers found in the model viewer + * @note You can get the number for your animation by looking at the disasm for virtual calls to DoAnimationEvent + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D_OnDoAnimationEvent_Post(int client, int event, int variant_param); + +/** + * @brief Called whenever CTerrorPlayer::DoAnimationEvent is invoked + * @note The event argument is NOT the same as the sequence numbers found in the model viewer + * @note You can get the number for your animation by looking at the disasm for virtual calls to DoAnimationEvent + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D_OnDoAnimationEvent_PostHandled(int client, int event, int variant_param); + +/** + * @brief Called whenever CDirectorScriptedEventManager::SendInRescueVehicle(void) is invoked + * @remarks Called when the last Finale stage is reached and the Rescue means becomes 'available' + * Take note this forward WILL fire upon using the native of the same function + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// 2020 Left4DHooks update: Blocked on L4D1/L4D2 Linux to prevent crashes. Waiting for DHooks update to support object returns +forward Action L4D2_OnSendInRescueVehicle(); + +/** + * @brief Called whenever CDirectorScriptedEventManager::ChangeFinaleStage is invoked + * @remarks Called when the director stage changes + * @remarks some values for FinaleStageType: 1 - Finale Started; 6 - Rescue Vehicle Ready; 7 - Zombie Hordes; 8 - Tank; 10 - Combat Respite (nothing spawns) + * @remarks SendInRescueVehicle does not depend on Finale Stage being 6, that only signals endless Hordes/Tanks + * @remarks Can use the "FINALE_*" enums (search for them above) for the finaleType value + * + * @param FinaleStageType integer value + * + * @return Plugin_Handled to block, Plugin_Changed to change finaleType, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnChangeFinaleStage(int &finaleType, const char[] arg); + +/** + * @brief Called whenever CDirectorScriptedEventManager::ChangeFinaleStage is invoked + * @remarks Called when the director stage changes + * @remarks some values for FinaleStageType: 1 - Finale Started; 6 - Rescue Vehicle Ready; 7 - Zombie Hordes; 8 - Tank; 10 - Combat Respite (nothing spawns) + * @remarks SendInRescueVehicle does not depend on Finale Stage being 6, that only signals endless Hordes/Tanks + * @remarks Can use the "FINALE_*" enums (search for them above) for the finaleType value + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param FinaleStageType integer value + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnChangeFinaleStage_Post(int finaleType, const char[] arg); + +/** + * @brief Called whenever CDirectorScriptedEventManager::ChangeFinaleStage is invoked + * @remarks Called when the director stage changes + * @remarks some values for FinaleStageType: 1 - Finale Started; 6 - Rescue Vehicle Ready; 7 - Zombie Hordes; 8 - Tank; 10 - Combat Respite (nothing spawns) + * @remarks SendInRescueVehicle does not depend on Finale Stage being 6, that only signals endless Hordes/Tanks + * @remarks Can use the "FINALE_*" enums (search for them above) for the finaleType value + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param FinaleStageType integer value + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnChangeFinaleStage_PostHandled(int finaleType, const char[] arg); + +/** + * @brief Called whenever CDirectorVersusMode::EndVersusModeRound(bool) is invoked + * @remarks Called before score calculations and the scoreboard display + * + * @param countSurvivors True if the survival multiplier count needs to be nonzero. I guess + * @remarks Not sure what bool does exactly yet. Just monitor it. If true, survivors will be counted for multiplier. If false, survival multiplier will be set to 0 + * @remarks A lot of Score calculations happen on this function, and the round-end scoreboard comes up doing this. Don't block unless you're sure you can reproduce this logic + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D2_OnEndVersusModeRound(bool countSurvivors); + +/** + * @brief Called after CDirectorVersusMode::EndVersusModeRound(bool) + * @remarks Called after all score calculations are complete and the scoreboard shows + * @remarks Called after all score calculations inside CDirectorVersusMode::EndVersusModeRound(bool). This good forward to replace standard "round_end" hook + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D2_OnEndVersusModeRound_Post(); + +/** + * @brief Called after CDirectorVersusMode::EndVersusModeRound(bool) + * @remarks Called after all score calculations are complete and the scoreboard shows + * @remarks Called after all score calculations inside CDirectorVersusMode::EndVersusModeRound(bool). This good forward to replace standard "round_end" hook + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @noreturn + */ +forward void L4D2_OnEndVersusModeRound_PostHandled(); + +/** + * @brief Called whenever CTerrorPlayer::OnLedgeGrabbed(CTerrorPlayer *this, const Vector *) is invoked + * @remarks Called when a player is about to grab a ledge + * + * @param client client grabbing the ledge + * + * @return Plugin_Handled to prevent grabbing, Plugin_Continue otherwise + */ +forward Action L4D_OnLedgeGrabbed(int client); + +/** + * @brief Called whenever CTerrorPlayer::OnLedgeGrabbed(CTerrorPlayer *this, const Vector *) is invoked + * @remarks Called when a player is about to grab a ledge + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client client grabbing the ledge + * + * @noreturn + */ +forward void L4D_OnLedgeGrabbed_Post(int client); + +/** + * @brief Called whenever CTerrorPlayer::OnLedgeGrabbed(CTerrorPlayer *this, const Vector *) is invoked + * @remarks Called when a player is about to grab a ledge + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client client grabbing the ledge + * + * @noreturn + */ +forward void L4D_OnLedgeGrabbed_PostHandled(int client); + +/** + * @brief Called when CTerrorPlayer::OnRevived(void) is invoked + * @remarks Called post-revive so all data values are post-revive status + * + * @param client the client that has been revived + * + * @noreturn + */ +forward void L4D2_OnRevived(int client); + +/** + * @brief Called whenever CTerrorWeapon::OnSwingStart(CTerrorWeapon *this) is invoked + * @remarks Called when a Survivor shoves + * @remarks Blocking has no effect so this function is void only + * + * @param client the client that did the shoving + * @param weapon the weapon being held when shoving + * + * @noreturn + */ +forward void L4D_OnSwingStart(int client, int weapon); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedBySurvivor(CTerrorPlayer, Vector&) is invoked + * @remarks L4D2 only uses this on Special Infected + * @remarks Blocks hunter dead stop + * + * @param client the client that did the shoving + * @param victim the client that was shoved (CAUTION retrieved from function pointer, don't meddle with it) + * @param vecDir Vector Angle of Shoveforce + * + * @return Plugin_Handled to block melee effect (staggering), Plugin_Continue otherwise + */ +forward Action L4D_OnShovedBySurvivor(int client, int victim, const float vecDir[3]); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedBySurvivor(CTerrorPlayer, Vector&) is invoked + * @remarks L4D2 only uses this on Special Infected + * @remarks Blocks hunter dead stop + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that did the shoving + * @param victim the client that was shoved (CAUTION retrieved from function pointer, don't meddle with it) + * @param vecDir Vector Angle of Shoveforce + * + * @noreturn + */ +forward void L4D_OnShovedBySurvivor_Post(int client, int victim, const float vecDir[3]); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedBySurvivor(CTerrorPlayer, Vector&) is invoked + * @remarks L4D2 only uses this on Special Infected + * @remarks Blocks hunter dead stop + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that did the shoving + * @param victim the client that was shoved (CAUTION retrieved from function pointer, don't meddle with it) + * @param vecDir Vector Angle of Shoveforce + * + * @noreturn + */ +forward void L4D_OnShovedBySurvivor_PostHandled(int client, int victim, const float vecDir[3]); + +/** + * @brief Called whenever CTerrorWeapon::OnHit(CGameTrace &, Vector const&, bool) is invoked + * @remarks Called for every single shovable and even some of the unshovable entities in the game + * + * @param client survivor who did the shoving + * @param entity entity that is about to get shoved + * @param weapon weapon that has been held while shoving + * @param vecDir stagger direction + * @param bIsHighPounce a boolean to determine if it was a pounce from a height or not; reliable to a certain degree and should only be considered for hunters + * @param bIsHighPounce sometimes reset to 0 when punched before the detour retrieves the information + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D2_OnEntityShoved(int client, int entity, int weapon, float vecDir[3], bool bIsHighPounce); + +/** + * @brief Called whenever CTerrorWeapon::OnHit(CGameTrace &, Vector const&, bool) is invoked + * @remarks Called for every single shovable and even some of the unshovable entities in the game + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client survivor who did the shoving + * @param entity entity that is about to get shoved + * @param weapon weapon that has been held while shoving + * @param vecDir stagger direction + * @param bIsHighPounce a boolean to determine if it was a pounce from a height or not; reliable to a certain degree and should only be considered for hunters + * @param bIsHighPounce sometimes reset to 0 when punched before the detour retrieves the information + * + * @noreturn + */ +forward void L4D2_OnEntityShoved_Post(int client, int entity, int weapon, const float vecDir[3], bool bIsHighPounce); + +/** + * @brief Called whenever CTerrorWeapon::OnHit(CGameTrace &, Vector const&, bool) is invoked + * @remarks Called for every single shovable and even some of the unshovable entities in the game + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client survivor who did the shoving + * @param entity entity that is about to get shoved + * @param weapon weapon that has been held while shoving + * @param vecDir stagger direction + * @param bIsHighPounce a boolean to determine if it was a pounce from a height or not; reliable to a certain degree and should only be considered for hunters + * @param bIsHighPounce sometimes reset to 0 when punched before the detour retrieves the information + * + * @noreturn + */ +forward void L4D2_OnEntityShoved_PostHandled(int client, int entity, int weapon, const float vecDir[3], bool bIsHighPounce); + +/** + * @brief Called whenever CTerrorPlayer::OnStaggered(CBaseEntity *, Vector const *) is invoked + * @remarks Source is always null for Charger impacts (Valve) + * + * @param client the client that is about to get staggered + * @param source the client that is about to stagger the client + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D2_OnStagger(int client, int source); + +/** + * @brief Called whenever CTerrorPlayer::OnStaggered(CBaseEntity *, Vector const *) is invoked + * @remarks Source is always null for Charger impacts (Valve) + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that is about to get staggered + * @param source the client that is about to stagger the client + * + * @noreturn + */ +forward void L4D2_OnStagger_Post(int client, int source); + +/** + * @brief Called whenever CTerrorPlayer::OnStaggered(CBaseEntity *, Vector const *) is invoked + * @remarks Source is always null for Charger impacts (Valve) + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client that is about to get staggered + * @param source the client that is about to stagger the client + * + * @noreturn + */ +forward void L4D2_OnStagger_PostHandled(int client, int source); + +/** + * @brief Called when CTerrorPlayer::CancelStagger() is invoked + * @remarks Called when a players staggering is about to be cancelled + * + * @param client Client index of the player + * + * @return Plugin_Handled to allow staggering to continue, Plugin_Continue to allow + **/ +forward Action L4D_OnCancelStagger(int client); + +/** + * @brief Called when CTerrorPlayer::CancelStagger() is invoked + * @remarks Called when a players staggering is being cancelled + * @remarks This will not trigger if the cancel is being blocked by other plugins + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player + * + * @return Plugin_Handled to allow staggering to continue, Plugin_Continue to allow + **/ +forward void L4D_OnCancelStagger_Post(int client); + +/** + * @brief Called when CTerrorPlayer::CancelStagger() is invoked + * @remarks Called when a players staggering has not been cancelled + * @remarks This will trigger if the cancel is being blocked by other plugins + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player + * + * @return Plugin_Handled to allow staggering to continue, Plugin_Continue to allow + **/ +forward void L4D_OnCancelStagger_PostHandled(int client); + +/** + * @brief Called when CTerrorPlayer::Fling(Vector const&, PlayerAnimEvent_t, CBaseCombatCharacter*, float) is invoked + * @remarks Called when a player is flung to the ground + * + * @param client Client index of the player + * @param attacker Client index of the attacker + * @param vecDir Vector direction of the fling + * + * @return Plugin_Handled to block fling, Plugin_Continue to allow + **/ +// L4D2 only +forward Action L4D2_OnPlayerFling(int client, int attacker, float vecDir[3]); + +/** + * @brief Called when CTerrorPlayer::Fling(Vector const&, PlayerAnimEvent_t, CBaseCombatCharacter*, float) is invoked + * @remarks Called when a player is flung to the ground + * @remarks This will not trigger if the fling is being blocked by other plugins + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player + * @param attacker Client index of the attacker + * @param vecDir Vector direction of the fling + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnPlayerFling_Post(int client, int attacker, const float vecDir[3]); + +/** + * @brief Called when CTerrorPlayer::Fling(Vector const&, PlayerAnimEvent_t, CBaseCombatCharacter*, float) is invoked + * @remarks Called when a player is flung to the ground + * @remarks This will trigger if the fling is being blocked by other plugins + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player + * @param attacker Client index of the attacker + * @param vecDir Vector direction of the fling + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnPlayerFling_PostHandled(int client, int attacker, const float vecDir[3]); + +/** + * @brief Called when CTerrorPlayer::IsMotionControlledXY is invoked + * @remarks Called when a player is staggering or a Hunter has been knocked off someone + * @remarks Blocking this will allow the player to fall with gravity instead of floating in the air + * @remarks Pre-public release: various bugs surrounding this method. To be addressed later + * + * @param client Client index of the player + * @param activity The activity sequence playing that has overridden gravity + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + **/ +#pragma deprecated This is for private testing and not released for public usage yet +forward Action L4D_OnMotionControlledXY(int client, int activity); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedByPounceLanding(CTerrorPlayer*) is invoked + * + * @param victim the survivor that is about to get stumbled as a result of "attacker" capping someone in close proximity + * @param attacker the SI that is about to cause a stumble as a result of capping someone in close proximity to a survivor + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D2_OnPounceOrLeapStumble(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedByPounceLanding(CTerrorPlayer*) is invoked + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the survivor that is about to get stumbled as a result of "attacker" capping someone in close proximity + * @param attacker the SI that is about to cause a stumble as a result of capping someone in close proximity to a survivor + * + * @noreturn + */ +forward void L4D2_OnPounceOrLeapStumble_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnShovedByPounceLanding(CTerrorPlayer*) is invoked + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the survivor that is about to get stumbled as a result of "attacker" capping someone in close proximity + * @param attacker the SI that is about to cause a stumble as a result of capping someone in close proximity to a survivor + * + * @noreturn + */ +forward void L4D2_OnPounceOrLeapStumble_PostHandled(int victim, int attacker); + +/** + * @brief Called when CTerrorPlayer::OnKnockedDown(CTerrorPlayer*) is invoked + * @remarks Called when someone is about to be hit by a Tank rock or lunged by a Hunter + * @remarks You can use the "KNOCKDOWN_*" enum values for the reason + * @remarks Called multiple times when someone is about to be has been pounced by a Hunter + * + * @param victim Client index of the victim + * @param reason The Knockdown reason type. 1=Hunter lunge, 2=Tank rock, 3=Charger impact + * + * @return Plugin_Handled to block fling, Plugin_Continue to allow + **/ +forward Action L4D_OnKnockedDown(int client, int reason); + +/** + * @brief Called when CTerrorPlayer::OnKnockedDown(CTerrorPlayer*) is invoked + * @remarks Called when someone is about to be hit by a Tank rock or lunged by a Hunter + * @remarks Called multiple times when someone is about to be has been pounced by a Hunter + * @remarks You can use the "KNOCKDOWN_*" enum values for the reason + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim Client index of the victim + * @param reason The Knockdown reason type. 1=Hunter lunge, 2=Tank rock + * + * @noreturn + **/ +forward void L4D_OnKnockedDown_Post(int client, int reason); + +/** + * @brief Called when CTerrorPlayer::OnKnockedDown(CTerrorPlayer*) is invoked + * @remarks Called when someone is about to be hit by a Tank rock or lunged by a Hunter + * @remarks Called multiple times when someone is about to be has been pounced by a Hunter + * @remarks You can use the "KNOCKDOWN_*" enum values for the reason + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim Client index of the victim + * @param reason The Knockdown reason type. 1=Hunter lunge, 2=Tank rock + * + * @noreturn + **/ +forward void L4D_OnKnockedDown_PostHandled(int client, int reason); + +/** + * @brief Called when ThrowImpactedSurvivor(CTerrorPlayer *, CTerrorPlayer *, float, bool) is invoked + * @remarks Called when a player is about to be flung by a Charger impact + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @return Plugin_Handled to block fling, Plugin_Continue to allow + **/ +// L4D2 only +forward Action L4D2_OnThrowImpactedSurvivor(int attacker, int victim); + +/** + * @brief Called when ThrowImpactedSurvivor(CTerrorPlayer *, CTerrorPlayer *, float, bool) is invoked + * @remarks Called when a player is flung by a Charger impact + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnThrowImpactedSurvivor_Post(int attacker, int victim); + +/** + * @brief Called when ThrowImpactedSurvivor(CTerrorPlayer *, CTerrorPlayer *, float, bool) is invoked + * @remarks Called when a player is flung by a Charger impact + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnThrowImpactedSurvivor_PostHandled(int attacker, int victim); + +/** + * @brief Called when CDeathFallCamera::Enable(CBasePlayer*) is invoked + * @remarks Called when a player is falling in a fatal zone + * @remarks Does not trigger for all cases when someone is fatally falling + * @remarks Use this forward to check if the current map has death fall cameras (fatal falls) + * + * @param client Client index of the player. Can be 0 + * @param camera Death fall camera index + * + * @return Plugin_Handled to block the death fall camera, Plugin_Continue to allow + **/ +forward Action L4D_OnFatalFalling(int client, int camera); + +/** + * @brief Called when CTerrorPlayer::OnFalling() is invoked + * @remarks Called when a player is falling + * + * @param client Client index of the player + **/ +forward void L4D_OnFalling(int client); + +/** + * @brief Called when CTerrorPlayer::Cough() is invoked + * @remarks Called when a player is coughing, most likely from Smoker Cloud, but possibly called by other plugins + * + * @param client Client index of the player affected + * @param attacker Client index who caused the cough, can be 0 after a while when the AI special infected is kicked + * + * @return return Plugin_Handled to block, Plugin_Continue otherwise + **/ +forward Action L4D_OnPlayerCough(int client, int attacker); + +/** + * @brief Called when CTerrorPlayer::Cough() is invoked + * @remarks Called when a player is coughing, most likely from Smoker Cloud, but possibly called by other plugins + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player affected + * @param attacker Client index who caused the cough, can be 0 after a while when the AI special infected is kicked + * + * @noreturn + **/ +forward void L4D_OnPlayerCough_Post(int client, int attacker); + +/** + * @brief Called when CTerrorPlayer::Cough() is invoked + * @remarks Called when a player is coughing, most likely from Smoker Cloud, but possibly called by other plugins + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client Client index of the player affected + * @param attacker Client index who caused the cough, can be 0 after a while when the AI special infected is kicked + * + * @noreturn + **/ +forward void L4D_OnPlayerCough_PostHandled(int client, int attacker); + +/** + * @brief Called whenever CInferno::Spread(Vector const&) is invoked (only for spitters -- ignores fire) + * + * @param spitter spitter that spat (:D) + * @param projectile spitter's projectile entity + * @param x x coordinate of the new acid puddle (can be overridden) + * @param y y coordinate of the new acid puddle (can be overridden) + * @param z z coordinate of the new acid puddle (can be overridden) + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// 2020 Left4DHooks update: Works for Molotovs and Spitters +// return Plugin_Handled to make small fire or goo puddle +// x,y,z has no affect, is 0,0,0 for spitter, molotovs is area size or something +forward Action L4D2_OnSpitSpread(int spitter, int projectile, float &x, float &y, float &z); + +/** + * @brief Called whenever CTerrorPlayer::Extinguish() is invoked + * @remarks Called when a player (Survivor or Special Infected) is about to be extinguished + * + * @param client the client who is about to be extinguished + * + * @return Plugin_Handled to block extinguishing, Plugin_Continue otherwise + */ +forward Action L4D_PlayerExtinguish(int client); + +/** + * @brief Called when SurvivorBot::UseHealingItems(Action *) is invoked + * @remarks Causes bots to use or give healing items (except in safe room on non-expert) + * + * @param client the client that will decide whether to use healing items + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// 2020 Left4DHooks update: Blocked on L4D1/L4D2 Linux to prevent crashes. Waiting for DHooks update to support object returns +forward Action L4D2_OnUseHealingItems(int client); + +/** + * @brief Called after SurvivorBot::FindScavengeItem(Action *) is invoked + * @remarks Indicates which item the Survivor Bot will attempt to pick up + * + * @param client the client that will try to pick something up + * @param item the item the client will try to pick up (null means no item) + * + * @return Plugin_Handled to block, Plugin_Changed to overwrite item, Plugin_Continue otherwise + */ +forward Action L4D2_OnFindScavengeItem(int client, int &item); + +/** + * @brief Called whenever BossZombiePlayer(CTerrorPlayer *, int, CBaseEntity *) is invoked + * @remarks Called when Special Infected are targeting a victim + * + * @param specialInfected the SI entity index + * @param curTarget the survivor player index who is chosen victim + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D2_OnChooseVictim(int specialInfected, int &curTarget); + +/** + * @brief Called whenever CTerrorPlayer::OnPouncedOnSurvivor() is invoked + * @remarks Called when a Survivor player is about to be pounced on by a Hunter + * + * @param victim the client who's being pounced + * @param attacker the Hunter pouncing on someone + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnPouncedOnSurvivor(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnPouncedOnSurvivor() is invoked + * @remarks Called when a Survivor player is about to be pounced on by a Hunter + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being pounced + * @param attacker the Hunter pouncing on someone + * + * @noreturn + */ +forward void L4D_OnPouncedOnSurvivor_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnPouncedOnSurvivor() is invoked + * @remarks Called when a Survivor player is about to be pounced on by a Hunter + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being pounced + * @param attacker the Hunter pouncing on someone + * + * @noreturn + */ +forward void L4D_OnPouncedOnSurvivor_PostHandled(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::GrabVictimWithTongue() is invoked + * @remarks Called when a Survivor player is about to be grabbed by a Smoker + * + * @param victim the client who's being grabbed + * @param attacker the Smoker grabbing someone + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +forward Action L4D_OnGrabWithTongue(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::GrabVictimWithTongue() is invoked + * @remarks Called when a Survivor player is grabbed by a Smoker + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Smoker grabbing someone + * + * @noreturn + */ +forward void L4D_OnGrabWithTongue_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::GrabVictimWithTongue() is invoked + * @remarks Called when a Survivor player is grabbed by a Smoker + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Smoker grabbing someone + * + * @noreturn + */ +forward void L4D_OnGrabWithTongue_PostHandled(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnLeptOnSurvivor() is invoked + * @remarks Called when a Survivor player is about to be ridden by a Jockey + * + * @param victim the client who's being grabbed + * @param attacker the Jockey grabbing someone + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnJockeyRide(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnLeptOnSurvivor() is invoked + * @remarks Called when a Survivor player is starting to be ridden by a Jockey + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Jockey grabbing someone + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnJockeyRide_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnLeptOnSurvivor() is invoked + * @remarks Called when a Survivor player is starting to be ridden by a Jockey + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Jockey grabbing someone + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnJockeyRide_PostHandled(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnSlammedSurvivor() is invoked + * @remarks Called when a Survivor is slammed into a wall by a Charger, or on the first pummel if bWallSlam is 0 + * @remarks bDeadlyCharge seems to always return 1 on Windows + * + * @param victim the client who's being slammed + * @param attacker the Charger slamming someone + * @param bWallSlam when slammed into a wall. Changing this can play a different animation + * @param bDeadlyCharge indicates the carry ends at a height down 360.0 units from the carry start, and adds DMG_PARALYZE to the damage flags to incap the victim. Changing this can incap the victim + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnSlammedSurvivor(int victim, int attacker, bool &bWallSlam, bool &bDeadlyCharge); + +/** + * @brief Called whenever CTerrorPlayer::OnSlammedSurvivor() is invoked + * @remarks Called when a Survivor is slammed into a wall by a Charger, or on the first pummel if bWallSlam is 0 + * @bDeadlyCharge seems to always return 1 on Windows + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being slammed + * @param attacker the Charger slamming someone + * @param bWallSlam when slammed into a wall. Changing this can play a different animation + * @param bDeadlyCharge indicates the carry ends at a height down 360.0 units from the carry start, and adds DMG_PARALYZE to the damage flags to incap the victim. Changing this can incap the victim + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnSlammedSurvivor_Post(int victim, int attacker, bool bWallSlam, bool bDeadlyCharge); + +/** + * @brief Called whenever CTerrorPlayer::OnSlammedSurvivor() is invoked + * @remarks Called when a Survivor is slammed into a wall by a Charger, or on the first pummel if bWallSlam is 0 + * @bDeadlyCharge seems to always return 1 on Windows + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being slammed + * @param attacker the Charger slamming someone + * @param bWallSlam when slammed into a wall. Changing this can play a different animation + * @param bDeadlyCharge indicates the carry ends at a height down 360.0 units from the carry start, and adds DMG_PARALYZE to the damage flags to incap the victim. Changing this can incap the victim + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnSlammedSurvivor_PostHandled(int victim, int attacker, bool bWallSlam, bool bDeadlyCharge); + +/** + * @brief Called whenever CTerrorPlayer::OnStartCarryingVictim() is invoked + * @remarks Called when a Survivor player is about to be carried by a Charger + * + * @param victim the client who's being grabbed + * @param attacker the Charger picking up someone + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnStartCarryingVictim(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnStartCarryingVictim() is invoked + * @remarks Called when a Survivor player is about to be carried by a Charger + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Charger picking up someone + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnStartCarryingVictim_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnStartCarryingVictim() is invoked + * @remarks Called when a Survivor player is about to be carried by a Charger + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's being grabbed + * @param attacker the Charger picking up someone + * + * @noreturn + */ +// L4D2 only +forward void L4D2_OnStartCarryingVictim_PostHandled(int victim, int attacker); + +/** + * @brief Called when CCharge::ImpactStagger is invoked + * @remarks Called when a Charger impacts a wall or object after charging, but not when carrying a Survivor + * @remarks Can be used to determine if someone is being staggered from this impact, L4D2_OnStagger should trigger in the same frame + * + * @param client Client index + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnChargerImpact(int client); + +/** + * @brief Called when CTerrorPlayer::QueuePummelVictim is invoked + * @remarks Called when a player is about to be pummelled by a Charger + * @remarks To block the stumble animation and getting stuck inside a Charger see the "L4D2_OnPummelVictim" section for a demonstration in "left4dhooks_test.sp" + * @remarks Note: when blocking pummel the Survivor will be stuck inside the Charger (eventually teleporting them) and AI chargers cannot move. See the above demo for a solution + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @return Plugin_Handled to block pummel, Plugin_Continue to allow + **/ +// L4D2 only +forward Action L4D2_OnPummelVictim(int attacker, int victim); + +/** + * @brief Called when CTerrorPlayer::QueuePummelVictim is invoked + * @remarks Called when a player is about to be pummelled by a Charger + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnPummelVictim_Post(int attacker, int victim); + +/** + * @brief Called when CTerrorPlayer::QueuePummelVictim is invoked + * @remarks Called when a player is about to be pummelled by a Charger + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param attacker Client index of the attacker + * @param victim Client index of the victim + * + * @noreturn + **/ +// L4D2 only +forward void L4D2_OnPummelVictim_PostHandled(int attacker, int victim); + +/** + * @brief Called whenever CTerrorPlayer::OnVomitedUpon is invoked + * @remarks Called when a Survivor player is covered in Boomer bile, or when using "Bile the World" plugin by "AtomicStryker" + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * @param boomerExplosion true if triggered by a boommer explosion + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D_OnVomitedUpon(int victim, int &attacker, bool &boomerExplosion); + +/** + * @brief Called whenever CTerrorPlayer::OnVomitedUpon is invoked + * @remarks Called when a Survivor player is covered in Boomer bile, or when using "Bile the World" plugin by "AtomicStryker" + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * @param boomerExplosion true if triggered by a boommer explosion + * + * @noreturn + */ +forward void L4D_OnVomitedUpon_Post(int victim, int attacker, bool boomerExplosion); + +/** + * @brief Called whenever CTerrorPlayer::OnVomitedUpon is invoked + * @remarks Called when a Survivor player is covered in Boomer bile, or when using "Bile the World" plugin by "AtomicStryker" + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * @param boomerExplosion true if triggered by a boommer explosion + * + * @noreturn + */ +forward void L4D_OnVomitedUpon_PostHandled(int victim, int attacker, bool boomerExplosion); + +/** + * @brief Called whenever CTerrorPlayer::OnHitByVomitJar is invoked + * @remarks Called when a Special Infected is about to be hit from a Bilejar explosion + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * + * @return Plugin_Handled to block, Plugin_Changed to use overwritten values from plugin, Plugin_Continue otherwise + */ +forward Action L4D2_OnHitByVomitJar(int victim, int &attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnHitByVomitJar is invoked + * @remarks Called when a Special Infected is hit from a Bilejar explosion + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * + * @noreturn + */ +forward void L4D2_OnHitByVomitJar_Post(int victim, int attacker); + +/** + * @brief Called whenever CTerrorPlayer::OnHitByVomitJar is invoked + * @remarks Called when a Special Infected is hit from a Bilejar explosion + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param victim the client who's now it + * @param attacker the attacker who caused the vomit (can be 0) + * + * @noreturn + */ +forward void L4D2_OnHitByVomitJar_PostHandled(int victim, int attacker); + +/** + * @brief Called whenever CPipeBombProjectile::Create is invoked + * @remarks Called when a PipeBomb projectile is being created + * + * @param client the client who is throwing the grenade (can be 0) + * @param vecPos the position vector of the projectile + * @param vecAng the angle vector of the projectile + * @param vecVel the velocity vector of the projectile + * @param vecRot the rotation vector of the projectile + * + * @return Plugin_Handled to block the grenade creation, Plugin_Changed to modify the vector values, Plugin_Continue otherwise + */ +forward Action L4D_PipeBombProjectile_Pre(int client, float vecPos[3], float vecAng[3], float vecVel[3], float vecRot[3]); + +/** + * @brief Called whenever CPipeBombProjectile::Create is invoked + * @remarks Called when a PipeBomb projectile has been created + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client who is throwing the grenade + * @param projectile the projectile entity index (can be 0 if blocked in the pre hook) + * @param vecPos the position vector of the projectile + * @param vecAng the angle vector of the projectile + * @param vecVel the velocity vector of the projectile + * @param vecRot the rotation vector of the projectile + * + * @noreturn + */ +forward void L4D_PipeBombProjectile_Post(int client, int projectile, const float vecPos[3], const float vecAng[3], const float vecVel[3], const float vecRot[3]); + +/** + * @brief Called whenever CPipeBombProjectile::Create is invoked + * @remarks Called when a PipeBomb projectile has been created + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client who is throwing the grenade (can be -1 if blocked) + * @param projectile the projectile entity index (can be 0 if blocked in the pre hook) + * @param vecPos the position vector of the projectile + * @param vecAng the angle vector of the projectile + * @param vecVel the velocity vector of the projectile + * @param vecRot the rotation vector of the projectile + * + * @noreturn + */ +forward void L4D_PipeBombProjectile_PostHandled(int client, int projectile, const float vecPos[3], const float vecAng[3], const float vecVel[3], const float vecRot[3]); + +/** + * @brief Called whenever CMolotovProjectile::Detonate is invoked + * @remarks Called when a Molotov projectile is about to explode + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @return Plugin_Handled to block explosion which will cause the Molotov projectile to bounce remain active, Plugin_Continue otherwise + */ +forward Action L4D_Molotov_Detonate(int entity, int client); + +/** + * @brief Called whenever CMolotovProjectile::Detonate is invoked + * @remarks Called when a Molotov projectile is about to explode + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +forward void L4D_Molotov_Detonate_Post(int entity, int client); + +/** + * @brief Called whenever CMolotovProjectile::Detonate is invoked + * @remarks Called when a Molotov projectile is about to explode + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +forward void L4D_Molotov_Detonate_PostHandled(int entity, int client); + +/** + * @brief Called whenever CPipeBombProjectile::Detonate is invoked + * @remarks Called when a PipeBomb projectile is about to explode + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @return Plugin_Handled to block explosion which will cause the PipeBomb projectile to continue flashing and remain active, Plugin_Continue otherwise + */ +forward Action L4D_PipeBomb_Detonate(int entity, int client); + +/** + * @brief Called whenever CPipeBombProjectile::Detonate is invoked + * @remarks Called when a PipeBomb projectile is about to explode + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +forward void L4D_PipeBomb_Detonate_Post(int entity, int client); + +/** + * @brief Called whenever CPipeBombProjectile::Detonate is invoked + * @remarks Called when a PipeBomb projectile is about to explode + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +forward void L4D_PipeBomb_Detonate_PostHandled(int entity, int client); + +/** + * @brief Called whenever CVomitJarProjectile::Detonate is invoked + * @remarks Called when a VomitJar projectile is about to explode + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @return Plugin_Handled to block explosion which will cause the Vomitjar projectile to bounce and remain active, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_VomitJar_Detonate(int entity, int client); + +/** + * @brief Called whenever CVomitJarProjectile::Detonate is invoked + * @remarks Called when a VomitJar projectile is about to explode + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +// L4D2 only +forward void L4D2_VomitJar_Detonate_Post(int entity, int client); + +/** + * @brief Called whenever CVomitJarProjectile::Detonate is invoked + * @remarks Called when a VomitJar projectile is about to explode + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param entity the entity that exploded + * @param client the client who threw the grenade, can be -1 + * + * @noreturn + */ +// L4D2 only +forward void L4D2_VomitJar_Detonate_PostHandled(int entity, int client); + +/** + * @brief Called whenever CInsectSwarm::CanHarm() is invoked + * @remarks Called when Spitter Acid is determining if a client or entity can be damaged + * + * @param acid the acid entity index causing the damage + * @param spitter the Spitter or client who created the acid (can be 0 or -1) + * @param entity the client or entity index being checked if it can be damaged + * + * @return Plugin_Handled to block allowing damage to an entity, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_CInsectSwarm_CanHarm(int acid, int spitter, int entity); + +/** + * @brief Called whenever CInsectSwarm::CanHarm() is invoked + * @remarks Called when Spitter Acid has determining if a client or entity can be damaged, or not called when block in the pre forward + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param acid the acid entity index causing the damage + * @param spitter the Spitter or client who created the acid (can be 0 or -1) + * @param entity the client or entity index being checked if it can be damaged + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CInsectSwarm_CanHarm_Post(int acid, int spitter, int entity); + +/** + * @brief Called whenever CInsectSwarm::CanHarm() is invoked + * @remarks Called when Spitter Acid has determining if a client or entity can be damaged + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param acid the acid entity index causing the damage + * @param spitter the Spitter or client who created the acid (can be 0 or -1) + * @param entity the client or entity index being checked if it can be damaged + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CInsectSwarm_CanHarm_PostHandled(int acid, int spitter, int entity); + +/** + * @brief Called whenever CBreakableProp::Break() is invoked + * @remarks Called when a physics prop is broken + * @note When a propanetank explodes, it will create and explode another prop_physics and the attacker entity will be 0. Maybe only L4D2 has this issue + * + * @param prop the physics entity index which broke + * @param entity the client or entity who caused the prop to break (could be 0) + * + * @noreturn + */ +forward void L4D_CBreakableProp_Break(int prop, int entity); + +/** + * @brief Called whenever CFirstAidKit::StartHealing() is invoked + * @remarks Called when a player is using a first aid kit to heal + * @note: Detouring as a pre-hook for changing "first_aid_heal_percent" per player before healing finishes. + * @note: Detouring as a post-hook for changing "first_aid_heal_percent" back to default value after healing finishes. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @return Plugin_Handled to block healing, Plugin_Continue otherwise + */ +// L4D1 only +forward Action L4D1_FirstAidKit_StartHealing(int client, int entity); + +/** + * @brief Called whenever CFirstAidKit::StartHealing() is invoked + * @remarks Called when a player is using a first aid kit to heal + * @note: Detouring as a pre-hook for changing "first_aid_heal_percent" per player before healing finishes. + * @note: Detouring as a post-hook for changing "first_aid_heal_percent" back to default value after healing finishes. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @noreturn + */ +// L4D1 only +forward void L4D1_FirstAidKit_StartHealing_Post(int client, int entity); + +/** + * @brief Called whenever CFirstAidKit::StartHealing() is invoked + * @remarks Called when a player is using a first aid kit to heal + * @note: Detouring as a pre-hook for changing "first_aid_heal_percent" per player before healing finishes. + * @note: Detouring as a post-hook for changing "first_aid_heal_percent" back to default value after healing finishes. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @noreturn + */ +// L4D1 only +forward void L4D1_FirstAidKit_StartHealing_PostHandled(int client, int entity); + +/** + * @brief Called whenever sourcemodCBaseBackpackItem::StartAction() is invoked + * @remarks Called when a player is using an item and about to use it + * @note: Detouring as a pre-hook for changing the following per player before starting any actions: + * - "first_aid_kit_use_duration" + * - "ammo_pack_use_duration" + * - "cola_bottles_use_duration" + * - "defibrillator_use_duration" + * - "gas_can_use_duration" + * - "upgrade_pack_use_duration" + * @note: Detouring as a post-hook for changing the above back to default values after starting any actions. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @return Plugin_Handled to block healing, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_BackpackItem_StartAction(int client, int entity); + +/** + * @brief Called whenever sourcemodCBaseBackpackItem::StartAction() is invoked + * @remarks Called when a player is using an item and about to use it + * @note: Detouring as a pre-hook for changing the following per player before starting any actions: + * - "first_aid_kit_use_duration" + * - "ammo_pack_use_duration" + * - "cola_bottles_use_duration" + * - "defibrillator_use_duration" + * - "gas_can_use_duration" + * - "upgrade_pack_use_duration" + * @note: Detouring as a post-hook for changing the above back to default values after starting any actions. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @noreturn + */ +// L4D2 only +forward void L4D2_BackpackItem_StartAction_Post(int client, int entity); + +/** + * @brief Called whenever sourcemodCBaseBackpackItem::StartAction() is invoked + * @remarks Called when a player is using an item and about to use it + * @note: Detouring as a pre-hook for changing the following per player before starting any actions: + * - "first_aid_kit_use_duration" + * - "ammo_pack_use_duration" + * - "cola_bottles_use_duration" + * - "defibrillator_use_duration" + * - "gas_can_use_duration" + * - "upgrade_pack_use_duration" + * @note: Detouring as a post-hook for changing the above back to default values after starting any actions. + * + * @param client the client performing the action + * @param entity the medkit entity they are using + * + * @noreturn + */ +// L4D2 only +forward void L4D2_BackpackItem_StartAction_PostHandled(int client, int entity); + +/** + * @brief Called whenever CGasCan::Event_Killed() is invoked + * @remarks Called when a gascan is broken + * + * @param gascan the gascan entity index + * @param inflictor the inflictor entity index + * @param attacker the attacker entity index + * + * @return Plugin_Handled to block detonating, Plugin_Changed to change any values, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_CGasCan_EventKilled(int gascan, int &inflictor, int &attacker); + +/** + * @brief Called whenever CGasCan::Event_Killed() is invoked + * @remarks Called when a gascan is broken + * + * @param gascan the gascan entity index + * @param inflictor the inflictor entity index + * @param attacker the attacker entity index + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_EventKilled_Post(int gascan, int inflictor, int attacker); + +/** + * @brief Called whenever CGasCan::Event_Killed() is invoked + * @remarks Called when a gascan is broken + * + * @param gascan the gascan entity index + * @param inflictor the inflictor entity index + * @param attacker the attacker entity index + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_EventKilled_PostHandled(int gascan, int inflictor, int attacker); + +/** + * @brief Called whenever CGasCan::ShouldStartAction() is invoked + * @remarks Called when someone is about to pour a gascan into a nozzle + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @return Plugin_Handled to block adding to Scavenge score (see "Scavenge Score Fix" plugin for more details), Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_CGasCan_ShouldStartAction(int client, int gascan, int nozzle); + +/** + * @brief Called whenever CGasCan::ShouldStartAction() is invoked + * @remarks Called when someone has started to pour a gascan into a nozzle + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_ShouldStartAction_Post(int client, int gascan, int nozzle); + +/** + * @brief Called whenever CGasCan::ShouldStartAction() is invoked + * @remarks Called when someone has started to pour a gascan into a nozzle + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_ShouldStartAction_PostHandled(int client, int gascan, int nozzle); + +/** + * @brief Called whenever CGasCan::OnActionComplete() is invoked + * @remarks Called when someone is about to complete pouring a gascan into a nozzle + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @return Plugin_Handled to block adding to Scavenge score (see "Scavenge Score Fix" plugin for more details), Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_CGasCan_ActionComplete(int client, int gascan, int nozzle); + +/** + * @brief Called whenever CGasCan::OnActionComplete() is invoked + * @remarks Called when someone completes pouring a gascan into a nozzle + * @remarks This forward will not trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_ActionComplete_Post(int client, int gascan, int nozzle); + +/** + * @brief Called whenever CGasCan::OnActionComplete() is invoked + * @remarks Called when someone completes pouring a gascan into a nozzle + * @remarks This forward will ONLY trigger if the relative pre-hook forward has been blocked with Plugin_Handled + * + * @param client the client pouring + * @param gascan the gascan entity index that is being consumed + * @param nozzle the nozzle being poured into + * + * @noreturn + */ +// L4D2 only +forward void L4D2_CGasCan_ActionComplete_PostHandled(int client, int gascan, int nozzle); + +/** + * @brief Returns the current game mode type when it changes. 0=Unknown or error. 1=Coop. 2=Versus. 4=Survival. 8=Scavenge (L4D2) + * @remarks You can use the "GAMEMODE_*" enums provided above to match the mode + * @remarks Only triggers when the server starts and after when the game mode changes + * + * @param gamemode Current game mode + * + * @noreturn + */ +forward void L4D_OnGameModeChange(int gamemode); + +/** + * @brief Called when the server changes hibernation status + * + * @param hibernating true when hibernating, false when waking up + * + * @noreturn + */ +forward void L4D_OnServerHibernationUpdate(bool hibernating); + +/** + * @brief Called when the client's material system is expecting instructions from the server in regards to addons + * @remarks Doesn't fire if l4d2_addons_eclipse is -1 or 0 + * + * @param SteamID SteamID of the client expecting a matsys reply + * + * @return Plugin_Handled to let the client through with addons, Plugin_Continue otherwise + */ +// L4D2 only +forward Action L4D2_OnClientDisableAddons(const char[] SteamID); + +/** + * @brief Called whenever InfectedShoved::OnShoved(Infected *, CBaseEntity *) is invoked + * @remarks Called when common Infected are about to get shoved + * + * @return Plugin_Handled to block, Plugin_Continue otherwise + */ +#pragma deprecated This was never enabled +forward Action L4D_OnInfectedShoved(int infected, int entity); + +/** + * @brief Called whenever CBasePlayer::WaterMove() is invoked + * @remarks Couple it with a FL_INWATER check to be sure + * + * @param client the client that is moving in the water + * + * @noreturn + */ +#pragma deprecated Does not return water state. Use FL_INWATER instead. See Swimming plugin for L4D/2 +forward void L4D2_OnWaterMove(int client); + +/** + * @brief Called whenever ZombieManager::GetRandomPZSpawnPosition is invoked + * @remarks Attempts to find a valid position to spawn Special Infected + * + * @param client Client id to find an area near this player + * @param zombieClass Special Infected class to search for a spawn position for + * @param attempts How many tries to find a valid location + * @param vecPos The vector location. Sometimes is 0,0,0. Use post hook for real selected position + * + * @return Plugin_Changed to change any values, Plugin_Continue otherwise + */ +#pragma deprecated Removed because it spawns specials at 0,0,0 when modifying any value +forward Action L4D_OnGetRandomPZSpawnPosition(int &client, int &zombieClass, int &attempts, float vecPos[3]); + + + + + +// ==================================================================================================== +// NATIVES - Silvers +// ==================================================================================================== +/** + * @brief Returns the address pointer to various internal game objects + * + * @param ptr_type Using the PointerType enum to select which pointer to return + * + * @return Address pointer or 0 on failure + */ +native Address L4D_GetPointer(PointerType ptr_type); + +/** + * @brief Returns a client index from a memory address + * + * @param addy Address to check + * + * @return Client index or 0 on failure + */ +native int L4D_GetClientFromAddress(Address addy); + +/** + * @brief Returns an entity index from a memory address + * + * @param addy Address to check + * + * @return Entity index or -1 on failure + */ +native int L4D_GetEntityFromAddress(Address addy); + +/** + * @brief Returns a string read from a memory address + * + * @param addy Address to check + * + * @return Entity index or -1 on failure + */ +native int L4D_ReadMemoryString(Address addy, char[] buffer, int maxlength); + +/** + * @brief Returns the servers operating system + * + * @return 0=Windows. 1=Linux + */ +native int L4D_GetServerOS(); + +/** + * @brief Returns the Left4DHooks version number. For example version "1.122" is 1122 + * @note This will only work from Left4DHooks version 1.122 or newer + * + * @remarks Use to verify a newer version is running from a certain version number, where for example a new native or forward was added + * @remarks Each version number will be greater than the previous + * @remarks Example code: + * @remarks Put: MarkNativeAsOptional("Left4DHooks_Version") in your plugins "AskPluginLoad2" section + * @remarks Then run this code to determine the version: + * @remarks if( GetFeatureStatus(FeatureType_Native, "Left4DHooks_Version") == FeatureStatus_Available && Left4DHooks_Version() >= 1122 ) + * + * @remarks Alternatively, to support all versions, it would be better to use the "left4dhooks_version" convar, retrieve as a float and check + * @remarks For example: FindConVar("left4dhooks_version").FloatValue >= 1.122 + * + * @return Version number + */ +native int Left4DHooks_Version(); + +/** +* @brief Returns an entities script scope (HSCRIPT) +* +* @param entity The entity to retrieve it's script scope +* +* @return Script scope or 0 if none +*/ +// L4D2 only +native int L4D2_GetScriptScope(int entity); + +/** +* @brief Creates or uses an existing "logic_script" entity that is created by Left4DHooks +* @remarks Do NOT use entity outputs as this entity is shared by other plugins +* +* @return VScript "logic_script" entity index +* @error 0 on error +*/ +// L4D2 only +native int L4D2_GetVScriptEntity(); + +/** +* @brief Runs a specified VScript code +* @remarks Saves having to create an entity. The entity can remain alive and used again +* @remarks unless the core plugins define KILL_VSCRIPT is changed and the plugin recompiled +* +* @param code The VScript code to execute. Maximum length seems to be 1006 characters +* +* @return True on success, false otherwise +* @error Invalid code or failed to create logic_script +*/ +// L4D2 only +native bool L4D2_ExecVScriptCode(char[] code); + +/** +* @brief Runs a specified VScript code and returns values from it +* @remarks Can execute several code blocks on a single line separating them with ; as standard coding practice +* @remarks Can also execute several lines of code from SourcePawn, you must end the line with a backslash +* @remarks Can return specific data by wrapping what you want to return within "" and "" +* @remarks See the test plugin for examples to all the above +* +* @param code The VScript code to execute. Maximum length seems to be 1006 characters +* @param buffer Buffer to copy return data to. You can use StringToInt or StringToFloat if required +* @param maxlength Maximum size of the buffer +* +* @return True on success, false otherwise +* @error Invalid code or failed to create logic_script or possibly an empty string +*/ +// L4D2 only +native bool L4D2_GetVScriptOutput(char[] code, char[] buffer, int maxlength); + +/** + * @brief Returns the current game mode type. 0=Unknown or error. 1=Coop. 2=Versus. 4=Survival. 8=Scavenge (L4D2) + * @remarks You can use the "GAMEMODE_*" enums provided above to match the mode + * + * @return Current game mode + */ +native int L4D_GetGameModeType(); + +/** + * @brief Deafens a player with a high pitch ringing sound for a few seconds + * @remarks Used in the "Prototype Grenades" plugin by Silvers + * + * @param client Client id of the player to deafen + * + * @noreturn + */ +native void L4D_Deafen(int client); + +/** + * @brief Returns a Survivors current temporary health buffer HP + * + * @param client Client id of the Survivor player + * + * @return Temp health value + */ +native float L4D_GetTempHealth(int client); + +/** + * @brief Sets a Survivors temporary health buffer HP + * + * @param client Client id of the Survivor player + * @param health Health value to set + * + * @noreturn + */ +native void L4D_SetTempHealth(int client, float health); + +/** + * @brief Returns the reserve ammo for a specific players weapon + * + * @param client Client id of the Survivor player + * @param weapon Weapon entity index to affect + * + * @return Reserve ammo count + */ +native int L4D_GetReserveAmmo(int client, int weapon); + +/** + * @brief Sets the reserve ammo for a specific players weapon + * + * @param client Client id of the Survivor player + * @param weapon Weapon entity index to affect + * @param ammo Reserve ammo count to set + * + * @noreturn + */ +native void L4D_SetReserveAmmo(int client, int weapon, int ammo); + +/** + * @brief Plays specified music string name on the music channel to a client + * @remarks Music strings such as "Event.BleedingOut" + * @remarks List of strings can be found inside the games VPK files here: scripts\game_sounds_music.txt + * + * @param client Client id of the Survivor player + * @param music_str Music string name to play + * @param source_ent Source entity to play from (can be 0) + * @param one_float Unknown, maybe duration? Please report what this is when using + * @param one_bool Unknown. Please report what this is when using + * @param two_bool Unknown. Please report what this is when using + * + * @noreturn + */ +native void L4D_PlayMusic(int client, const char[] music_str, int source_ent = 0, float one_float, bool one_bool, bool two_bool); + +/** + * @brief Stops playing the specified music_str to the client + * @remarks Music strings such as "Event.BleedingOut" + * @remarks List of strings can be found inside the games VPK files here: scripts\game_sounds_music.txt + * + * @param client Client id of the Survivor player + * @param music_str Music string name to stop playing + * @param one_float Unknown, maybe duration? Please report what this is when using + * @param one_bool Unknown. Please report what this is when using + * + * @noreturn + */ +native void L4D_StopMusic(int client, const char[] music_str, float one_float = 0.0, bool one_bool = false); + +/** + * @brief Creates the dissolve effect on common infected, players or objects + * @remarks You must handle the fading or killing of an entity as required + * @remarks Used in the "Dissolve Infected" plugin by Silvers + * + * @param entity The entity to dissolve + * + * @return Entity index of the dissolver, which should automatically delete itself when the effect is done + */ +native int L4D_Dissolve(int entity); + +/** + * @brief Removes the boomer vomit effect from a player + * + * @param client Client id of the player to remove the effect from + * + * @noreturn + */ +native void L4D_OnITExpired(int client); + +/** + * @brief Returns the estimated fall damage of a player + * @remarks This only gives an estimate and not the actual damage the player is likely to receive + * @remarks The value maxes out at 400.0. Use SourceScamble to modify "FallingDamageForSpeed(float)" and change the minimum and maximum values + * + * @param client Client id of the player + * + * @return Estimated falling damage value + */ +native float L4D_EstimateFallingDamage(int client); + +/** + * @brief Returns the worldspace center of an entity + * + * @param entity The entity to use + * @param vecPos The entities worldspace center returned vector + * + * @noreturn + */ +native void L4D_GetEntityWorldSpaceCenter(int entity, float vecPos[3]); + +/** + * @brief Sets a physics entity angular velocity vector + * @remarks Spins an entity, for example used in "Throwable Melee Weapons" plugin by Silvers + * @remarks See the "left4dhooks_test" plugin for an example on spinning the entity top over or sideways + * + * @param entity The entity to spin + * @param vecAng Angular velocity vector, director to spin the projectile + * + * @noreturn + */ +native void L4D_AngularVelocity(int entity, const float vecAng[3]); + +/** + * @brief Attempts to find a random valid position to spawn a Special Infected + * @remarks The zombieClass does not matter but different values yield different results: + * @remarks Using the Tank zombieClass probably searches for a larger area that's clear of objects + * + * @param client Client id to find an area near this player. Accepts 0 to find a random area instead + * @param zombieClass Special Infected class to search for a spawn position for + * @param attempts How many tries to find a valid location + * @param vecPos The vector array to store the valid location on success + * + * @return True on success, false on failure to find valid location + */ +native bool L4D_GetRandomPZSpawnPosition(int client, int zombieClass, int attempts, float vecPos[3]); + +/** + * @brief Given a vector position, returns the relative NavArea + * @remarks This is more reliable than L4D2Direct_GetTerrorNavArea + * + * @param vecPos The vector array to use to retrieve the NavArea + * @param maxDist Furthest distance to the nearest nav area + * @param anyZ Any ground position? + * @param checkLOS Check line of sight + * @param checkGround Check if on ground? + * @param teamID Team ID to check for + * + * @return The NavArea value, or 0 on failure probably + */ +native any L4D_GetNearestNavArea(const float vecPos[3], float maxDist = 300.0, bool anyZ = false, bool checkLOS = false, bool checkGround = false, int teamID = 2); + +/** + * @brief Returns the nav address of the last known area + * + * @param client The client to check + * + * @return The nav area address or 0 on fail + */ +native any L4D_GetLastKnownArea(int client); + +/** + * @brief Gets the first Special Infected type the Director will spawn. Value set on map start + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * + * @return zombieClass of the Special Infected first spawning + */ +// L4D2 only +native int L4D2_GetFirstSpawnClass(); + +/** + * @brief Sets the first Special Infected type the Director will spawn + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * + * @noreturn + */ +// L4D2 only +native void L4D2_SetFirstSpawnClass(int zombieClass); + +/** + * @brief Gets the maximum flow distance any survivor has achieved + * + * @return Returns the maximum flow distance any survivor has achieved + */ +// L4D2 only +native float L4D2_GetFurthestSurvivorFlow(); + +/** + * @brief Given a nav area value, returns a randomly selected position for spawning + * @remarks This is what Witches use to spawn + * + * @param NavArea The NavArea to search for a valid location + * @param vecPos The vector array to store the valid location on success + * + * @noreturn + */ +native void L4D_FindRandomSpot(int NavArea, float vecPos[3]); + +/** + * @brief Checks if a player is visible to a specified position. Should be slightly faster than using TR_TraceRayFilterEx + * + * @param client Client to check visibility from + * @param vecPos The vector position of the target location + * @param team The team of the client, can possibly pass 0 to 3 + * @param team_target Target point team, if it is 0, the client's angle will be considered + * @param NavArea NavArea of ​​the target, or 0 to automatically get with GetNearestNavArea + * + * @return True if visible, false otherwise + */ +native bool L4D2_IsVisibleToPlayer(int client, int team, int team_target, int NavArea, float vecPos[3]); + +/** + * @brief Teleports a player to a valid position if they are stuck + * + * @param client Client to perform the action + * + * @noreturn + */ +native void L4D_WarpToValidPositionIfStuck(int client); + +/** + * @brief Returns true when any survivor has left the starting area and true in Versus when the saferoom door automatically opens + * + * @return True if a survivor has left the starting area. False otherwise + */ +native bool L4D_HasAnySurvivorLeftSafeArea(); + +/** + * @brief Returns true when any survivor is in the starting checkpoint area + * + * @return True if any survivor is in the starting checkpoint area. False otherwise + */ +native bool L4D_IsAnySurvivorInStartArea(); + +/** + * @brief Returns true when any survivor is in the starting or ending checkpoint area + * + * @return True if a survivor is in the starting or ending checkpoint area. False otherwise + */ +native bool L4D_IsAnySurvivorInCheckpoint(); + +/** + * @brief Returns true when all survivors are in the finale area + * + * @return True when in all Survivors are in the area. False otherwise + */ +native bool L4D_AreAllSurvivorsInFinaleArea(); + +/** + * @brief Returns true when the specified Survivor or Special Infected is in the starting checkpoint area + * @remarks This might return true on certain maps, maybe in Survival/Scavenge start areas if they are close enough to the saferoom + * @remarks You could use the "L4D_IsPositionInFirstCheckpoint" native instead to accurately determine if someone is in the starting area + * @remarks This will always returns false when the "Unlock Finales" plugin by "Marttt" is installed: https://forums.alliedmods.net/showthread.php?t=333274 + * + * @param client Client id to check their checkpoint + * + * @return True if a survivor is in the starting checkpoint area. False otherwise + */ +native bool L4D_IsInFirstCheckpoint(int client); + +/** + * @brief Returns true when the specified Survivor or Special Infected is in the ending checkpoint area + * + * @param client Client id to check their checkpoint + * + * @return True if a survivor is in the ending checkpoint area. False otherwise + */ +native bool L4D_IsInLastCheckpoint(int client); + +/** + * @brief Returns true when a given vector is within the starting checkpoint area + * + * @param vecPos Vector position to check + * + * @return True if the position is within the starting checkpoint area. False otherwise + */ +native bool L4D_IsPositionInFirstCheckpoint(float vecPos[3]); + +/** + * @brief Returns true when a given vector is within the ending checkpoint area + * + * @param vecPos Vector position to check + * + * @return True if the position is within the ending checkpoint area. False otherwise + */ +native bool L4D_IsPositionInLastCheckpoint(float vecPos[3]); + +/** + * @brief Returns the entity index of the first saferoom door, if available + * @remarks This works by checking the saferoom door position against the maps flow distance selecting the door with 2000.0 (DOOR_RANGE_TOLLERANCE define) from map start + * @remarks Does not include doors with the DOOR_FLAG_IGNORE_USE flag. This flag is set by the "Safe Door Spam" plugin by Silvers for 0.1 seconds when someone attempts to open the saferoom door + * + * @return -1 if none exists or entity index of saferoom door + */ +native int L4D_GetCheckpointFirst(); + +/** + * @brief Returns the entity index of the last saferoom door, if available + * @remarks This works by checking the saferoom door position against the maps flow distance selecting the door with 2000.0 (DOOR_RANGE_TOLLERANCE define) from map end + * @remarks Does not include doors with the DOOR_FLAG_IGNORE_USE flag. This flag is set by the "Safe Door Spam" plugin by Silvers for 0.1 seconds when someone attempts to open the saferoom door + * + * @return -1 if none exists or entity index of saferoom door + */ +native int L4D_GetCheckpointLast(); + +/** + * @brief Checks if a world position is accessible to a Survivor bot + * @remarks You must pass a survivor bots client index into this, otherwise the plugin will attempt to find a bot or throw an error otherwise + * @remarks It appears the server will sometimes crash when passing a real players client index + * @remarks If the clients flow distance is too far away from the position to test it will return false + * + * @param client Client id to use for testing + * @param vecPos Vector coordinate to test + * + * @return True if accessible, false otherwise + */ +// L4D2 only +native bool L4D2_IsReachable(int client, const float vecPos[3]); + +/** + * @brief Returns the nav distance between two areas. Does not account for out-of-bounds areas + * + * @param startArea NavArea address + * @param endArea NavArea address + * @param ignoreNavBlockers Bool to ignore blocked areas while checking (does not seem to work as expected) (ignored in L4D1) + * + * @return Distance between the areas, 0.0 if the same area or -1.0 on failure + */ +native float L4D2_NavAreaTravelDistance(float startPos[3], float endPos[3], bool ignoreNavBlockers); + +/** + * @brief Test two vector positions if they can be reached (only returns false if a location has no valid NavArea, out-of-bounds can be valid) + * @remarks Uses the "ShortestPathCost" system + * + * @param nav_startPos The NavArea address start position (can use L4D_GetNearestNavArea) + * @param nav_endPos The NavArea address end position from (can use L4D_GetNearestNavArea) + * @param flMaxPathLength Maximum distance allowed between the two points + * @param teamID Which team to validate the path for + * @param ignoreNavBlockers Should nav blockers be ignored or not + * + * @return Returns true if a path exists, false if not or on script error + */ +// L4D2 only +native bool L4D2_NavAreaBuildPath(Address nav_startPos, Address nav_endPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers); + +// Used by "L4D2_CommandABot" native: +enum BOT_CMD +{ + BOT_CMD_ATTACK = 0, // Force the bot to attack a specific target, even bypassing CTerrorPlayer::SetSenseFlags (DirectorScript.BOT_CANT_SEE) + BOT_CMD_MOVE = 1, // Force the bot to move to a specific location, which then they will do it unconditionally without performing any other AI behaviours controlled by themselves + // This means that Survivor Bots and most player-controllable Special Infected won't attack anything when commanded, but Common Infected still automatically attack enemies if they close in enough + BOT_CMD_RETREAT = 2, // Force the bot to retreat from a target entity. Only works when used on Survivor Bots, and if target is a Tank + BOT_CMD_RESET = 3 // Removes the active bot command and lets the AI resume controlling the bot +}; + +/** + * @brief Uses the VScript "CommandABot" function to command a bot to attack, move, retreat or reset previous command + * + * @param entity The bot or infected to command + * @param target The Special Infected to target (used for types "BOT_CMD_ATTACK" and "BOT_CMD_RETREAT") + * @param type Type of command (see the "BOT_CMD" enum) + * @param vecPos Move to this location (Used for type "BOT_CMD_MOVE") + * + * @return Returns false when unable to perform, true otherwise + */ +// L4D2 only +native bool L4D2_CommandABot(int entity, int target, BOT_CMD type, float vecPos[3] = NULL_VECTOR); + +/** + * @brief Returns if players can control infected + * + * @return True if players can control infected, false otherwise + */ +native bool L4D_HasPlayerControlledZombies(); + +/** + * @brief Detonates an active grenade projectile + * @remarks Can detonate in L4D1 & L4D2: "molotov_projectile", "pipebomb_projectile", "tank_rock" + * @remarks Can detonate in L4D2: "vomitjar_projectile", "grenadelauncher_projectile", "spitter_projectile" + * + * @param entity The projectile entity to detonate + * + * @noreturn + */ +native void L4D_DetonateProjectile(int entity); + +/** + * @brief Detonates an active grenade projectile + * @remarks Can detonate in L4D1 & L4D2: "molotov_projectile", "pipebomb_projectile", "tank_rock" + * @remarks Can detonate in L4D2: "vomitjar_projectile", "grenadelauncher_projectile", "spitter_projectile" + * + * @param entity The projectile entity to detonate + * + * @noreturn + */ +// NOT IMPLEMENTED +// native int L4D_StartBurning(int entity, float vecPos[3], float vecNorm[3], float vecVel[3]); + +/** + * @brief Creates an activated Tank Rock projectile + * @remarks It seems when using a Survivor for the client index and hitting another Survivor, the victim will take 1.0 damage (maybe due to friendly fire settings) + * @remarks Suggest using an OnTakeDamage hook if you want to apply more damage + * + * @param client Client id to attribute the projectile to for damage credit. Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector direction of the projectile + * + * @return Entity index of the projectile + */ +native int L4D_TankRockPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Creates an activated PipeBomb projectile + * @remarks Does not attach the "Fuse" or "Light" particles, see the "left4dhooks_test" plugin for example on attaching these + * @remarks Also used in the "PipeBomb Shove" plugin by Silvers + * + * @param client Client id to attribute the projectile to for damage credit. Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector velocity and direction of the projectile + * + * @return Entity index of the projectile + */ +native int L4D_PipeBombPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Creates an activated Molotov projectile + * + * @param client Client id to attribute the projectile to for damage credit Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector velocity and direction of the projectile + * + * @return Entity index of the projectile + */ +native int L4D_MolotovPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Creates an activated VomitJar projectile + * + * @param client Client id to attribute the projectile to for damage credit Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector velocity and direction of the projectile + * + * @return Entity index of the projectile + */ +// L4D2 Only +native int L4D2_VomitJarPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Creates an activated Grenade Launcher projectile + * + * @param client Client id to attribute the projectile to for damage credit Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector velocity and direction of the projectile + * + * @return Entity index of the projectile + */ +// L4D2 Only +native int L4D2_GrenadeLauncherPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Creates a Spitter goo projectile + * + * @param client Client id to attribute the projectile to for damage credit Passing 0 (world) is allowed + * @param vecPos Vector coordinate of the projectile on creation + * @param vecAng Vector velocity and direction of the projectile + * + * @return Entity index of the projectile + */ +// L4D2 only +native int L4D2_SpitterPrj(int client, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Gives the player adrenaline effect and health benefits + * + * @param client Client id to affect + * @param fTime Duration of screen effects (game default: 15.0 - Cvar: "adrenaline_duration") + * @param heal True = give health benefits and fire "adrenaline_used" event. False = only screen effects + * + * @return True on success, false otherwise + */ +// L4D2 only +native void L4D2_UseAdrenaline(int client, float fTime = 15.0, bool heal = true); + +/** + * @brief Respawns a player from dead state + * @remarks Resets players stats for kills etc + * @remarks To preserve stats please view the code in "[L4D1 & L4D2] SM Respawn Improved" plugin by "Dragokas": https://forums.alliedmods.net/showthread.php?t=323220 + * + * @param client Client ID of the person to respawn + * + * @noreturn + */ +native void L4D_RespawnPlayer(int client); + +/** + * @brief To takeover a Survivor bot. First use "ChangeClientTeam" and change them to 0. Then call "L4D_SetHumanSpec" then call "L4D_TakeOverBot" + * + * @param bot Bot ID of the person to set spectator + * @param client Client ID of the spectator + * + * @return True or false + */ +native bool L4D_SetHumanSpec(int bot, int client); + +/** + * @brief To takeover a Survivor bot. First use "ChangeClientTeam" and change them to 0. Then call "L4D_SetHumanSpec" then call "L4D_TakeOverBot" + * + * @param client Client ID of who should takeover + * + * @return True or false + */ +native bool L4D_TakeOverBot(int client); + +/** + * @brief Returns true when the "You will enter Spawn Mode in X seconds" text appears on the screen + * + * @param client Client ID to check + * + * @return True or false + */ +native bool L4D_CanBecomeGhost(int client); + +/** + * @brief Set a dead Special Infected players time until they transition into ghost state. Can be used when the "ghost_spawn_time" event triggers + * + * @param client Client ID to check + * + * @return True or false + */ +native void L4D_SetBecomeGhostAt(int client, float time); + +/** + * @brief Sets a client as idle, afk - away from keyboard + * + * @param client Client ID to check + * + * @return True or false + */ +native bool L4D_GoAwayFromKeyboard(int client); + +/** + * @brief Returns if Wandering Witches are allowed + * + * @return True or false + */ +// L4D2 only +native bool L4D2_AreWanderersAllowed(); + +/** + * @brief Returns true when the rescue vehicle is leaving until the screen fades and credits start + * + * @return True or false + */ +native bool L4D_IsFinaleEscapeInProgress(); + +/** + * @brief Returns the current Finale stage type + * @remarks some values for FinaleStageType: 1 - Finale Started; 6 - Rescue Vehicle Ready; 7 - Zombie Hordes; 8 - Tank; 10 - Combat Respite (nothing spawns) + * @remarks Seems to return 18 for non-finale maps + * @remarks Can use the "FINALE_*" enums (search for them above) for the finaleType value + * + * @return finaleType stage value + */ +// L4D2 only +native any L4D2_GetCurrentFinaleStage(); + +/** + * @brief Forces the ScriptedMode stage to advance to the next stage + * + * @noreturn + */ +// L4D2 only +native void L4D2_ForceNextStage(); + +/** + * @brief Forces the game to start in Versus + * + * @noreturn + */ +native void L4D_ForceVersusStart(); + +/** + * @brief Forces the game to start in Survival + * + * @noreturn + */ +native void L4D_ForceSurvivalStart(); + +/** + * @brief Forces the game to start in Scavenge + * + * @noreturn + */ +// L4D2 only +native void L4D2_ForceScavengeStart(); + +/** + * @brief Returns true when any tanks are on the map + * + * @return True when any tanks are on the map. False when no tanks + */ +// L4D2 only +native bool L4D2_IsTankInPlay(); + +/** + * @brief Returns the directors script scope handle + * @remarks Scope level + * 0 = DirectorScript + * 1 = MapScript + * 2 = LocalScript + * 3 = ChallengeScript + * 4 = DirectorOptionsScope + * + * @Param level The scope level + * + * @return Value of directors script scope + */ +// L4D2 only +native int L4D2_GetDirectorScriptScope(int level); + +/** + * @brief Returns the value of the specified Director Variable key + * @remarks You should provide a valid default value to use as the native is likely to return that unless the key value has been modified by a mutation or director script + * @remarks See the "left4dhooks_test.sp" plugin and search for "L4D2_GetScriptValueInt" to see a list of keys and their default values and related cvars + * + * @param key Director variable key name to search for + * @param value Default value to use when the variable is not found + * + * @return Value of the variable, or provided default value on failure + */ +// L4D2 only +native int L4D2_GetScriptValueInt(const char[] key, int value); + +/** + * @brief Returns the value of the specified Director Variable key + * @remarks You should provide a valid default value to use as the native is likely to return that unless the key value has been modified by a mutation or director script + * @remarks See the "left4dhooks_test.sp" plugin and search for "L4D2_GetScriptValueFloat" to see a list of keys and their default values and related cvars + * + * @param key Director variable key name to search for + * @param value Default value to use when the variable is not found + * + * @return Value of the variable, or provided default value on failure + */ +// L4D2 only +native float L4D2_GetScriptValueFloat(const char[] key, float value); + +// Crashes when the key has not been set +// native void L4D2_GetScriptValueString(const char[] key, const char[] value, char[] retValue, int maxlength); + +/** + * @brief Returns if there is a configurable difficulty setting + * @brief Returns true for Coop/Realism modes + * + * @return True if there is a configurable difficulty setting, false otherwise + **/ +// L4D2 only +native bool L4D2_HasConfigurableDifficultySetting(); + +/** + * @brief Returns the maps default Survivor set + * @brief Does not return the overridden value when changed from the "L4D_OnGetSurvivorSet" or "L4D_OnFastGetSurvivorSet" forwards + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + * @return Maps default survivor set + **/ +// L4D2 only +native int L4D2_GetSurvivorSetMap(); + +/** + * @brief Returns the current Survivor set + * @brief Return the current set which may have been overridden if changed in the "L4D_OnGetSurvivorSet" or "L4D_OnFastGetSurvivorSet" forwards + * + * @return Maps default survivor set + **/ +// L4D2 only +native int L4D2_GetSurvivorSetMod(); + +/** + * @brief Returns if the current game mode is Coop/Realism mode + * + * @return True if the current game mode is Coop/Realism mode, false otherwise + **/ +// L4D2 only +native bool L4D2_IsGenericCooperativeMode(); + +/** + * @brief Returns if the current game mode is Coop mode + * + * @return True if the current game mode is Coop mode, false otherwise + **/ +native bool L4D_IsCoopMode(); + +/** + * @brief Returns if the current game mode is Realism mode + * + * @return True if the current game mode is Realism mode, false otherwise + **/ +// L4D2 only +native bool L4D2_IsRealismMode(); + +/** + * @brief Returns if the current game mode is Survival mode + * + * @return True if the current game mode is Survival mode, false otherwise + **/ +native bool L4D_IsSurvivalMode(); + +/** + * @brief Returns if the current game mode is Scavenge mode + * + * @return True if the current game mode is Scavenge mode, false otherwise + **/ +// L4D2 only +native bool L4D2_IsScavengeMode(); + +/** + * @brief Returns if the current game mode is Versus mode + * + * @return True if the current game mode is Versus mode, false otherwise + **/ +native bool L4D_IsVersusMode(); + + + + + +// ==================================================================================================== +// NATIVES - Silvers - VSCRIPT WRAPPERS +// ==================================================================================================== +// These natives are using VScripts to call functions - this is much slower than native SDKCalls +// Popular VScript functions will be converted to standard native SDKCalls. Please tell me +// Recommend not using these too often, instead request proper native SDKCalls + +/** + * @brief Returns the number of maps played since a new campaign (not the current chapter) + * + * @return Number of maps played + */ +// L4D2 only +native int L4D2_VScriptWrapper_GetMapNumber(); + +/** + * @brief Returns true if the character has ever been injured by a member of the given team + * @remarks Team 3 returns true when hurt by Common Infected + * + * @param client Client to test + * @param team Team to test + * + * @return Number of maps played + */ +// L4D2 only +native bool L4D2_VScriptWrapper_HasEverBeenInjured(int client, int team); + +/** + * @brief Returns the time the character has been alive (only valid when alive) + * + * @return Client to test + */ +// L4D2 only +native float L4D2_VScriptWrapper_GetAliveDuration(int client); + +/** + * @brief Returns true when a player is dead and can spectate others + * + * @param client Client to test + * + * @return True if dead, false if not or script error + */ +// L4D2 only +native bool L4D2_VScriptWrapper_IsDead(int client); + +/** + * @brief Returns true when a player is dead, but cannot spectate others yet + * + * @param client Client to test + * + * @return True if dying, false if not or script error + */ +// L4D2 only +native bool L4D2_VScriptWrapper_IsDying(int client); + +/** + * @brief Causes Adrenaline's speed and visual effect, no change to health + * + * @param client Client to affect + * + * @return True on success (does not guarantee effect turned on), false on script error + */ +// L4D2 only +#pragma deprecated Use L4D2_UseAdrenaline native instead (kept here for speed comparison) +native bool L4D2_VScriptWrapper_UseAdrenaline(int client, float time); + +/** + * @brief Revive a dead player by defib + * + * @param client Client to revive + * + * @return True on success (does not guarantee they were revived), false on script error + */ +// L4D2 only +native bool L4D2_VScriptWrapper_ReviveByDefib(int client); + +/** + * @brief Revive an incapacitated player + * + * @param client Client to revive + * + * @return True on success (does not guarantee they were revived), false on script error + */ +// L4D2 only +native bool L4D2_VScriptWrapper_ReviveFromIncap(int client); + +/** + * @brief Get the current bits for the bot sense flags: BOT_CANT_SEE, BOT_CANT_HEAR, BOT_CANT_FEEL + * + * @param bot Bot to check + * + * @return Current sense flags + */ +// L4D2 only +native any L4D2_VScriptWrapper_GetSenseFlags(int bot); + +/** + * @brief Test two vector positions if they can be reached (only returns false if a location has no valid NavArea, out-of-bounds can be valid) + * + * @return Returns true if a path exists, false if not or on script error + */ +// L4D2 only +#pragma deprecated Use L4D2_NavAreaBuildPath native instead (kept here for speed comparison) +native bool L4D2_VScriptWrapper_NavAreaBuildPath(const float startPos[3], const float endPos[3], float flMaxPathLength, bool checkLOS, bool checkGround, int teamID, bool ignoreNavBlockers); + +/** + * @brief Compute distance between two areas + * + * @return -1 if can't reach 'endArea' from 'startArea' + */ +// L4D2 only +// Added as a demonstration and test, SDKCall is available, use "L4D2_NavAreaTravelDistance" instead +native float L4D2_VScriptWrapper_NavAreaTravelDistance(const float startPos[3], const float endPos[3], float flMaxPathLength, bool checkLOS, bool checkGround); + + + + + +// ==================================================================================================== +// NATIVES - left4downtown.inc (and new ones by Silvers) +// ==================================================================================================== +/** + * @brief Restarts the setup timer (when in scavenge mode) + * @remarks If game has already started, the setup timer will show, + * but it still won't go back into setup + */ +// L4D2 only +native int L4D_ScavengeBeginRoundSetupTime(); + +/** + * @brief Resets the natural mob (horde) timer + * @remarks Requires the Director to be available--map must be started + * + * @noreturn + */ +// L4D2 only +native void L4D_ResetMobTimer(); + +/** + * @brief Get the remaining spawn time for a SI + * @remarks This is meant for Special infected in ghost mode in versus + * + * @param player Player ID to get time + * + * @return Time (seconds) until the SI will spawn + */ +// L4D2 only +native float L4D_GetPlayerSpawnTime(int player); + +/** + * @brief Set the remaining spawn time for a SI + * @remarks This is meant for Special infected in ghost mode in versus + * + * @param player Player ID to set time + * @param time Number of seconds until the SI will spawn + * @param bReportToPlayer If the change should be sent to clients, updating timer in HUD + * + * @noreturn + */ +// L4D2 only +native void L4D_SetPlayerSpawnTime(int player, float time, bool bReportToPlayer = true); + +/** + * @brief Restarts the round, switching the map if necessary + * @remarks Set the map to the current map to restart the round + * + * @param map the mapname it should go to after the round restarts + * + * @return 1 always + */ +native int L4D_RestartScenarioFromVote(const char[] map); + +/** + * @brief Gets the max versus completion score for the map + * @remarks Requires GameRules to be initialized--map must be loaded + * Seems to be updated before OnMapStart + * + * @return The map's max completion distance (map distance score) + */ +native int L4D_GetVersusMaxCompletionScore(); + +/** + * @brief Sets the max versus completion score for the map + * @remarks Requires GameRules to be initialized--map must be loaded + * Seems to be updated before OnMapStart and checked on round_start + * + * @param score The versus max completion score to set for the round + */ +native int L4D_SetVersusMaxCompletionScore(int score); + +/** + * @brief Get the team scores for the current map + * @remarks The campaign scores are not set until the end of round 2, + * use L4D_GetCampaignScores to get them earlier + * + * @deprecated This function can be called through SDKTools using CTerrorGameRules, + * and so you should switch off to using SDKTools instead of this native + * + * @param logical_team L4D1: 1 for A, 2 for B. L4D1: 1-6 (Maybe something like: 1: Your team 1. 2: Enemy team. 3: Survivor completion percentage. 4: Health bonus. 5: Completion percentage. 6: Total score at round end.) + * @param campaign_score true to get campaign score instead of map score + * + * @return the logical team's map score + * or -1 if the team hasn't played the round yet, + * or the team's campaign score if campaign_score = true + */ +native int L4D_GetTeamScore(int logical_team, bool campaign_score=false); + +/** + * @brief Tells if the Mission (map) is the first map of the campaign + * + * @return true if the map is the first map of the campaign + */ +native bool L4D_IsFirstMapInScenario(); + +/** + * @brief Tells if the Mission (map) is the final map of the campaign + * + * @return true if the map is the last map of the campaign (finale) + */ +native bool L4D_IsMissionFinalMap(); + +/** + * @brief Notifies the CGameRulesProxy that the game state has been changed + * @remarks Use this function before changing networked members of GameRules, + * like with L4D_SetVersusMaxCompletionScore() + * + * @noreturn + */ +native void L4D_NotifyNetworkStateChanged(); + +/** + * @brief Trigger's a target player's stagger behaviour + * @remarks Works on any CTerrorPlayer--survivor or infected + * + * @param target Player to stagger + * @param source_ent Source of the stagger (another player, etc) + * @param vecSource Source location of the stagger. If NULL_VECTOR, origins of source_ent is used + * + * @noreturn + */ +native void L4D_StaggerPlayer(int target, int source_ent, const float vecSource[3]); + +/** + * @brief Calls CDirectorScriptedEventManager::SendInRescueVehicle(void) + * @remarks Calls in the rescue vehicle + * @remarks will fire the forward of the same function + * + * @noreturn + */ +native void L4D2_SendInRescueVehicle(); + +/** + * @brief Calls CDirectorScriptedEventManager::ChangeFinaleStage(CDirectorScriptedEventManager FinaleStageType,char const*) + * @remarks Changes the Finale stage + * @remarks some values for FinaleStageType: 1 - Finale Started; 6 - Rescue Vehicle Ready; 7 - Zombie Hordes; 8 - Tank; 10 - Combat Respite (nothing spawns) + * @remarks will fire the forward of the same function + * @remarks Can use the "FINALE_*" enums (search for them above) for the finaleType value + * + * @param FinaleStageType integer value + * + * @noreturn + */ +// L4D2 only +native void L4D2_ChangeFinaleStage(any finaleType, const char[] arg); + +/** + * @brief Calls ZombieManager::ReplaceTank(CTerrorPlayer *,CTerrorPlayer *) + * @remarks Replaces a players tank control with another player + * + * @param tank the player who was a tank + * @param newtank a player who will become a new tank + */ +native void L4D_ReplaceTank(int tank, int newtank); + +/** + * @brief Calls ZombieManager::SpawnTank(Vector&,QAngle&) + * + * @param vecPos Vector coordinate where the tank will be spawned + * @param vecAng QAngle where the tank will be facing + * + * @return Entity index of the spawned tank + */ +native int L4D2_SpawnTank(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Calls ZombieManager::SpawnSpecial(ZombieClassType,Vector&,QAngle&) + * @remarks Only used for bot special spawns (not players) + * + * @param vecPos Vector coordinate where the SI will be spawned + * @param vecAng QAngle where the SI will be facing + * + * @return Entity index of the spawned SI + */ +native int L4D2_SpawnSpecial(int zombieClass, const float vecPos[3], const float vecAng[3]); + +/** + * @brief Calls ZombieManager::SpawnWitch(Vector&,QAngle&) + * + * @param vecPos Vector coordinate where the witch will be spawned + * @param vecAng QAngle where the witch will be facing + * + * @return Entity index of the spawned witch + */ +native int L4D2_SpawnWitch(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Calls ZombieManager::SpawnWitchBride(Vector&,QAngle&) + * + * @param vecPos Vector coordinate where the witch bride will be spawned + * @param vecAng QAngle where the witch bride will be facing + * + * @return Entity index of the spawned witch bride + */ +// L4D2 only +native int L4D2_SpawnWitchBride(const float vecPos[3], const float vecAng[3]); + +/** + * @brief Removes lobby reservation from a server + * @remarks Sets the reservation cookie to 0, it is safe to call this even if it's unreserved + * + * @noreturn + */ +native void L4D_LobbyUnreserve(); + +/** + * @brief Checks if the server is currently reserved for a lobby + * @remarks Server is automatically unreserved if it hibernates or if all players leave + * + * @return true if reserved, false if not reserved + */ +native bool L4D_LobbyIsReserved(); + +/** + * @brief Returns the lobby reservation ID + * + * @param reservation String to store the reservation ID to + * @param maxlength Maximum length of the string to store to + * + * @noreturn + */ +native void L4D_GetLobbyReservation(char [] reservation, int maxlength); + +/** + * @brief Sets the lobby reservation ID + * + * @param reservation The reservation ID to set + * + * @noreturn + */ +native void L4D_SetLobbyReservation(char reservation[20]); + +/** + * @brief Get the current campaign scores stored in the Director + * @remarks The campaign scores are updated after L4D_OnSetCampaignScores + * + * @deprecated This will set the scores to -1 for both sides on L4D2, + * this function is no longer supported + * + * @param scoreA score of logical team A + * @param scoreB score of logical team B + * + * @return 1 always + */ +#pragma deprecated Use GetTeamScore and OnClearTeamScores instead +native int L4D_GetCampaignScores(int &scoreA, int &scoreB); + +/** + * @brief Get the time remaining before the next director horde + * @remarks This timer is used for scripted event hordes and natural timed hordes + * + * @return Time remaining before next director horde + */ +#pragma deprecated Use L4D2_CTimerGetRemainingTime(L4D2CT_MobSpawnTimer) +native float L4D_GetMobSpawnTimerRemaining(); + +/** + * @brief Get the duration the horde timer was set to after the last horde + * @remarks This timer is used for scripted event hordes and natural timed hordes + * + * @return Total time from last horde to next horde + */ +#pragma deprecated Use L4D2_CTimerGetCountdownDuration(L4D2CT_MobSpawnTimer) +native float L4D_GetMobSpawnTimerDuration(); + + + + + +// ==================================================================================================== +// NATIVES - l4d2director.inc (and new ones by Silvers) +// ==================================================================================================== +/** + * @brief Gets the number of tanks currently in play + * @remarks This value is tracked by the director, and should be a good + * indicator that a tank is in play + * + * @return Current Tank count + */ +native int L4D2_GetTankCount(); + +/** + * @brief Gets the number of witches currently in play + * @remarks This value is tracked by the director, and should be a good + * indicator that a witch is in play + * + * @return Current Witch count + */ +native int L4D2_GetWitchCount(); + +/** + * @brief Returns the current map chapter number of the campaign + * + * @return Map chapter + */ +native int L4D_GetCurrentChapter(); + +/** + * @brief Returns the maximum number of chapters for the current game mode + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + * @return Max chapters + */ +native int L4D_GetMaxChapters(); + +/** + * @brief Returns all TheNavAreas addresses + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param aList The ArrayList to store all nav area addresses + * + * @noreturn + */ +native void L4D_GetAllNavAreas(ArrayList aList); + +/** + * @brief Returns a given NavArea's ID from it's address + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param area The NavArea address + * + * @return NavArea ID + */ +native int L4D_GetNavAreaID(Address area); + +/** + * @brief Returns a given NavArea address from it's ID + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param id The NavArea ID + * + * @return NavArea address or Address_Null if invalid ID + */ +native Address L4D_GetNavAreaByID(int id); + +/** + * @brief Returns origin of a given NavArea + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param area The address of the NavArea to read + *param vecPos The vector to store the position read + * + * @noreturn + */ +native void L4D_GetNavAreaPos(Address area, float vecPos[3]); + +/** + * @brief Returns center of a given NavArea + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param area The address of the NavArea to read + *param vecPos The vector to store the center position + * + * @noreturn + */ +native void L4D_GetNavAreaCenter(Address area, float vecPos[3]); + +/** + * @brief Returns size of a given NavArea + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param area The address of the NavArea to read + *param vecPos The vector to store the size read + * + * @noreturn + */ +native void L4D_GetNavAreaSize(Address area, float vecSize[3]); + +/** + * @brief Returns true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection) + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param area1 The address of the first NavArea + *param are2a The address of the second NavArea + *param direction The direction to check in (NAV_NORTH, NAV_EAST, NAV_SOUTH, NAV_WEST, NAV_ALL) - provide value 1 to 4 only + * + * @noreturn + */ +native bool L4D_NavArea_IsConnected(Address area1, Address area2, int direction); + +/** + * @brief Returns the nav area attribute flags + * @remarks See the "NAV_BASE_*" near the top of the include file + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param pTerrorNavArea Pointer to a NavArea + * + * @return Attribute flags + */ +native int L4D_GetNavArea_AttributeFlags(Address pTerrorNavArea); + +/** + * @brief Sets the nav area attribute flags + * @remarks See the "NAV_BASE_*" near the top of the include file + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param pTerrorNavArea Pointer to a NavArea + *param flags Attribute flags to set + * + * @return Attribute flags + */ +native void L4D_SetNavArea_AttributeFlags(Address pTerrorNavArea, int flags); + +/** + * @brief Returns the terror nav area attribute flags + * @remarks See the "NAV_SPAWN_*" near the top of the include file + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param pTerrorNavArea Pointer to a TerrorNavArea + * + * @return Attribute flags + */ +native int L4D_GetNavArea_SpawnAttributes(Address pTerrorNavArea); + +/** + * @brief Sets the terror nav area attribute flags + * @remarks See the "NAV_SPAWN_*" near the top of the include file + * @remarks Can only be called 1 frame after OnMapStart at the earliest otherwise the addresses are invalid + * + *param pTerrorNavArea Pointer to a TerrorNavArea + *param flags Attribute flags to set + * + * @noreturn + */ +native void L4D_SetNavArea_SpawnAttributes(Address pTerrorNavArea, int flags); + +/** + * @brief Gets the campaign scores stored in the Versus Director + * @remarks These are the actual values used for campaign scores--not proxies + * + * @param scores Array to store the campaign scores in + * @noreturn + */ +// L4D2 only +native void L4D2_GetVersusCampaignScores(int scores[2]); + +/** + * @brief Sets the campaign scores stored in the Versus Director + * @remarks These are the actual values used for campaign scores--not proxies + * + * @param scores Array of campaign scores to set the director's values to + * @noreturn + */ +// L4D2 only +native void L4D2_SetVersusCampaignScores(const int scores[2]); + +/** + * @brief Gets the flow percent for tank spawns for both versus rounds + * @remarks These values are checked against as the survivors move through the + * map. Once they are passed, the tank spawns. Note that this is flow + * as a percent of the map's flow, not flow distance + * + * @param tankFlows Array to store the Tank Spawn Flow percents in director + * @noreturn + */ +// L4D2 only +native void L4D2_GetVersusTankFlowPercent(float tankFlows[2]); + +/** + * @brief Sets the flow percent for tank spawns for both versus rounds + * @remarks These values are checked against as the survivors move through the + * map. Once they are passed, the tank spawns. Note that this is flow + * as a percent of the map's flow, not flow distance + * + * @param tankFlows Array of Tank Spawn Flow percents to store in director + * @noreturn + */ +// L4D2 only +native void L4D2_SetVersusTankFlowPercent(const float tankFlows[2]); + +/** + * @brief Gets the flow percent for witch spawns for both versus rounds + * @remarks These values are checked against as the survivors move through the + * map. Once they are passed, the witch spawns. Note that this is flow + * as a percent of the map's flow, not flow distance + * + * @param witchFlows Array to store the Witch Spawn Flow percents in director + * @noreturn + */ +// L4D2 only +native void L4D2_GetVersusWitchFlowPercent(float witchFlows[2]); + +/** + * @brief Sets the flow percent for witch spawns for both versus rounds + * @remarks These values are checked against as the survivors move through the + * map. Once they are passed, the witch spawns. Note that this is flow + * as a percent of the map's flow, not flow distance + * + * @param witchFlows Array of Witch Spawn Flow percents to store in director + * @noreturn + */ +// L4D2 only +native void L4D2_SetVersusWitchFlowPercent(const float witchFlows[2]); + + + + + +// ==================================================================================================== +// NATIVES - l4d2timers.inc +// ==================================================================================================== +enum L4D2CountdownTimer +{ + L4D2CT_MobSpawnTimer, + L4D2CT_SmokerSpawnTimer, + L4D2CT_BoomerSpawnTimer, + L4D2CT_HunterSpawnTimer, + L4D2CT_SpitterSpawnTimer, + L4D2CT_JockeySpawnTimer, + L4D2CT_ChargerSpawnTimer, + L4D2CT_VersusStartTimer, + L4D2CT_UpdateMarkersTimer +}; + +enum L4D2IntervalTimer +{ + L4D2IT_SmokerDeathTimer, + L4D2IT_BoomerDeathTimer, + L4D2IT_HunterDeathTimer, + L4D2IT_SpitterDeathTimer, + L4D2IT_JockeyDeathTimer, + L4D2IT_ChargerDeathTimer +}; + + + +/************************************* + CountdownTimer Natives +***********************************/ +/** + * @brief Resets a given CountdownTimer (start again with same duration) + * @remarks Equivalent to Start(timer, GetCountdownDuration(timer)) + * + * @param timer CountdownTimer to reset + * @noreturn + */ +// L4D2 only +native void L4D2_CTimerReset(L4D2CountdownTimer timer); + +/** + * @brief Starts a given CountdownTimer with a given duration + * @remarks This sets a new duration and sets up the end timestamp + * + * @param timer CountdownTimer to start + * @param duration Duration for the timer to use + * @noreturn + */ +// L4D2 only +native void L4D2_CTimerStart(L4D2CountdownTimer timer, float duration); + +/** + * @brief Invalidates a given CountdownTimer (Timer essentially does not run) + * @remarks Sets the timestamp to -1.0f + * + * @param timer CountdownTimer to Invalidate + * @noreturn + */ +// L4D2 only +native void L4D2_CTimerInvalidate(L4D2CountdownTimer timer); + +/** + * @brief Tells if a given CountdownTimer has started + * @remarks Checks to see if the end timestamp is greater than 0.0f + * + * @param timer CountdownTimer to check + * + * @return true if timer has started, false if timer is not started/invalid + */ +// L4D2 only +native bool L4D2_CTimerHasStarted(L4D2CountdownTimer timer); + +/** + * @brief Tells if a given CountdownTimer is elapsed + * @remarks If a timer is "up," e.g duration has passed since start, this returns true; + * + * @param timer CountdownTimer to check + * + * @return true if timer has elapsed or timer invalid/not started, false otherwise + */ +// L4D2 only +native bool L4D2_CTimerIsElapsed(L4D2CountdownTimer timer); + +/** + * @brief Gets elapsed time of a given CountdownTimer, from the timed it was started + * @remarks Value is (Now() - timestamp) + duration + * + * @param timer CountdownTimer to get elapsed time of + * + * @return float amount of time since timer started + */ +// L4D2 only +native float L4D2_CTimerGetElapsedTime(L4D2CountdownTimer timer); + +/** + * @brief Gets remaining time on a given CountdownTimer + * @remarks Value is (timestamp - Now()) + * + * @param timer CountdownTimer to get remaining time of + * + * @return float amount of time remaining on the timer + */ +// L4D2 only +native float L4D2_CTimerGetRemainingTime(L4D2CountdownTimer timer); + +/** + * @brief Gets the duration of a given CountdownTimer + * @remarks Value is (timestamp > 0.0f ? duration 0.0f) + * + * @param timer CountdownTimer to get duration of + * + * @return 0.0 for invalid/not started timers, timer duration otherwise + */ +// L4D2 only +native float L4D2_CTimerGetCountdownDuration(L4D2CountdownTimer timer); + + + +/************************************* + IntervalTimer Natives +***********************************/ + +/** + * @brief Starts a given IntervalTimer + * @remarks Just sets timestamp = Now(), so counting starts from now + * + * @param timer IntervalTimer to start + * + * @noreturn + */ +// L4D2 only +native void L4D2_ITimerStart(L4D2IntervalTimer timer); + +/** + * @brief Invalidates a given IntervalTimer + * @remarks Just sets timestamp = -1.0f + * + * @param timer IntervalTimer to Invalidate + * @noreturn + */ +// L4D2 only +native void L4D2_ITimerInvalidate(L4D2IntervalTimer timer); + +/** + * @brief Tells whether a given IntervalTimer has started + * @remarks Checks to see if timestamp > 0.0f + * + * @param timer IntervalTimer to check + * + * @return true if timer is started, false if it is invalid/not started + */ +// L4D2 only +native bool L4D2_ITimerHasStarted(L4D2IntervalTimer timer); + +/** + * @brief Gets the elapsed time of a given IntervalTimer + * @remarks Value is Now() - Timestamp + * + * @param timer IntervalTimer to get elapsed time of + * + * @return Elapsed time if timer started and valid, 99999.9f otherwise + */ +// L4D2 only +native float L4D2_ITimerGetElapsedTime(L4D2IntervalTimer timer); + + + + + +// ==================================================================================================== +// NATIVES - l4d2weapons.inc +// ==================================================================================================== +/* + * 2020 Update1: Use the "Info Editor" plugin by Silvers to edit the weapon scripts and increase clip size + * 2020 Update2: Now works in Left4DHooks. Glitchy animation bug when reloading an already full weapon + * 2021 Update3: Fix plugin for modified ammo clips found here: https://forums.alliedmods.net/showthread.php?t=327105 + + A note regarding Clipsize: Any non-standard value will NOT be in effect at weapon pickup, which means the client + has to reload once to achieve the modified value. To fix this, add a weapon pickup hook in your plugin (eg "player_use") + and use something like this with a small timer delay of 0.1 seconds or more (dont you love this engine) + + int weapon = GetPlayerWeaponSlot(client, 0); + if( weapon == INVALID_ENT_REFERENCE ) return; + char class[56]; + GetEdictClassname(weapon, class, sizeof(class)); + SetEntProp(weapon, Prop_Send, "m_iClip1", L4D2_GetIntWeaponAttribute(class, L4D2IWA_ClipSize)); +*/ +enum L4D2IntWeaponAttributes +{ + L4D2IWA_Damage, + L4D2IWA_Bullets, + L4D2IWA_ClipSize, + L4D2IWA_Bucket, + L4D2IWA_Tier, // L4D2 only + L4D2IWA_DefaultSize, // Default weapon clip size + MAX_SIZE_L4D2IntWeaponAttributes +}; + +enum L4D2FloatWeaponAttributes +{ + L4D2FWA_MaxPlayerSpeed, + L4D2FWA_SpreadPerShot, + L4D2FWA_MaxSpread, + L4D2FWA_SpreadDecay, + L4D2FWA_MinDuckingSpread, + L4D2FWA_MinStandingSpread, + L4D2FWA_MinInAirSpread, + L4D2FWA_MaxMovementSpread, + L4D2FWA_PenetrationNumLayers, + L4D2FWA_PenetrationPower, + L4D2FWA_PenetrationMaxDist, + L4D2FWA_CharPenetrationMaxDist, + L4D2FWA_Range, + L4D2FWA_RangeModifier, + L4D2FWA_CycleTime, + L4D2FWA_PelletScatterPitch, + L4D2FWA_PelletScatterYaw, + L4D2FWA_VerticalPunch, + L4D2FWA_HorizontalPunch, // Requires "z_gun_horiz_punch" cvar changed to "1" + L4D2FWA_GainRange, + L4D2FWA_ReloadDuration, + MAX_SIZE_L4D2FloatWeaponAttributes +}; + +// L4D2 only +enum L4D2BoolMeleeWeaponAttributes +{ + L4D2BMWA_Decapitates, + MAX_SIZE_L4D2BoolMeleeWeaponAttributes +}; + +// L4D2 only +enum L4D2IntMeleeWeaponAttributes +{ + L4D2IMWA_DamageFlags, + L4D2IMWA_RumbleEffect, + MAX_SIZE_L4D2IntMeleeWeaponAttributes +}; + +// L4D2 only +enum L4D2FloatMeleeWeaponAttributes +{ + L4D2FMWA_Damage, + L4D2FMWA_RefireDelay, + L4D2FMWA_WeaponIdleTime, + MAX_SIZE_L4D2FloatMeleeWeaponAttributes +}; + + + +/** + * @brief Returns the weapon ID for a specific classname + * @remarks Can specify either "rifle" or "weapon_rifle" for example + * + * @param weaponName Weapon classname to check up on + * + * @return -1 if not found, otherwise returns weaponID + */ +native int L4D_GetWeaponID(const char[] weaponName); + +/** + * @brief Checks for a given weapon string to exist in the WeaponInformationDatabase + * @remarks Throws an error if Database is unavailable + * + * @param weaponName Weapon to check up on + * + * @return True if weapon is found, false if not + */ +native bool L4D2_IsValidWeapon(const char[] weaponName); + +/** + * @brief Read an int-typed attribute for a given weapon from the WeaponInformationDatabase + * @remarks Throws an error if the weapon is not found or the attribute is incorrect + * + * @param weaponName Weapon to lookup attribute for + * @param attr Attribute to read from the weapon's info struct + * + * @return The value read + */ +native int L4D2_GetIntWeaponAttribute(const char[] weaponName, L4D2IntWeaponAttributes attr); + +/** + * @brief Read a float-typed attribute for a given weapon from the WeaponInformationDatabase + * @remarks Throws an error if the weapon is not found or the attribute is incorrect + * + * @param weaponName Weapon to lookup attribute for + * @param attr Attribute to read from the weapon's info struct + * + * @return The value read + */ +native float L4D2_GetFloatWeaponAttribute(const char[] weaponName, L4D2FloatWeaponAttributes attr); + +/** + * @brief Set an int-typed attribute for a given weapon from the WeaponInformationDatabase to a given value + * @remarks Throws an error if the weapon is not found or the attribute is incorrect + * + * @param weaponName Weapon to lookup attribute for + * @param attr Attribute to alter in the weapon's info struct + * @param value Value to set the attribute to + * + * @noreturn + */ +native void L4D2_SetIntWeaponAttribute(const char[] weaponName, L4D2IntWeaponAttributes attr, int value); + +/** + * @brief Set a float-typed attribute for a given weapon from the WeaponInformationDatabase to a given value + * @remarks Throws an error if the weapon is not found or the attribute is incorrect + * + * @param weaponName Weapon to lookup attribute for + * @param attr Attribute to alter in the weapon's info struct + * @param value Value to set the attribute to + * + * @noreturn + */ +native void L4D2_SetFloatWeaponAttribute(const char[] weaponName, L4D2FloatWeaponAttributes attr, float value); + + + +/** + * @brief Retrieve the index for a given melee weapon from the Melee Weapon Database + * @remarks Index updated on OnMapStart - suggest using RequestFrame to find index + * @remarks Index can change depending on available melee weapons each map + * + * @param weaponName Weapon to lookup index id for + * + * @return The index id. Returns -1 if no match is found or melee unavailable + */ +// L4D2 only +native int L4D2_GetMeleeWeaponIndex(const char[] weaponName); + +/** + * @brief Read an int-typed attribute for a given id from the Melee Weapon Database + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to read from the weapon's info struct + * + * @return The value read + */ +// L4D2 only +native int L4D2_GetIntMeleeAttribute(int id, L4D2IntMeleeWeaponAttributes attr); + +/** + * @brief Read a float-typed attribute for a given id from the Melee Weapon Database + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to read from the weapon's info struct + * + * @return The value read + */ +// L4D2 only +native float L4D2_GetFloatMeleeAttribute(int id, L4D2FloatMeleeWeaponAttributes attr); + +/** + * @brief Read a bool-typed attribute for a given id from the Melee Weapon Database + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to read from the weapon's info struct + * + * @return The value read + */ +// L4D2 only +native bool L4D2_GetBoolMeleeAttribute(int id, L4D2BoolMeleeWeaponAttributes attr); + +/** + * @brief Set an int-typed attribute for a given id from the Melee Weapon Database to a given value + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to alter in the weapon's info struct + * @param value Value to set the attribute to + * + * @noreturn + */ +// L4D2 only +native void L4D2_SetIntMeleeAttribute(int id, L4D2IntMeleeWeaponAttributes attr, int value); + +/** + * @brief Set a float-typed attribute for a given id from the Melee Weapon Database to a given value + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to alter in the weapon's info struct + * @param value Value to set the attribute to + * + * @noreturn + */ +// L4D2 only +native void L4D2_SetFloatMeleeAttribute(int id, L4D2FloatMeleeWeaponAttributes attr, float value); + +/** + * @brief Set a bool-typed attribute for a given id from the Melee Weapon Database to a given value + * @remarks Throws an error if the id is not found or the attribute is incorrect + * + * @param id Melee id to lookup attribute for + * @param attr Attribute to alter in the weapon's info struct + * @param value Value to set the attribute to + * + * @noreturn + */ +// L4D2 only +native void L4D2_SetBoolMeleeAttribute(int id, L4D2BoolMeleeWeaponAttributes attr, bool value); + + + + + +// ==================================================================================================== +// NATIVES - l4d2_direct.inc +// ==================================================================================================== +enum CountdownTimer +{ + CTimer_Null = 0 /**< Invalid Timer when lookup fails */ +}; + +enum IntervalTimer +{ + ITimer_Null = 0 /**< Invalid Timer when lookup fails */ +}; + + + +/* CDirector Variable access */ + +/** + * Get the current Tank count stored by the director + * + * @note This should work on any gamemode, and is a good check to see if there is a tank in play + * + * @return The current number of tanks in play + * @error Director address not found + */ +native int L4D2Direct_GetTankCount(); + +/** + * Returns the number of infected waiting to spawn + * + * @return Mob size + */ +native int L4D2Direct_GetPendingMobCount(); + +/** + * Sets the number of infected waiting to spawn + * + * @param count Mob size + * + * @noreturn + */ +native void L4D2Direct_SetPendingMobCount(int count); + +/** + * Get a reference to the CDirector natural mob spawn CountdownTimer + * @note This timer is used to control the spawning of natural hordes + * @note This timer gets reset during unnatural hordes as well (boomer/car alarm hordes) + * @note Some scripted events will effectively "take over", by reducing the mob spawn time + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + */ +native CountdownTimer L4D2Direct_GetMobSpawnTimer(); + +/** + * Get a reference to a IntervalTimer that counts up from the last death of a given SI class + * @note The main place I've seen these timers used is in the SI spawning algorithms (CDirector::UpdateSpecialSpawns) + * @note This timer gets checked against SI respawn interval for different gamemodes, some of which are cvar controlled (e.g. versus_special_respawn_interval) + * + * @param class SI Class to retrieve timer for + * + * @return IntervalTimer reference to the timer, or ITimer_Null on lookup failure or bad class + */ +// L4D2 only +native IntervalTimer L4D2Direct_GetSIClassDeathTimer(int class); + +/** + * Get a reference to a CountdownTimer that counts down from the last attempted director-controlled spawn of an SI + * @note The main place I've seen these timers used is in the SI spawning algorithms (CDirector::UpdateSpecialSpawns) + * @note This timer is hard-coded to use a duration of 20.0s + * + * @param class SI Class to retrieve timer for + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure or bad class + */ +// L4D2 only +native CountdownTimer L4D2Direct_GetSIClassSpawnTimer(int class); + +/** + * Gets the number of times the tank has passed to a player + * @note When this variable is >1 the tank will be replaced with a bot when the his frustration reaches 0 + * @note The initial pass from AI to a player counts as a pass + * @note As this is global on the director weird things could potentially happen if more than one tank is alive at a time with z_frustration 1 + * + * @return The number of passes + */ +native int L4D2Direct_GetTankPassedCount(); + +/** + * Sets the number of times the tank has passed to a player + * @note When this variable is >1 the tank will be replaced with a bot when the his frustration reaches 0 + * @note The initial pass from AI to a player counts as a pass + * @note As this is global on the director weird things could potentially happen if more than one tank is alive at a time with z_frustration 1 + * + * @param passes New number of passes value + * + * @noreturn + */ +native void L4D2Direct_SetTankPassedCount(int passes); + + + +/* CDirectorVersusMode Variable access */ + +/** + * Reads the director's stored campaign score for a given team + * + * @note You can use the gamerules m_bAreTeamsFlipped property to figure out team numbers + * @note The campaign scores value is also stored in gamerules, however this is the "master" version + * @note Campaign scores are only updated on round end, so this will not reflect current survivor distance score + * + * @param teamNumber Team number to read campaign score of, 0 or 1 + * + * @return Campaign score for the given team + * @error Director or Versus Director address not found + */ +native int L4D2Direct_GetVSCampaignScore(int teamNumber); + +/** + * Set the director's stored campaign score for a given team + * + * @note You can use the gamerules m_bAreTeamsFlipped property to figure out team numbers + * @note The campaign scores value is also stored in gamerules, however this is the "master" version + * @note Keep in mind the current survivor team's distance/bonus score will be added at the end of a round + * + * @param teamNumber Team number to set campaign score of, 0 or 1 + * @param score Score to set for the team + * + * @noreturn + * @error Director or Versus Director address not found + */ +native void L4D2Direct_SetVSCampaignScore(int teamNumber, int score); + +/** + * Reads the tank flow percent for a given round for versus mode + * + * @note You should check GetVSTankToSpawnThisRound to find out if a tank is going to be spawned for this round + * @note When the survivors reach this flow percent minus versus_boss_buffer converted to flow percent, a tank will spawn + * + * @param roundNumber Round number to read tank spawn flow percent of + * + * @return Tank spawn flow percent for the given round + * @error Director or Versus Director address not found + */ +native float L4D2Direct_GetVSTankFlowPercent(int roundNumber); + +/** + * Sets the tank flow percent for a given round for versus mode + * + * @note You should check GetVSTankToSpawnThisRound to find out if there is still a tank to spawn this round + * @note When the survivors reach this flow percent minus versus_boss_buffer converted to flow percent, a tank will spawn + * + * @param roundNumber Round number to set tank spawn flow percent of + * @param flow Floating point percent of flow distance + * + * @noreturn + * @error Director or Versus Director address not found + */ +native void L4D2Direct_SetVSTankFlowPercent(int roundNumber, float flow); + +/** + * Is there going to be a tank spawned during the given round + * + * @param roundNumber Round number to check for tank spawn on + * + * @return True if there is still a tank to spawn for the given round, false if it has already been spawned or will not spawn + * @error Director or Versus Director address not found + */ +native bool L4D2Direct_GetVSTankToSpawnThisRound(int roundNumber); + +/** + * Tell the director whether or not to spawn a(nother) flow distance-based tank for this round + * @note If you set this to true after a flow-distance-based tank has been spawned, this can trigger another tank to be spawned based on flow distance + * + * @param roundNumber Round number to set a tank spawn on + * @param spawn Whether or not to spawn a flow-distance-based tank for this round + * + * @noreturn + * @error Director or Versus Director address not found + */ +native void L4D2Direct_SetVSTankToSpawnThisRound(int roundNumber, bool spawn); + +/** + * Reads the witch flow percent for a given round for versus mode + * + * @note You should check GetVSWitchToSpawnThisRound to find out if a witch is going to be spawned for this round + * @note When the survivors reach this flow percent minus versus_boss_buffer converted to flow percent, a witch will spawn + * + * @param roundNumber Round number to read witch spawn flow percent of + * + * @return Witch spawn flow percent for the given round + * @error Director or Versus Director address not found + */ +native float L4D2Direct_GetVSWitchFlowPercent(int roundNumber); + +/** + * Sets the witch flow percent for a given round for versus mode + * + * @note You should check GetVSWitchToSpawnThisRound to find out if there is still a witch to spawn this round + * @note When the survivors reach this flow percent minus versus_boss_buffer converted to flow percent, a witch will spawn + * + * @param roundNumber Round number to set witch spawn flow percent of + * @param flow Floating point percent of flow distance + * + * @noreturn + * @error Director or Versus Director address not found + */ +native void L4D2Direct_SetVSWitchFlowPercent(int roundNumber, float flow); + +/** + * Is there going to be a witch spawned during the given round + * + * @param roundNumber Round number to check for witch spawn on + * + * @return True if there is still a witch to spawn for the given round, false if it has already been spawned or will not spawn + * @error Director or Versus Director address not found + */ +native bool L4D2Direct_GetVSWitchToSpawnThisRound(int roundNumber); + +/** + * Tell the director whether or not to spawn a(nother) flow distance-based witch for this round + * @note If you set this to true after a flow-distance-based witch has been spawned, this can trigger another witch to be spawned based on flow distance + * + * @param roundNumber Round number to set a witch spawn on + * @param spawn Whether or not to spawn a flow-distance-based witch for this round + * + * @noreturn + * @error Director or Versus Director address not found + */ +native void L4D2Direct_SetVSWitchToSpawnThisRound(int roundNumber, bool spawn); + +/** + * Get a reference to the VersusStart CountdownTimer + * @note This timer controls when the saferoom door will open and PZ spawning is enabled + * @note The default duration for this timer is controlled by cvar: versus_force_start_time + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + * @error Director address not found + */ +// L4D2 only +native CountdownTimer L4D2Direct_GetVSStartTimer(); + + + +/* CDirectorScavengeMode Variable access */ + +/** + * Get a reference to the Scavenge Round Setup CountdownTimer + * @note This timer controls when the scavenge "warmup" time ends and PZ/game timers start + * @note The default duration for this timer is controlled by cvar: scavenge_round_setup_time + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + * @error Director address not found + */ +// L4D2 only +native CountdownTimer L4D2Direct_GetScavengeRoundSetupTimer(); + +/** + * Get a reference to the Scavenge Overtime Grace CountdownTimer + * @note This timer keeps track of how long survivors have gone without holding a can during overtime + * @note The default duration for this timer is controlled by cvar: scavenge_overtime_grace_time + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + * @error Director address not found + */ +// L4D2 only +native CountdownTimer L4D2Direct_GetScavengeOvertimeGraceTimer(); + + + +/* TerrorNavMesh Variable access */ + +/** + * Get the max flow distance (in flow units) for the current map + * @note The flow distance for each map is generated as it is loaded, and it can change slightly (a few hundred units) with each load + * @note You can use this value to convert a flow distance to a flow percent, and vice versa + * + * @return Max flow distance for the current loaded map + * @error TerrorNavMesh address not found + */ +native float L4D2Direct_GetMapMaxFlowDistance(); + + + +/* CTerrorPlayer Variable access */ + +/** + * Get a reference to a CountdownTimer that tracks when an SI player can next spawn + * @note The duration of this timer is controlled by the cvars z_ghost_delay_min and z_ghost_delay_max + * @remarks It is advised to use the "L4D_GetPlayerSpawnTime" native instead of this + * + * @param client Client id to get the spawn timer for + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + * @error Invalid client + */ +// L4D2 only +native CountdownTimer L4D2Direct_GetSpawnTimer(int client); + +/** + * Get a reference to a CountdownTimer that tracks when an survivor player is invulnerable due to "godframes" + * + * @param client Client id to get the godframes timer for + * + * @return CountdownTimer reference to the timer, or CTimer_Null on lookup failure + * @error Invalid client + */ +native CountdownTimer L4D2Direct_GetInvulnerabilityTimer(int client); + +/** + * Looks up the number of tickets a client has for entry into the tank lottery + * @note The number of tickets you have is equal to your damage done as an SI and will still increase as you do damage with the Tank + * @note When the tank is passed away from you your tickets are set back to zero + * + * @param client Client id to get the tickets for + * + * @return Number of tickets + * @error Invalid client + */ +native int L4D2Direct_GetTankTickets(int client); + +/** + * Sets the number of tickets a player has for entry into the tank lottery + * + * @param client Client id to set the tickets for + * @param tickets New value for the client's tank lottery tickets + * + * @noreturn + * @error Invalid client + */ +native void L4D2Direct_SetTankTickets(int client, int tickets); + +/** + * Gets a client's shove penalty + * @note The returned value will be between 0 and z_gun_swing_{vs,coop}_max_penalty + * + * @param client Client id + * + * @return Shove penalty or -1 on error + */ +// L4D2 only +#pragma deprecated Use this instead: GetEntProp(client, Prop_Send, "m_iShovePenalty"); +native int L4D2Direct_GetShovePenalty(int client); + +/** + * Sets a client's shove penalty + * @note The penalty should be set between 0 and z_gun_swing_{vs,coop}_max_penalty + * + * @param client Client id + * @param penalty Shove penalty + * + * @noreturn + */ +// L4D2 only +#pragma deprecated Use this instead: SetEntProp(client, Prop_Send, "m_iShovePenalty", penalty); +native void L4D2Direct_SetShovePenalty(int client, int penalty); + +/** + * Gets the time at which a survivor can perform his next +attack2 + * + * @param client Client id + * + * @return Time or 0.0 on error + */ +// L4D2 only +native float L4D2Direct_GetNextShoveTime(int client); + +/** + * Sets the time at which a survivor can perform his next +attack2 + * + * @param client Client id + * @param time Game time + * + * @noreturn + */ +// L4D2 only +native void L4D2Direct_SetNextShoveTime(int client, float time); + +/** + * Gets the health of the survivor from before they were incapacitated + * @note This may only apply to hanging players + * + * @param client Client id + * + * @return Real health before incapacitation + */ +// L4D2 only +native int L4D2Direct_GetPreIncapHealth(int client); + +/** + * Sets the health of the survivor from before they were incapacitated + * @note This may only apply to hanging players + * + * @param client Client id + * @param health New pre-incap health + * + * @noreturn + */ +// L4D2 only +native void L4D2Direct_SetPreIncapHealth(int client, int health); + +/** + * Gets the temporary health of the survivor from before they were incapacitated + * @note This may only apply to hanging players + * + * @param client Client id + * @return Temporary health before incapacitation + */ +// L4D2 only +native int L4D2Direct_GetPreIncapHealthBuffer(int client); + +/** + * Sets the health of the survivor from before they were incapacitated + * @note This may only apply to hanging players + * + * @param client Client id + * @param health New pre-incap temporary health + * + * @noreturn + */ +// L4D2 only +native void L4D2Direct_SetPreIncapHealthBuffer(int client, int health); + +/** + * Gets the maximum number of flames a CInferno is allowed to spawn + * + * @param entity Entity id + * + * @return Number of flames or -1 on error + */ +// L4D2 only +native int L4D2Direct_GetInfernoMaxFlames(int entity); + +/** + * Sets the maximum number of flames a CInferno is allowed to spawn + * + * @param entity Entity id + * @param flames Number of flames + * + * @noreturn + */ +// L4D2 only +native void L4D2Direct_SetInfernoMaxFlames(int entity, int flames); + +/** + * Returns the CDirectorScriptedEventManager address + * This native replicates "L4D2_GetCDirectorScriptedEventManager" used by other plugins + * + * @return Address pointer + */ +// L4D2 only +native any L4D2Direct_GetScriptedEventManager(); + +/** + * Get the TerrorNavArea which holds a specific position + * @note Some positions will not return a nav area (Address_Null). Notable examples are saferooms and small ledges like the guard rail at the start of c2m1_highway + * @remarks This is less reliable than L4D_GetNearestNavArea + * + * @param pos The position to find the containing nav area of + * @param beneathLimit + * + * @return Address to a TerrorNavArea or Address_Null + * @error Unable to prepare SDK call + */ +native Address L4D2Direct_GetTerrorNavArea(float pos[3], float beneathLimit = 120.0); + +/** + * Find the distance through the map (in flow units) that a TerrorNavArea is located + * + * @param pTerrorNavArea Pointer to a TerrorNavArea + * + * @return The flow units through the map that the TerrorNavArea is located at + * @error When passed an Address_Null + */ +native float L4D2Direct_GetTerrorNavAreaFlow(Address pTerrorNavArea); + +/** + * Force the director to pass the tank + * + * @param client Client index of the tank + * @param bEnterStasis Should the tank be put in stasis + * + * @return False on error otherwise true + */ +native bool L4D2Direct_TryOfferingTankBot(int client, int bEnterStasis); + +/** + * Gets a player's distance in flow units + * + * @param client Client ID + * + * @return 0.0 on error otherwise flow distance + */ +native float L4D2Direct_GetFlowDistance(int client); + +/** + * Plays the specified animation for a player + * @note The event argument is NOT the same as the sequence numbers found in the model viewer + * @note You can get the number for your animation by looking at the disasm for virtual calls to DoAnimationEvent + * + * @param client Client ID to do animation + * @param event Animation index (PlayerAnimEvent_t) + * + * @noreturn + */ +native void L4D2Direct_DoAnimationEvent(int client, int event, int variant_param = 0); + +/** + * Get the clients health bonus + * + * @note Survivors health bonuses are 0 until CTerrorPlayer:RecalculateVersusScore(void) calculates it + * + * @param client Client id whose health bonus is to be returned + * + * @return Int value of the survivors health bonus +*/ +// L4D1 only +native int L4DDirect_GetSurvivorHealthBonus(int client); + +/** + * Sets the clients health bonus + * + * @note Keep in mind the individual survivors health bonus will be recalculate again when CTerrorPlayer:RecalculateVersusScore(void) is invoked + * @note L4D_OnRecalculateVersusScore(client) forward (left4downtown exts) can block health bonus from being calculated to store your own value with this function + * + * @param client Client id to set the health bonus for + * @param health Number of health bonus + * @param recompute If true, L4DDirect_RecomputeTeamScores() is called after the health bonus has been set + * @noreturn + * @error Invalid client +*/ +// L4D1 only +native void L4DDirect_SetSurvivorHealthBonus(int client, int health, bool recompute = true); + +/** + * Compute the scores on the scoreboard + * + * @noparam + * @return False on error otherwise true + * @error SDK call preparation failed + */ +// L4D1 only +native void L4DDirect_RecomputeTeamScores(); + + + +/* CountdownTimer funcs */ + +/** + * Reset a CountdownTimer to begin counting down again from now to its original duration + * + * @param timer CountdownTimer to reset + * + * @noreturn + */ +native void CTimer_Reset(CountdownTimer timer); + +/** + * Start a CountdownTimer from now for a given duration + * + * @param timer CountdownTimer to reset + * @param duration Duration for this CountdownTimer to use, in seconds + * + * @noreturn + */ +native void CTimer_Start(CountdownTimer timer, float duration); + +/** + * Invalidate a CountdownTimer, so it is considered not running + * + * @param timer CountdownTimer to Invalidate + * + * @noreturn + */ + +native void CTimer_Invalidate(CountdownTimer timer); + +/** + * Determine if a CountdownTimer has started counting down + * + * @param timer CountdownTimer to check + * + * @return True if it has started running, False if it is not (Invalidated) + */ +native bool CTimer_HasStarted(CountdownTimer timer); + +/** + * Determine if a CountdownTimer is elapsed + * + * @param timer CountdownTimer to check + * + * @return True if the timer's duration has passed since it started, false otherwise + */ +native bool CTimer_IsElapsed(CountdownTimer timer); + +/** + * Check how long a CountdownTimer has been running + * + * @param timer CountdownTimer to check + * + * @return Time since the CountdownTimer was last Started or Reset, in seconds + */ +native float CTimer_GetElapsedTime(CountdownTimer timer); + +/** + * Check how much time remains before a CountdownTimer is elapsed + * + * @param timer CountdownTimer to check + * + * @return Time until the CountdownTimer is elapsed, in seconds + */ +native float CTimer_GetRemainingTime(CountdownTimer timer); + +/** + * Get the countdown duration used for a CountdownTimer + * + * @param timer CountdownTimer to check + * + * @return Countdown duration in seconds if timer is running, or 0.0 if timer is invalidated (not running) + */ +native float CTimer_GetCountdownDuration(CountdownTimer timer); + +/* IntervalTimer funcs */ + +/** + * Reset an IntervalTimer to begin counting up again from now + * + * @param timer IntervalTimer to reset + * + * @noreturn + */ +native void ITimer_Reset(IntervalTimer timer); + +/** + * Start an IntervalTimer to begin counting up from now + * + * @note This is the same as reset for IntervalTimers + * + * @param timer IntervalTimer to start + * + * @noreturn + */ +native void ITimer_Start(IntervalTimer timer); + +/** + * Invalidate an IntervalTimer, so it is considered not running + * + * @param timer IntervalTimer to Invalidate + * + * @noreturn + */ +native void ITimer_Invalidate(IntervalTimer timer); + +/** + * Check if an IntervalTimer has started + * + * @param timer IntervalTimer to check + * + * @return True if the IntervalTimer is running, false if it is Invalidated + */ +native bool ITimer_HasStarted(IntervalTimer timer); + +/** + * Get the elapsed time of an IntervalTimer + * + * @param timer IntervalTimer to check + * + * @return Elapsed time of the IntervalTimer in seconds if it has started, or 99999.9 ("infinite") if it is Invalidated + */ +native float ITimer_GetElapsedTime(IntervalTimer timer); + + + +/* Timer Internals */ + +/** + * Read duration variable in CTimer + * + * @param timer CountdownTimer to check + * + * @return CountdownTimer duration value + */ +native float CTimer_GetDuration(CountdownTimer timer); + +/** + * Set duration variable in CTimer + * + * @param timer CountdownTimer to check + * @param duration Duration to set + * + * @noreturn + */ +native void CTimer_SetDuration(CountdownTimer timer, float duration); + +/** + * Read timestamp variable in CTimer + * + * @param timer CountdownTimer to check + * + * @return CountdownTimer duration value + */ +native float CTimer_GetTimestamp(CountdownTimer timer); + +/** + * Set timestamp variable in CTimer + * + * @param timer CountdownTimer to check + * @param timestamp Timestamp to set + * + * @noreturn + */ +native void CTimer_SetTimestamp(CountdownTimer timer, float timestamp); + +/** + * Read timestamp variable in ITimer + * + * @param timer IntervalTimer to check + * + * @return IntervalTimer duration value + */ +native float ITimer_GetTimestamp(IntervalTimer timer); + +/** + * Set timestamp variable in ITimer + * + * @param timer IntervalTimer to check + * @param timestamp Timestamp to set + * + * @noreturn + */ +native void ITimer_SetTimestamp(IntervalTimer timer, float timestamp); + + + + + +// ==================================================================================================== +// NATIVES - l4d2addresses.txt +// ==================================================================================================== +/** + * @brief Creates the boomer vomit effect on Survivors or Special infected + * + * @param client Client ID of the person to affect + * @param attacker Client ID who caused the blindness, can be the same as client + * + * @noreturn + */ +native void L4D_CTerrorPlayer_OnVomitedUpon(int client, int attacker); + +/** + * @brief Creates the boomer vomit effect on Survivors or Special infected + * + * @param client Client ID of the person to affect + * @param attacker Client ID who caused the blindness, can be the same as client + * + * @noreturn + */ +// L4D2 only +native void L4D2_CTerrorPlayer_OnHitByVomitJar(int client, int attacker); + +/** + * @brief Creates the boomer vomit effect on Common infected + * + * @param entity Entity ID of the common to affect + * @param attacker Client ID who caused the blindness, can be the same as client + * + * @noreturn + */ +// L4D2 only +native void L4D2_Infected_OnHitByVomitJar(int entity, int attacker); + +/** + * @brief Flings a player to the ground, like they were hit by a Charger + * + * @param client Client ID of the person to affect + * @param attacker Client ID who caused the attack, can be the same as client + * @param vecDir Vector direction to throw the player + * + * @noreturn + */ +// L4D2 only +native void L4D2_CTerrorPlayer_Fling(int client, int attacker, const float vecDir[3]); + +/** + * @brief Cancels a player staggering + * + * @param client Client ID of the person to affect + * + * @noreturn + */ +native void L4D_CancelStagger(int client); + +/** + * @brief Flings a Survivor like when they're flung by a nearby Charger impact + * @remarks attacker can be the same client index as victim + * + * @param victim Client index of the Survivor affect + * @param attacker Client index of the client attacking the Survivor + * + * @noreturn + */ +// L4D2 only +native void L4D2_Charger_ThrowImpactedSurvivor(int victim, int attacker); + +/** + * @brief Makes a Charger carry a Survivor + * @remarks The Survivor is teleported after 0.3 seconds to position in the Chargers arms, the position is not perfect and could do with tweaking + * @remarks It seems like the Survivor is colliding with the Charger. If anyone fixes this please report the changes required + * + * @param victim Client index of the Survivor to affect + * @param attacker Client index of the Charger attacking the Survivor + * + * @noreturn + */ +// L4D2 only +native void L4D2_Charger_StartCarryingVictim(int victim, int attacker); + +/** + * @brief Makes a Charger pummel a Survivor + * + * @param victim Client index of the Survivor to affect + * @param attacker Client index of the Charger attacking the Survivor + * + * @noreturn + */ +// L4D2 only +native void L4D2_Charger_PummelVictim(int victim, int attacker); + +/** + * @brief Makes a Charger stop pummelling a Survivor + * + * @param victim Client index of the Survivor to affect + * @param attacker Client index of the Charger attacking the Survivor + * + * @noreturn + */ +// L4D2 only +native void L4D2_Charger_EndPummel(int victim, int attacker); + +/** + * @brief Makes a Jockey stop riding a Survivor + * + * @param victim Client index of the Survivor to affect + * @param attacker Client index of the Jockey riding the Survivor + * + * @noreturn + */ +// L4D2 only +native void L4D2_Jockey_EndRide(int victim, int attacker); + +/** + * @brief Spawns all dead survivors in rescuable rooms + * @remarks L4D1: Any survivor must not be in the starting area for it to work + * @remarks L4D2: Any survivor must have left the starting area for it to work, they can return and all be in the starting area + * @remarks By default the game would spawn one per frame, but I've added a RequestFrame loop to spawn all dead. Request if you want a singular spawn native + * + * @noreturn + */ +native void L4D_CreateRescuableSurvivors(); + +/** + * @brief Revives an incapacitated survivor, also from ledge hanging + * + * @param client Client ID of the person to affect + * + * @noreturn + */ +native void L4D_ReviveSurvivor(int client); + +/** + * @brief Retrieve a clients map flow progress percentage. Doesn't have to be Versus mode + * + * @param client Client ID of the person to affect + * + * @return Returns value from 0-100 + */ +// L4D2 only +native int L4D2_GetVersusCompletionPlayer(int client); + +/** + * @brief Returns client who is furthest in flow + * + * @return Client ID of the player furthest ahead + */ +native int L4D_GetHighestFlowSurvivor(); + +/** + * @brief Retrieve the specified common infected map flow distance + * + * @param entity Common infected ID + * + * @return flow distance + */ +native float L4D_GetInfectedFlowDistance(int entity); + +/** + * @brief Takeover another special infected + * @remarks L4D1: Due to some bug and a workaround, when spawning you'll hear another special infected sound other than your own type + * + * @param client Client ID of the special infected taking over + * @param target Client ID of the special infected losing control + * + * @noreturn + */ +native void L4D_TakeOverZombieBot(int client, int target); + +/** + * @brief Replaces the player with a bot + * @remarks Survivors: makes the player go into spectator mode and a bot takeover, like going idle + * @remarks Infected: basically spawns an identical bot in your position. The client is forced into ghost mode + * + * @param client Client ID of the player losing control + * + * @noreturn + */ +native void L4D_ReplaceWithBot(int client); + +/** + * @brief Kills the player. Teleports their view to a random survivor + * + * @param client Client ID of the player to kill. Not common infected + * + * @noreturn + */ +native void L4D_CullZombie(int client); + +/** + * @brief Resets a players state equivalent to when they die + * @remarks does stuff like removing any pounces, stops reviving, stops healing, resets hang lighting, resets heartbeat and other sounds + * + * @param client Client ID to affect + * + * @noreturn + */ +native void L4D_CleanupPlayerState(int client); + +/** + * @brief Sets a players zombie class, special infected can be alive and change! + * @remarks Valid values L4D1: 1-3. L4D2: 1-6 + * @remarks zombieClass: 1=Smoker, 2=Boomer, 3=Hunter, 4=Spitter, 5=Jockey, 6=Charger + * + * @param client Client ID of the player to kill. Not common infected + * @param zombieClass Zombie class number to change to + * + * @noreturn + */ +native void L4D_SetClass(int client, int zombieClass); + +/** + * @brief Spawns a special infected from ghost state. Returns the clients "m_customAbility" weapon, or -1 on error (possibly not a ghost) + * + * @param client Client ID of the player to materialize + * + * @return Clients "m_customAbility" weapon entity ID or -1 on error + */ +native int L4D_MaterializeFromGhost(int client); + +/** + * @brief Turns an alive player into the ghost state + * + * @param client Client ID of the player to affect + * + * @return True on success, false on error or if already ghost state + */ +native bool L4D_BecomeGhost(int client); + +/** + * @brief Enter ghost/dead mode. Some state values may have different results. Unknown + * @remarks 6 and 8 are commonly used by the game + * @remarks Can use the "STATE_*" enums (search for them above) + * + * @param client Client ID of the player to affect + * + * @noreturn + */ +native void L4D_State_Transition(int client, any state); + +/** + * @brief Swaps the teams in Versus + * @remarks Some survivors may spawn dead on swapping, seems to be random + * + * @noreturn + */ +// L4D2 only +native void L4D2_SwapTeams(); + +/** + * @brief Returns if Versus team are flipped + * + * @return 0=Not flipped. 1=Flipped + */ +// L4D2 only +#pragma deprecated Use this instead: GameRules_GetProp("m_bAreTeamsFlipped"); +native bool L4D2_AreTeamsFlipped(); + +/** + * @brief Starts a Versus rematch vote like end of game before credits roll + * @remarks Failing a successful vote players are kicked back to lobby + * + * @noreturn + */ +// L4D2 only +native void L4D2_StartRematchVote(); + +/** + * @brief Seems to restart the chapter like "mp_restartgame". In Versus the teams flip + * + * @noreturn + */ +// L4D2 only +native void L4D2_FullRestart(); + +/** + * @brief Hides end of round scoreboard + * + * @noreturn + */ +// L4D2 only +native void L4D2_HideVersusScoreboard(); + +/** + * @brief Hides end of round scoreboard + * + * @noreturn + */ +// L4D2 only +native void L4D2_HideScavengeScoreboard(); + +/** + * @brief Hides end of round scoreboard + * + * @noreturn + */ +// L4D2 only +native void L4D2_HideScoreboard(); + +/** + * @brief NOT WORKING? Setup car alarm for object. Seems to have no affect. Only works on prop_breakable or prop_car_alarm? + * + * @return Some memory address (large value) or possibly ID if already registered (low value from 1+) + */ +native int L4D_RegisterForbiddenTarget(int entity); + +/** + * @brief NOT WORKING? Remove car alarm for object. Seems to have no affect. Only works on prop_breakable or prop_car_alarm? + * + * @return Some memory address (large value) or possibly ID if already registered (low value from 1+) + */ +native void L4D_UnRegisterForbiddenTarget(int entity); \ No newline at end of file diff --git a/scripting/include/left4dhooks_anim.inc b/scripting/include/left4dhooks_anim.inc new file mode 100644 index 0000000..776a509 --- /dev/null +++ b/scripting/include/left4dhooks_anim.inc @@ -0,0 +1,4095 @@ +/* +* Left 4 DHooks Direct +* Copyright (C) 2023 Silvers +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +#if defined _l4d_anim_included + #endinput +#endif +#define _l4d_anim_included + +#include +#include + +#tryinclude +#tryinclude +#tryinclude + + + + + +// ==================================================================================================== +// ACT_* ANIMATION VALUES +// ==================================================================================================== +// To find list: Search for "ACT_RESET" for example, in the server binary. XRef to the "ActivityList_RegisterSharedActivities" function. View in HexRays to see the full list of constants and values. +// These constants can be used in a plugins source code instead of hard coding the Activity number when working with the animation pre-hook. +// Only for Survivors, not Special Infected. + + + +// ==================================================================================================== +// LEFT 4 DEAD 1 +// ==================================================================================================== +enum +{ + L4D1_ACT_RESET, + L4D1_ACT_IDLE, + L4D1_ACT_TRANSITION, + L4D1_ACT_COVER, + L4D1_ACT_COVER_MED, + L4D1_ACT_COVER_LOW, + L4D1_ACT_WALK, + L4D1_ACT_WALK_AIM, + L4D1_ACT_WALK_CROUCH, + L4D1_ACT_WALK_CROUCH_AIM, + L4D1_ACT_RUN, + L4D1_ACT_RUN_AIM, + L4D1_ACT_RUN_CROUCH, + L4D1_ACT_RUN_CROUCH_AIM, + L4D1_ACT_RUN_PROTECTED, + L4D1_ACT_SCRIPT_CUSTOM_MOVE, + L4D1_ACT_RANGE_ATTACK1, + L4D1_ACT_RANGE_ATTACK2, + L4D1_ACT_RANGE_ATTACK1_LOW, + L4D1_ACT_RANGE_ATTACK2_LOW, + L4D1_ACT_DIESIMPLE, + L4D1_ACT_DIEBACKWARD, + L4D1_ACT_DIEFORWARD, + L4D1_ACT_DIEVIOLENT, + L4D1_ACT_DIERAGDOLL, + L4D1_ACT_FLY, + L4D1_ACT_HOVER, + L4D1_ACT_GLIDE, + L4D1_ACT_SWIM, + L4D1_ACT_JUMP, + L4D1_ACT_HOP, + L4D1_ACT_LEAP, + L4D1_ACT_LAND, + L4D1_ACT_CLIMB_UP, + L4D1_ACT_CLIMB_DOWN, + L4D1_ACT_CLIMB_DISMOUNT, + L4D1_ACT_SHIPLADDER_UP, + L4D1_ACT_SHIPLADDER_DOWN, + L4D1_ACT_STRAFE_LEFT, + L4D1_ACT_STRAFE_RIGHT, + L4D1_ACT_ROLL_LEFT, + L4D1_ACT_ROLL_RIGHT, + L4D1_ACT_TURN_LEFT, + L4D1_ACT_TURN_RIGHT, + L4D1_ACT_CROUCH, + L4D1_ACT_CROUCHIDLE, + L4D1_ACT_STAND, + L4D1_ACT_USE, + L4D1_ACT_SIGNAL1, + L4D1_ACT_SIGNAL2, + L4D1_ACT_SIGNAL3, + L4D1_ACT_SIGNAL_ADVANCE, + L4D1_ACT_SIGNAL_FORWARD, + L4D1_ACT_SIGNAL_GROUP, + L4D1_ACT_SIGNAL_HALT, + L4D1_ACT_SIGNAL_LEFT, + L4D1_ACT_SIGNAL_RIGHT, + L4D1_ACT_SIGNAL_TAKECOVER, + L4D1_ACT_LOOKBACK_RIGHT, + L4D1_ACT_LOOKBACK_LEFT, + L4D1_ACT_COWER, + L4D1_ACT_SMALL_FLINCH, + L4D1_ACT_BIG_FLINCH, + L4D1_ACT_MELEE_ATTACK1, + L4D1_ACT_MELEE_ATTACK2, + L4D1_ACT_RELOAD, + L4D1_ACT_RELOAD_START, + L4D1_ACT_RELOAD_FINISH, + L4D1_ACT_RELOAD_LOW, + L4D1_ACT_ARM, + L4D1_ACT_DISARM, + L4D1_ACT_DROP_WEAPON, + L4D1_ACT_DROP_WEAPON_SHOTGUN, + L4D1_ACT_PICKUP_GROUND, + L4D1_ACT_PICKUP_RACK, + L4D1_ACT_IDLE_ANGRY, + L4D1_ACT_IDLE_RELAXED, + L4D1_ACT_IDLE_STIMULATED, + L4D1_ACT_IDLE_AGITATED, + L4D1_ACT_IDLE_STEALTH, + L4D1_ACT_IDLE_HURT, + L4D1_ACT_WALK_RELAXED, + L4D1_ACT_WALK_STIMULATED, + L4D1_ACT_WALK_AGITATED, + L4D1_ACT_WALK_STEALTH, + L4D1_ACT_RUN_RELAXED, + L4D1_ACT_RUN_STIMULATED, + L4D1_ACT_RUN_AGITATED, + L4D1_ACT_RUN_STEALTH, + L4D1_ACT_IDLE_AIM_RELAXED, + L4D1_ACT_IDLE_AIM_STIMULATED, + L4D1_ACT_IDLE_AIM_AGITATED, + L4D1_ACT_IDLE_AIM_STEALTH, + L4D1_ACT_WALK_AIM_RELAXED, + L4D1_ACT_WALK_AIM_STIMULATED, + L4D1_ACT_WALK_AIM_AGITATED, + L4D1_ACT_WALK_AIM_STEALTH, + L4D1_ACT_RUN_AIM_RELAXED, + L4D1_ACT_RUN_AIM_STIMULATED, + L4D1_ACT_RUN_AIM_AGITATED, + L4D1_ACT_RUN_AIM_STEALTH, + L4D1_ACT_CROUCHIDLE_STIMULATED, + L4D1_ACT_CROUCHIDLE_AIM_STIMULATED, + L4D1_ACT_CROUCHIDLE_AGITATED, + L4D1_ACT_WALK_HURT, + L4D1_ACT_RUN_HURT, + L4D1_ACT_SPECIAL_ATTACK1, + L4D1_ACT_SPECIAL_ATTACK2, + L4D1_ACT_COMBAT_IDLE, + L4D1_ACT_WALK_SCARED, + L4D1_ACT_RUN_SCARED, + L4D1_ACT_VICTORY_DANCE, + L4D1_ACT_DIE_HEADSHOT, + L4D1_ACT_DIE_CHESTSHOT, + L4D1_ACT_DIE_GUTSHOT, + L4D1_ACT_DIE_BACKSHOT, + L4D1_ACT_FLINCH_HEAD, + L4D1_ACT_FLINCH_CHEST, + L4D1_ACT_FLINCH_STOMACH, + L4D1_ACT_FLINCH_LEFTARM, + L4D1_ACT_FLINCH_RIGHTARM, + L4D1_ACT_FLINCH_LEFTLEG, + L4D1_ACT_FLINCH_RIGHTLEG, + L4D1_ACT_FLINCH_PHYSICS, + L4D1_ACT_FLINCH_HEAD_BACK, + L4D1_ACT_FLINCH_CHEST_BACK, + L4D1_ACT_FLINCH_STOMACH_BACK, + L4D1_ACT_FLINCH_CROUCH_FRONT, + L4D1_ACT_FLINCH_CROUCH_BACK, + L4D1_ACT_FLINCH_CROUCH_LEFT, + L4D1_ACT_FLINCH_CROUCH_RIGHT, + L4D1_ACT_IDLE_ON_FIRE, + L4D1_ACT_WALK_ON_FIRE, + L4D1_ACT_RUN_ON_FIRE, + L4D1_ACT_RAPPEL_LOOP, + L4D1_ACT_180_LEFT, + L4D1_ACT_180_RIGHT, + L4D1_ACT_90_LEFT, + L4D1_ACT_90_RIGHT, + L4D1_ACT_STEP_LEFT, + L4D1_ACT_STEP_RIGHT, + L4D1_ACT_STEP_BACK, + L4D1_ACT_STEP_FORE, + L4D1_ACT_GESTURE_RANGE_ATTACK1, + L4D1_ACT_GESTURE_RANGE_ATTACK2, + L4D1_ACT_GESTURE_MELEE_ATTACK1, + L4D1_ACT_GESTURE_MELEE_ATTACK2, + L4D1_ACT_GESTURE_RANGE_ATTACK1_LOW, + L4D1_ACT_GESTURE_RANGE_ATTACK2_LOW, + L4D1_ACT_MELEE_ATTACK_SWING_GESTURE, + L4D1_ACT_GESTURE_SMALL_FLINCH, + L4D1_ACT_GESTURE_BIG_FLINCH, + L4D1_ACT_GESTURE_FLINCH_BLAST, + L4D1_ACT_GESTURE_FLINCH_BLAST_SHOTGUN, + L4D1_ACT_GESTURE_FLINCH_BLAST_DAMAGED, + L4D1_ACT_GESTURE_FLINCH_BLAST_DAMAGED_SHOTGUN, + L4D1_ACT_GESTURE_FLINCH_HEAD, + L4D1_ACT_GESTURE_FLINCH_CHEST, + L4D1_ACT_GESTURE_FLINCH_STOMACH, + L4D1_ACT_GESTURE_FLINCH_LEFTARM, + L4D1_ACT_GESTURE_FLINCH_RIGHTARM, + L4D1_ACT_GESTURE_FLINCH_LEFTLEG, + L4D1_ACT_GESTURE_FLINCH_RIGHTLEG, + L4D1_ACT_GESTURE_TURN_LEFT, + L4D1_ACT_GESTURE_TURN_RIGHT, + L4D1_ACT_GESTURE_TURN_LEFT45, + L4D1_ACT_GESTURE_TURN_RIGHT45, + L4D1_ACT_GESTURE_TURN_LEFT90, + L4D1_ACT_GESTURE_TURN_RIGHT90, + L4D1_ACT_GESTURE_TURN_LEFT45_FLAT, + L4D1_ACT_GESTURE_TURN_RIGHT45_FLAT, + L4D1_ACT_GESTURE_TURN_LEFT90_FLAT, + L4D1_ACT_GESTURE_TURN_RIGHT90_FLAT, + L4D1_ACT_BARNACLE_HIT, + L4D1_ACT_BARNACLE_PULL, + L4D1_ACT_BARNACLE_CHOMP, + L4D1_ACT_BARNACLE_CHEW, + L4D1_ACT_DO_NOT_DISTURB, + L4D1_ACT_VM_DRAW, + L4D1_ACT_VM_HOLSTER, + L4D1_ACT_VM_IDLE, + L4D1_ACT_VM_FIDGET, + L4D1_ACT_VM_PULLBACK, + L4D1_ACT_VM_PULLBACK_HIGH, + L4D1_ACT_VM_PULLBACK_LOW, + L4D1_ACT_VM_THROW, + L4D1_ACT_VM_PULLPIN, + L4D1_ACT_VM_PRIMARYATTACK, + L4D1_ACT_VM_SECONDARYATTACK, + L4D1_ACT_VM_RELOAD, + L4D1_ACT_VM_DRYFIRE, + L4D1_ACT_VM_HITLEFT, + L4D1_ACT_VM_HITLEFT2, + L4D1_ACT_VM_HITRIGHT, + L4D1_ACT_VM_HITRIGHT2, + L4D1_ACT_VM_HITCENTER, + L4D1_ACT_VM_HITCENTER2, + L4D1_ACT_VM_MISSLEFT, + L4D1_ACT_VM_MISSLEFT2, + L4D1_ACT_VM_MISSRIGHT, + L4D1_ACT_VM_MISSRIGHT2, + L4D1_ACT_VM_MISSCENTER, + L4D1_ACT_VM_MISSCENTER2, + L4D1_ACT_VM_HAULBACK, + L4D1_ACT_VM_SWINGHARD, + L4D1_ACT_VM_SWINGMISS, + L4D1_ACT_VM_SWINGHIT, + L4D1_ACT_VM_IDLE_TO_LOWERED, + L4D1_ACT_VM_IDLE_LOWERED, + L4D1_ACT_VM_LOWERED_TO_IDLE, + L4D1_ACT_VM_RECOIL1, + L4D1_ACT_VM_RECOIL2, + L4D1_ACT_VM_RECOIL3, + L4D1_ACT_VM_PICKUP, + L4D1_ACT_VM_RELEASE, + L4D1_ACT_VM_ATTACH_SILENCER, + L4D1_ACT_VM_DETACH_SILENCER, + L4D1_ACT_SLAM_STICKWALL_IDLE, + L4D1_ACT_SLAM_STICKWALL_ND_IDLE, + L4D1_ACT_SLAM_STICKWALL_ATTACH, + L4D1_ACT_SLAM_STICKWALL_ATTACH2, + L4D1_ACT_SLAM_STICKWALL_ND_ATTACH, + L4D1_ACT_SLAM_STICKWALL_ND_ATTACH2, + L4D1_ACT_SLAM_STICKWALL_DETONATE, + L4D1_ACT_SLAM_STICKWALL_DETONATOR_HOLSTER, + L4D1_ACT_SLAM_STICKWALL_DRAW, + L4D1_ACT_SLAM_STICKWALL_ND_DRAW, + L4D1_ACT_SLAM_STICKWALL_TO_THROW, + L4D1_ACT_SLAM_STICKWALL_TO_THROW_ND, + L4D1_ACT_SLAM_STICKWALL_TO_TRIPMINE_ND, + L4D1_ACT_SLAM_THROW_IDLE, + L4D1_ACT_SLAM_THROW_ND_IDLE, + L4D1_ACT_SLAM_THROW_THROW, + L4D1_ACT_SLAM_THROW_THROW2, + L4D1_ACT_SLAM_THROW_THROW_ND, + L4D1_ACT_SLAM_THROW_THROW_ND2, + L4D1_ACT_SLAM_THROW_DRAW, + L4D1_ACT_SLAM_THROW_ND_DRAW, + L4D1_ACT_SLAM_THROW_TO_STICKWALL, + L4D1_ACT_SLAM_THROW_TO_STICKWALL_ND, + L4D1_ACT_SLAM_THROW_DETONATE, + L4D1_ACT_SLAM_THROW_DETONATOR_HOLSTER, + L4D1_ACT_SLAM_THROW_TO_TRIPMINE_ND, + L4D1_ACT_SLAM_TRIPMINE_IDLE, + L4D1_ACT_SLAM_TRIPMINE_DRAW, + L4D1_ACT_SLAM_TRIPMINE_ATTACH, + L4D1_ACT_SLAM_TRIPMINE_ATTACH2, + L4D1_ACT_SLAM_TRIPMINE_TO_STICKWALL_ND, + L4D1_ACT_SLAM_TRIPMINE_TO_THROW_ND, + L4D1_ACT_SLAM_DETONATOR_IDLE, + L4D1_ACT_SLAM_DETONATOR_DRAW, + L4D1_ACT_SLAM_DETONATOR_DETONATE, + L4D1_ACT_SLAM_DETONATOR_HOLSTER, + L4D1_ACT_SLAM_DETONATOR_STICKWALL_DRAW, + L4D1_ACT_SLAM_DETONATOR_THROW_DRAW, + L4D1_ACT_SHOTGUN_RELOAD_START, + L4D1_ACT_SHOTGUN_RELOAD_FINISH, + L4D1_ACT_SHOTGUN_PUMP, + L4D1_ACT_SMG2_IDLE2, + L4D1_ACT_SMG2_FIRE2, + L4D1_ACT_SMG2_DRAW2, + L4D1_ACT_SMG2_RELOAD2, + L4D1_ACT_SMG2_DRYFIRE2, + L4D1_ACT_SMG2_TOAUTO, + L4D1_ACT_SMG2_TOBURST, + L4D1_ACT_PHYSCANNON_UPGRADE, + L4D1_ACT_RANGE_ATTACK_AR1, + L4D1_ACT_RANGE_ATTACK_AR2, + L4D1_ACT_RANGE_ATTACK_AR2_LOW, + L4D1_ACT_RANGE_ATTACK_AR2_GRENADE, + L4D1_ACT_RANGE_ATTACK_HMG1, + L4D1_ACT_RANGE_ATTACK_ML, + L4D1_ACT_RANGE_ATTACK_SMG1, + L4D1_ACT_RANGE_ATTACK_SMG1_LOW, + L4D1_ACT_RANGE_ATTACK_SMG2, + L4D1_ACT_RANGE_ATTACK_SHOTGUN, + L4D1_ACT_RANGE_ATTACK_SHOTGUN_LOW, + L4D1_ACT_RANGE_ATTACK_PISTOL, + L4D1_ACT_RANGE_ATTACK_PISTOL_LOW, + L4D1_ACT_RANGE_ATTACK_SLAM, + L4D1_ACT_RANGE_ATTACK_TRIPWIRE, + L4D1_ACT_RANGE_ATTACK_THROW, + L4D1_ACT_RANGE_ATTACK_SNIPER_RIFLE, + L4D1_ACT_RANGE_ATTACK_RPG, + L4D1_ACT_MELEE_ATTACK_SWING, + L4D1_ACT_RANGE_AIM_LOW, + L4D1_ACT_RANGE_AIM_SMG1_LOW, + L4D1_ACT_RANGE_AIM_PISTOL_LOW, + L4D1_ACT_RANGE_AIM_AR2_LOW, + L4D1_ACT_COVER_PISTOL_LOW, + L4D1_ACT_COVER_SMG1_LOW, + L4D1_ACT_GESTURE_RANGE_ATTACK_AR1, + L4D1_ACT_GESTURE_RANGE_ATTACK_AR2, + L4D1_ACT_GESTURE_RANGE_ATTACK_AR2_GRENADE, + L4D1_ACT_GESTURE_RANGE_ATTACK_HMG1, + L4D1_ACT_GESTURE_RANGE_ATTACK_ML, + L4D1_ACT_GESTURE_RANGE_ATTACK_SMG1, + L4D1_ACT_GESTURE_RANGE_ATTACK_SMG1_LOW, + L4D1_ACT_GESTURE_RANGE_ATTACK_SMG2, + L4D1_ACT_GESTURE_RANGE_ATTACK_SHOTGUN, + L4D1_ACT_GESTURE_RANGE_ATTACK_PISTOL, + L4D1_ACT_GESTURE_RANGE_ATTACK_PISTOL_LOW, + L4D1_ACT_GESTURE_RANGE_ATTACK_SLAM, + L4D1_ACT_GESTURE_RANGE_ATTACK_TRIPWIRE, + L4D1_ACT_GESTURE_RANGE_ATTACK_THROW, + L4D1_ACT_GESTURE_RANGE_ATTACK_SNIPER_RIFLE, + L4D1_ACT_GESTURE_MELEE_ATTACK_SWING, + L4D1_ACT_IDLE_RIFLE, + L4D1_ACT_IDLE_SMG1, + L4D1_ACT_IDLE_ANGRY_SMG1, + L4D1_ACT_IDLE_PISTOL, + L4D1_ACT_IDLE_ANGRY_PISTOL, + L4D1_ACT_IDLE_ANGRY_SHOTGUN, + L4D1_ACT_IDLE_STEALTH_PISTOL, + L4D1_ACT_IDLE_PACKAGE, + L4D1_ACT_WALK_PACKAGE, + L4D1_ACT_IDLE_SUITCASE, + L4D1_ACT_WALK_SUITCASE, + L4D1_ACT_IDLE_SMG1_RELAXED, + L4D1_ACT_IDLE_SMG1_STIMULATED, + L4D1_ACT_WALK_RIFLE_RELAXED, + L4D1_ACT_RUN_RIFLE_RELAXED, + L4D1_ACT_WALK_RIFLE_STIMULATED, + L4D1_ACT_RUN_RIFLE_STIMULATED, + L4D1_ACT_IDLE_AIM_RIFLE_STIMULATED, + L4D1_ACT_WALK_AIM_RIFLE_STIMULATED, + L4D1_ACT_RUN_AIM_RIFLE_STIMULATED, + L4D1_ACT_IDLE_SHOTGUN_RELAXED, + L4D1_ACT_IDLE_SHOTGUN_STIMULATED, + L4D1_ACT_IDLE_SHOTGUN_AGITATED, + L4D1_ACT_WALK_ANGRY, + L4D1_ACT_POLICE_HARASS1, + L4D1_ACT_POLICE_HARASS2, + L4D1_ACT_IDLE_MANNEDGUN, + L4D1_ACT_IDLE_MELEE, + L4D1_ACT_IDLE_ANGRY_MELEE, + L4D1_ACT_IDLE_RPG_RELAXED, + L4D1_ACT_IDLE_RPG, + L4D1_ACT_IDLE_ANGRY_RPG, + L4D1_ACT_COVER_LOW_RPG, + L4D1_ACT_WALK_RPG, + L4D1_ACT_RUN_RPG, + L4D1_ACT_WALK_CROUCH_RPG, + L4D1_ACT_RUN_CROUCH_RPG, + L4D1_ACT_WALK_RPG_RELAXED, + L4D1_ACT_RUN_RPG_RELAXED, + L4D1_ACT_WALK_RIFLE, + L4D1_ACT_WALK_AIM_RIFLE, + L4D1_ACT_WALK_CROUCH_RIFLE, + L4D1_ACT_WALK_CROUCH_AIM_RIFLE, + L4D1_ACT_RUN_RIFLE, + L4D1_ACT_RUN_AIM_RIFLE, + L4D1_ACT_RUN_CROUCH_RIFLE, + L4D1_ACT_RUN_CROUCH_AIM_RIFLE, + L4D1_ACT_RUN_STEALTH_PISTOL, + L4D1_ACT_WALK_AIM_SHOTGUN, + L4D1_ACT_RUN_AIM_SHOTGUN, + L4D1_ACT_WALK_PISTOL, + L4D1_ACT_RUN_PISTOL, + L4D1_ACT_WALK_AIM_PISTOL, + L4D1_ACT_RUN_AIM_PISTOL, + L4D1_ACT_WALK_STEALTH_PISTOL, + L4D1_ACT_WALK_AIM_STEALTH_PISTOL, + L4D1_ACT_RUN_AIM_STEALTH_PISTOL, + L4D1_ACT_RELOAD_PISTOL, + L4D1_ACT_RELOAD_PISTOL_LOW, + L4D1_ACT_RELOAD_SMG1, + L4D1_ACT_RELOAD_SMG1_LOW, + L4D1_ACT_RELOAD_SHOTGUN, + L4D1_ACT_RELOAD_SHOTGUN_LOW, + L4D1_ACT_GESTURE_RELOAD, + L4D1_ACT_GESTURE_RELOAD_PISTOL, + L4D1_ACT_GESTURE_RELOAD_SMG1, + L4D1_ACT_GESTURE_RELOAD_SHOTGUN, + L4D1_ACT_BUSY_LEAN_LEFT, + L4D1_ACT_BUSY_LEAN_LEFT_ENTRY, + L4D1_ACT_BUSY_LEAN_LEFT_EXIT, + L4D1_ACT_BUSY_LEAN_BACK, + L4D1_ACT_BUSY_LEAN_BACK_ENTRY, + L4D1_ACT_BUSY_LEAN_BACK_EXIT, + L4D1_ACT_BUSY_SIT_GROUND, + L4D1_ACT_BUSY_SIT_GROUND_ENTRY, + L4D1_ACT_BUSY_SIT_GROUND_EXIT, + L4D1_ACT_BUSY_SIT_CHAIR, + L4D1_ACT_BUSY_SIT_CHAIR_ENTRY, + L4D1_ACT_BUSY_SIT_CHAIR_EXIT, + L4D1_ACT_BUSY_STAND, + L4D1_ACT_BUSY_QUEUE, + L4D1_ACT_DUCK_DODGE, + L4D1_ACT_DIE_BARNACLE_SWALLOW, + L4D1_ACT_GESTURE_BARNACLE_STRANGLE, + L4D1_ACT_PHYSCANNON_DETACH, + L4D1_ACT_PHYSCANNON_ANIMATE, + L4D1_ACT_PHYSCANNON_ANIMATE_PRE, + L4D1_ACT_PHYSCANNON_ANIMATE_POST, + L4D1_ACT_DIE_FRONTSIDE, + L4D1_ACT_DIE_RIGHTSIDE, + L4D1_ACT_DIE_BACKSIDE, + L4D1_ACT_DIE_LEFTSIDE, + L4D1_ACT_DIE_CROUCH_FRONTSIDE, + L4D1_ACT_DIE_CROUCH_RIGHTSIDE, + L4D1_ACT_DIE_CROUCH_BACKSIDE, + L4D1_ACT_DIE_CROUCH_LEFTSIDE, + L4D1_ACT_DIE_INCAP, + L4D1_ACT_OPEN_DOOR, + L4D1_ACT_DI_ALYX_ZOMBIE_MELEE, + L4D1_ACT_DI_ALYX_ZOMBIE_TORSO_MELEE, + L4D1_ACT_DI_ALYX_HEADCRAB_MELEE, + L4D1_ACT_DI_ALYX_ANTLION, + L4D1_ACT_DI_ALYX_ZOMBIE_SHOTGUN64, + L4D1_ACT_DI_ALYX_ZOMBIE_SHOTGUN26, + L4D1_ACT_READINESS_RELAXED_TO_STIMULATED, + L4D1_ACT_READINESS_RELAXED_TO_STIMULATED_WALK, + L4D1_ACT_READINESS_AGITATED_TO_STIMULATED, + L4D1_ACT_READINESS_STIMULATED_TO_RELAXED, + L4D1_ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED, + L4D1_ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED_WALK, + L4D1_ACT_READINESS_PISTOL_AGITATED_TO_STIMULATED, + L4D1_ACT_READINESS_PISTOL_STIMULATED_TO_RELAXED, + L4D1_ACT_IDLE_CARRY, + L4D1_ACT_WALK_CARRY, + L4D1_ACT_STARTDYING, + L4D1_ACT_DYINGLOOP, + L4D1_ACT_DYINGTODEAD, + L4D1_ACT_RIDE_MANNED_GUN, + L4D1_ACT_VM_SPRINT_ENTER, + L4D1_ACT_VM_SPRINT_IDLE, + L4D1_ACT_VM_SPRINT_LEAVE, + L4D1_ACT_FIRE_START, + L4D1_ACT_FIRE_LOOP, + L4D1_ACT_FIRE_END, + L4D1_ACT_CROUCHING_GRENADEIDLE, + L4D1_ACT_CROUCHING_GRENADEREADY, + L4D1_ACT_CROUCHING_PRIMARYATTACK, + L4D1_ACT_OVERLAY_GRENADEIDLE, + L4D1_ACT_OVERLAY_GRENADEREADY, + L4D1_ACT_OVERLAY_PRIMARYATTACK, + L4D1_ACT_OVERLAY_SHIELD_UP, + L4D1_ACT_OVERLAY_SHIELD_DOWN, + L4D1_ACT_OVERLAY_SHIELD_UP_IDLE, + L4D1_ACT_OVERLAY_SHIELD_ATTACK, + L4D1_ACT_OVERLAY_SHIELD_KNOCKBACK, + L4D1_ACT_SHIELD_UP, + L4D1_ACT_SHIELD_DOWN, + L4D1_ACT_SHIELD_UP_IDLE, + L4D1_ACT_SHIELD_ATTACK, + L4D1_ACT_SHIELD_KNOCKBACK, + L4D1_ACT_CROUCHING_SHIELD_UP, + L4D1_ACT_CROUCHING_SHIELD_DOWN, + L4D1_ACT_CROUCHING_SHIELD_UP_IDLE, + L4D1_ACT_CROUCHING_SHIELD_ATTACK, + L4D1_ACT_CROUCHING_SHIELD_KNOCKBACK, + L4D1_ACT_TURNRIGHT45, + L4D1_ACT_TURNLEFT45, + L4D1_ACT_TURN, + L4D1_ACT_OBJ_ASSEMBLING, + L4D1_ACT_OBJ_DISMANTLING, + L4D1_ACT_OBJ_STARTUP, + L4D1_ACT_OBJ_RUNNING, + L4D1_ACT_OBJ_IDLE, + L4D1_ACT_OBJ_PLACING, + L4D1_ACT_OBJ_DETERIORATING, + L4D1_ACT_OBJ_UPGRADING, + L4D1_ACT_DEPLOY, + L4D1_ACT_DEPLOY_IDLE, + L4D1_ACT_UNDEPLOY, + L4D1_ACT_GRENADE_ROLL, + L4D1_ACT_GRENADE_TOSS, + L4D1_ACT_HANDGRENADE_THROW1, + L4D1_ACT_HANDGRENADE_THROW2, + L4D1_ACT_HANDGRENADE_THROW3, + L4D1_ACT_SHOTGUN_IDLE_DEEP, + L4D1_ACT_SHOTGUN_IDLE4, + L4D1_ACT_GLOCK_SHOOTEMPTY, + L4D1_ACT_GLOCK_SHOOT_RELOAD, + L4D1_ACT_RPG_DRAW_UNLOADED, + L4D1_ACT_RPG_HOLSTER_UNLOADED, + L4D1_ACT_RPG_IDLE_UNLOADED, + L4D1_ACT_RPG_FIDGET_UNLOADED, + L4D1_ACT_CROSSBOW_DRAW_UNLOADED, + L4D1_ACT_CROSSBOW_IDLE_UNLOADED, + L4D1_ACT_CROSSBOW_FIDGET_UNLOADED, + L4D1_ACT_GAUSS_SPINUP, + L4D1_ACT_GAUSS_SPINCYCLE, + L4D1_ACT_TRIPMINE_GROUND, + L4D1_ACT_TRIPMINE_WORLD, + L4D1_ACT_VM_PRIMARYATTACK_SILENCED, + L4D1_ACT_VM_RELOAD_SILENCED, + L4D1_ACT_VM_DRYFIRE_SILENCED, + L4D1_ACT_VM_IDLE_SILENCED, + L4D1_ACT_VM_DRAW_SILENCED, + L4D1_ACT_VM_IDLE_EMPTY_LEFT, + L4D1_ACT_VM_DRYFIRE_LEFT, + L4D1_ACT_PLAYER_IDLE_FIRE, + L4D1_ACT_PLAYER_CROUCH_FIRE, + L4D1_ACT_PLAYER_CROUCH_WALK_FIRE, + L4D1_ACT_PLAYER_WALK_FIRE, + L4D1_ACT_PLAYER_RUN_FIRE, + L4D1_ACT_IDLETORUN, + L4D1_ACT_RUNTOIDLE, + L4D1_ACT_SPRINT, + L4D1_ACT_GET_DOWN_STAND, + L4D1_ACT_GET_UP_STAND, + L4D1_ACT_GET_DOWN_CROUCH, + L4D1_ACT_GET_UP_CROUCH, + L4D1_ACT_PRONE_FORWARD, + L4D1_ACT_PRONE_IDLE, + L4D1_ACT_DEEPIDLE1, + L4D1_ACT_DEEPIDLE2, + L4D1_ACT_DEEPIDLE3, + L4D1_ACT_DEEPIDLE4, + L4D1_ACT_VM_RELOAD_DEPLOYED, + L4D1_ACT_VM_RELOAD_IDLE, + L4D1_ACT_VM_DRAW_DEPLOYED, + L4D1_ACT_VM_DRAW_EMPTY, + L4D1_ACT_VM_PRIMARYATTACK_EMPTY, + L4D1_ACT_VM_RELOAD_EMPTY, + L4D1_ACT_VM_IDLE_EMPTY, + L4D1_ACT_VM_IDLE_DEPLOYED_EMPTY, + L4D1_ACT_VM_IDLE_8, + L4D1_ACT_VM_IDLE_7, + L4D1_ACT_VM_IDLE_6, + L4D1_ACT_VM_IDLE_5, + L4D1_ACT_VM_IDLE_4, + L4D1_ACT_VM_IDLE_3, + L4D1_ACT_VM_IDLE_2, + L4D1_ACT_VM_IDLE_1, + L4D1_ACT_VM_IDLE_DEPLOYED, + L4D1_ACT_VM_IDLE_DEPLOYED_8, + L4D1_ACT_VM_IDLE_DEPLOYED_7, + L4D1_ACT_VM_IDLE_DEPLOYED_6, + L4D1_ACT_VM_IDLE_DEPLOYED_5, + L4D1_ACT_VM_IDLE_DEPLOYED_4, + L4D1_ACT_VM_IDLE_DEPLOYED_3, + L4D1_ACT_VM_IDLE_DEPLOYED_2, + L4D1_ACT_VM_IDLE_DEPLOYED_1, + L4D1_ACT_VM_UNDEPLOY, + L4D1_ACT_VM_UNDEPLOY_8, + L4D1_ACT_VM_UNDEPLOY_7, + L4D1_ACT_VM_UNDEPLOY_6, + L4D1_ACT_VM_UNDEPLOY_5, + L4D1_ACT_VM_UNDEPLOY_4, + L4D1_ACT_VM_UNDEPLOY_3, + L4D1_ACT_VM_UNDEPLOY_2, + L4D1_ACT_VM_UNDEPLOY_1, + L4D1_ACT_VM_UNDEPLOY_EMPTY, + L4D1_ACT_VM_DEPLOY, + L4D1_ACT_VM_DEPLOY_8, + L4D1_ACT_VM_DEPLOY_7, + L4D1_ACT_VM_DEPLOY_6, + L4D1_ACT_VM_DEPLOY_5, + L4D1_ACT_VM_DEPLOY_4, + L4D1_ACT_VM_DEPLOY_3, + L4D1_ACT_VM_DEPLOY_2, + L4D1_ACT_VM_DEPLOY_1, + L4D1_ACT_VM_DEPLOY_EMPTY, + L4D1_ACT_VM_PRIMARYATTACK_8, + L4D1_ACT_VM_PRIMARYATTACK_7, + L4D1_ACT_VM_PRIMARYATTACK_6, + L4D1_ACT_VM_PRIMARYATTACK_5, + L4D1_ACT_VM_PRIMARYATTACK_4, + L4D1_ACT_VM_PRIMARYATTACK_3, + L4D1_ACT_VM_PRIMARYATTACK_2, + L4D1_ACT_VM_PRIMARYATTACK_1, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_8, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_7, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_6, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_5, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_4, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_3, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_2, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_1, + L4D1_ACT_VM_PRIMARYATTACK_DEPLOYED_EMPTY, + L4D1_ACT_DOD_DEPLOYED, + L4D1_ACT_DOD_PRONE_DEPLOYED, + L4D1_ACT_DOD_IDLE_ZOOMED, + L4D1_ACT_DOD_WALK_ZOOMED, + L4D1_ACT_DOD_CROUCH_ZOOMED, + L4D1_ACT_DOD_CROUCHWALK_ZOOMED, + L4D1_ACT_DOD_PRONE_ZOOMED, + L4D1_ACT_DOD_PRONE_FORWARD_ZOOMED, + L4D1_ACT_DOD_PRIMARYATTACK_DEPLOYED, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED, + L4D1_ACT_DOD_RELOAD_DEPLOYED, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE, + L4D1_ACT_DOD_SECONDARYATTACK_PRONE, + L4D1_ACT_DOD_RELOAD_CROUCH, + L4D1_ACT_DOD_RELOAD_PRONE, + L4D1_ACT_DOD_STAND_IDLE, + L4D1_ACT_DOD_STAND_AIM, + L4D1_ACT_DOD_CROUCH_IDLE, + L4D1_ACT_DOD_CROUCH_AIM, + L4D1_ACT_DOD_CROUCHWALK_IDLE, + L4D1_ACT_DOD_CROUCHWALK_AIM, + L4D1_ACT_DOD_WALK_IDLE, + L4D1_ACT_DOD_WALK_AIM, + L4D1_ACT_DOD_RUN_IDLE, + L4D1_ACT_DOD_RUN_AIM, + L4D1_ACT_DOD_STAND_AIM_PISTOL, + L4D1_ACT_DOD_CROUCH_AIM_PISTOL, + L4D1_ACT_DOD_CROUCHWALK_AIM_PISTOL, + L4D1_ACT_DOD_WALK_AIM_PISTOL, + L4D1_ACT_DOD_RUN_AIM_PISTOL, + L4D1_ACT_DOD_PRONE_AIM_PISTOL, + L4D1_ACT_DOD_STAND_IDLE_PISTOL, + L4D1_ACT_DOD_CROUCH_IDLE_PISTOL, + L4D1_ACT_DOD_CROUCHWALK_IDLE_PISTOL, + L4D1_ACT_DOD_WALK_IDLE_PISTOL, + L4D1_ACT_DOD_RUN_IDLE_PISTOL, + L4D1_ACT_DOD_SPRINT_IDLE_PISTOL, + L4D1_ACT_DOD_PRONEWALK_IDLE_PISTOL, + L4D1_ACT_DOD_STAND_AIM_C96, + L4D1_ACT_DOD_CROUCH_AIM_C96, + L4D1_ACT_DOD_CROUCHWALK_AIM_C96, + L4D1_ACT_DOD_WALK_AIM_C96, + L4D1_ACT_DOD_RUN_AIM_C96, + L4D1_ACT_DOD_PRONE_AIM_C96, + L4D1_ACT_DOD_STAND_IDLE_C96, + L4D1_ACT_DOD_CROUCH_IDLE_C96, + L4D1_ACT_DOD_CROUCHWALK_IDLE_C96, + L4D1_ACT_DOD_WALK_IDLE_C96, + L4D1_ACT_DOD_RUN_IDLE_C96, + L4D1_ACT_DOD_SPRINT_IDLE_C96, + L4D1_ACT_DOD_PRONEWALK_IDLE_C96, + L4D1_ACT_DOD_STAND_AIM_RIFLE, + L4D1_ACT_DOD_CROUCH_AIM_RIFLE, + L4D1_ACT_DOD_CROUCHWALK_AIM_RIFLE, + L4D1_ACT_DOD_WALK_AIM_RIFLE, + L4D1_ACT_DOD_RUN_AIM_RIFLE, + L4D1_ACT_DOD_PRONE_AIM_RIFLE, + L4D1_ACT_DOD_STAND_IDLE_RIFLE, + L4D1_ACT_DOD_CROUCH_IDLE_RIFLE, + L4D1_ACT_DOD_CROUCHWALK_IDLE_RIFLE, + L4D1_ACT_DOD_WALK_IDLE_RIFLE, + L4D1_ACT_DOD_RUN_IDLE_RIFLE, + L4D1_ACT_DOD_SPRINT_IDLE_RIFLE, + L4D1_ACT_DOD_PRONEWALK_IDLE_RIFLE, + L4D1_ACT_DOD_STAND_AIM_BOLT, + L4D1_ACT_DOD_CROUCH_AIM_BOLT, + L4D1_ACT_DOD_CROUCHWALK_AIM_BOLT, + L4D1_ACT_DOD_WALK_AIM_BOLT, + L4D1_ACT_DOD_RUN_AIM_BOLT, + L4D1_ACT_DOD_PRONE_AIM_BOLT, + L4D1_ACT_DOD_STAND_IDLE_BOLT, + L4D1_ACT_DOD_CROUCH_IDLE_BOLT, + L4D1_ACT_DOD_CROUCHWALK_IDLE_BOLT, + L4D1_ACT_DOD_WALK_IDLE_BOLT, + L4D1_ACT_DOD_RUN_IDLE_BOLT, + L4D1_ACT_DOD_SPRINT_IDLE_BOLT, + L4D1_ACT_DOD_PRONEWALK_IDLE_BOLT, + L4D1_ACT_DOD_STAND_AIM_TOMMY, + L4D1_ACT_DOD_CROUCH_AIM_TOMMY, + L4D1_ACT_DOD_CROUCHWALK_AIM_TOMMY, + L4D1_ACT_DOD_WALK_AIM_TOMMY, + L4D1_ACT_DOD_RUN_AIM_TOMMY, + L4D1_ACT_DOD_PRONE_AIM_TOMMY, + L4D1_ACT_DOD_STAND_IDLE_TOMMY, + L4D1_ACT_DOD_CROUCH_IDLE_TOMMY, + L4D1_ACT_DOD_CROUCHWALK_IDLE_TOMMY, + L4D1_ACT_DOD_WALK_IDLE_TOMMY, + L4D1_ACT_DOD_RUN_IDLE_TOMMY, + L4D1_ACT_DOD_SPRINT_IDLE_TOMMY, + L4D1_ACT_DOD_PRONEWALK_IDLE_TOMMY, + L4D1_ACT_DOD_STAND_AIM_MP40, + L4D1_ACT_DOD_CROUCH_AIM_MP40, + L4D1_ACT_DOD_CROUCHWALK_AIM_MP40, + L4D1_ACT_DOD_WALK_AIM_MP40, + L4D1_ACT_DOD_RUN_AIM_MP40, + L4D1_ACT_DOD_PRONE_AIM_MP40, + L4D1_ACT_DOD_STAND_IDLE_MP40, + L4D1_ACT_DOD_CROUCH_IDLE_MP40, + L4D1_ACT_DOD_CROUCHWALK_IDLE_MP40, + L4D1_ACT_DOD_WALK_IDLE_MP40, + L4D1_ACT_DOD_RUN_IDLE_MP40, + L4D1_ACT_DOD_SPRINT_IDLE_MP40, + L4D1_ACT_DOD_PRONEWALK_IDLE_MP40, + L4D1_ACT_DOD_STAND_AIM_MP44, + L4D1_ACT_DOD_CROUCH_AIM_MP44, + L4D1_ACT_DOD_CROUCHWALK_AIM_MP44, + L4D1_ACT_DOD_WALK_AIM_MP44, + L4D1_ACT_DOD_RUN_AIM_MP44, + L4D1_ACT_DOD_PRONE_AIM_MP44, + L4D1_ACT_DOD_STAND_IDLE_MP44, + L4D1_ACT_DOD_CROUCH_IDLE_MP44, + L4D1_ACT_DOD_CROUCHWALK_IDLE_MP44, + L4D1_ACT_DOD_WALK_IDLE_MP44, + L4D1_ACT_DOD_RUN_IDLE_MP44, + L4D1_ACT_DOD_SPRINT_IDLE_MP44, + L4D1_ACT_DOD_PRONEWALK_IDLE_MP44, + L4D1_ACT_DOD_STAND_AIM_GREASE, + L4D1_ACT_DOD_CROUCH_AIM_GREASE, + L4D1_ACT_DOD_CROUCHWALK_AIM_GREASE, + L4D1_ACT_DOD_WALK_AIM_GREASE, + L4D1_ACT_DOD_RUN_AIM_GREASE, + L4D1_ACT_DOD_PRONE_AIM_GREASE, + L4D1_ACT_DOD_STAND_IDLE_GREASE, + L4D1_ACT_DOD_CROUCH_IDLE_GREASE, + L4D1_ACT_DOD_CROUCHWALK_IDLE_GREASE, + L4D1_ACT_DOD_WALK_IDLE_GREASE, + L4D1_ACT_DOD_RUN_IDLE_GREASE, + L4D1_ACT_DOD_SPRINT_IDLE_GREASE, + L4D1_ACT_DOD_PRONEWALK_IDLE_GREASE, + L4D1_ACT_DOD_STAND_AIM_MG, + L4D1_ACT_DOD_CROUCH_AIM_MG, + L4D1_ACT_DOD_CROUCHWALK_AIM_MG, + L4D1_ACT_DOD_WALK_AIM_MG, + L4D1_ACT_DOD_RUN_AIM_MG, + L4D1_ACT_DOD_PRONE_AIM_MG, + L4D1_ACT_DOD_STAND_IDLE_MG, + L4D1_ACT_DOD_CROUCH_IDLE_MG, + L4D1_ACT_DOD_CROUCHWALK_IDLE_MG, + L4D1_ACT_DOD_WALK_IDLE_MG, + L4D1_ACT_DOD_RUN_IDLE_MG, + L4D1_ACT_DOD_SPRINT_IDLE_MG, + L4D1_ACT_DOD_PRONEWALK_IDLE_MG, + L4D1_ACT_DOD_STAND_AIM_30CAL, + L4D1_ACT_DOD_CROUCH_AIM_30CAL, + L4D1_ACT_DOD_CROUCHWALK_AIM_30CAL, + L4D1_ACT_DOD_WALK_AIM_30CAL, + L4D1_ACT_DOD_RUN_AIM_30CAL, + L4D1_ACT_DOD_PRONE_AIM_30CAL, + L4D1_ACT_DOD_STAND_IDLE_30CAL, + L4D1_ACT_DOD_CROUCH_IDLE_30CAL, + L4D1_ACT_DOD_CROUCHWALK_IDLE_30CAL, + L4D1_ACT_DOD_WALK_IDLE_30CAL, + L4D1_ACT_DOD_RUN_IDLE_30CAL, + L4D1_ACT_DOD_SPRINT_IDLE_30CAL, + L4D1_ACT_DOD_PRONEWALK_IDLE_30CAL, + L4D1_ACT_DOD_STAND_AIM_GREN_FRAG, + L4D1_ACT_DOD_CROUCH_AIM_GREN_FRAG, + L4D1_ACT_DOD_CROUCHWALK_AIM_GREN_FRAG, + L4D1_ACT_DOD_WALK_AIM_GREN_FRAG, + L4D1_ACT_DOD_RUN_AIM_GREN_FRAG, + L4D1_ACT_DOD_PRONE_AIM_GREN_FRAG, + L4D1_ACT_DOD_SPRINT_AIM_GREN_FRAG, + L4D1_ACT_DOD_PRONEWALK_AIM_GREN_FRAG, + L4D1_ACT_DOD_STAND_AIM_GREN_STICK, + L4D1_ACT_DOD_CROUCH_AIM_GREN_STICK, + L4D1_ACT_DOD_CROUCHWALK_AIM_GREN_STICK, + L4D1_ACT_DOD_WALK_AIM_GREN_STICK, + L4D1_ACT_DOD_RUN_AIM_GREN_STICK, + L4D1_ACT_DOD_PRONE_AIM_GREN_STICK, + L4D1_ACT_DOD_SPRINT_AIM_GREN_STICK, + L4D1_ACT_DOD_PRONEWALK_AIM_GREN_STICK, + L4D1_ACT_DOD_STAND_AIM_KNIFE, + L4D1_ACT_DOD_CROUCH_AIM_KNIFE, + L4D1_ACT_DOD_CROUCHWALK_AIM_KNIFE, + L4D1_ACT_DOD_WALK_AIM_KNIFE, + L4D1_ACT_DOD_RUN_AIM_KNIFE, + L4D1_ACT_DOD_PRONE_AIM_KNIFE, + L4D1_ACT_DOD_SPRINT_AIM_KNIFE, + L4D1_ACT_DOD_PRONEWALK_AIM_KNIFE, + L4D1_ACT_DOD_STAND_AIM_SPADE, + L4D1_ACT_DOD_CROUCH_AIM_SPADE, + L4D1_ACT_DOD_CROUCHWALK_AIM_SPADE, + L4D1_ACT_DOD_WALK_AIM_SPADE, + L4D1_ACT_DOD_RUN_AIM_SPADE, + L4D1_ACT_DOD_PRONE_AIM_SPADE, + L4D1_ACT_DOD_SPRINT_AIM_SPADE, + L4D1_ACT_DOD_PRONEWALK_AIM_SPADE, + L4D1_ACT_DOD_STAND_AIM_BAZOOKA, + L4D1_ACT_DOD_CROUCH_AIM_BAZOOKA, + L4D1_ACT_DOD_CROUCHWALK_AIM_BAZOOKA, + L4D1_ACT_DOD_WALK_AIM_BAZOOKA, + L4D1_ACT_DOD_RUN_AIM_BAZOOKA, + L4D1_ACT_DOD_PRONE_AIM_BAZOOKA, + L4D1_ACT_DOD_STAND_IDLE_BAZOOKA, + L4D1_ACT_DOD_CROUCH_IDLE_BAZOOKA, + L4D1_ACT_DOD_CROUCHWALK_IDLE_BAZOOKA, + L4D1_ACT_DOD_WALK_IDLE_BAZOOKA, + L4D1_ACT_DOD_RUN_IDLE_BAZOOKA, + L4D1_ACT_DOD_SPRINT_IDLE_BAZOOKA, + L4D1_ACT_DOD_PRONEWALK_IDLE_BAZOOKA, + L4D1_ACT_DOD_STAND_AIM_PSCHRECK, + L4D1_ACT_DOD_CROUCH_AIM_PSCHRECK, + L4D1_ACT_DOD_CROUCHWALK_AIM_PSCHRECK, + L4D1_ACT_DOD_WALK_AIM_PSCHRECK, + L4D1_ACT_DOD_RUN_AIM_PSCHRECK, + L4D1_ACT_DOD_PRONE_AIM_PSCHRECK, + L4D1_ACT_DOD_STAND_IDLE_PSCHRECK, + L4D1_ACT_DOD_CROUCH_IDLE_PSCHRECK, + L4D1_ACT_DOD_CROUCHWALK_IDLE_PSCHRECK, + L4D1_ACT_DOD_WALK_IDLE_PSCHRECK, + L4D1_ACT_DOD_RUN_IDLE_PSCHRECK, + L4D1_ACT_DOD_SPRINT_IDLE_PSCHRECK, + L4D1_ACT_DOD_PRONEWALK_IDLE_PSCHRECK, + L4D1_ACT_DOD_STAND_AIM_BAR, + L4D1_ACT_DOD_CROUCH_AIM_BAR, + L4D1_ACT_DOD_CROUCHWALK_AIM_BAR, + L4D1_ACT_DOD_WALK_AIM_BAR, + L4D1_ACT_DOD_RUN_AIM_BAR, + L4D1_ACT_DOD_PRONE_AIM_BAR, + L4D1_ACT_DOD_STAND_IDLE_BAR, + L4D1_ACT_DOD_CROUCH_IDLE_BAR, + L4D1_ACT_DOD_CROUCHWALK_IDLE_BAR, + L4D1_ACT_DOD_WALK_IDLE_BAR, + L4D1_ACT_DOD_RUN_IDLE_BAR, + L4D1_ACT_DOD_SPRINT_IDLE_BAR, + L4D1_ACT_DOD_PRONEWALK_IDLE_BAR, + L4D1_ACT_DOD_STAND_ZOOM_RIFLE, + L4D1_ACT_DOD_CROUCH_ZOOM_RIFLE, + L4D1_ACT_DOD_CROUCHWALK_ZOOM_RIFLE, + L4D1_ACT_DOD_WALK_ZOOM_RIFLE, + L4D1_ACT_DOD_RUN_ZOOM_RIFLE, + L4D1_ACT_DOD_PRONE_ZOOM_RIFLE, + L4D1_ACT_DOD_STAND_ZOOM_BOLT, + L4D1_ACT_DOD_CROUCH_ZOOM_BOLT, + L4D1_ACT_DOD_CROUCHWALK_ZOOM_BOLT, + L4D1_ACT_DOD_WALK_ZOOM_BOLT, + L4D1_ACT_DOD_RUN_ZOOM_BOLT, + L4D1_ACT_DOD_PRONE_ZOOM_BOLT, + L4D1_ACT_DOD_STAND_ZOOM_BAZOOKA, + L4D1_ACT_DOD_CROUCH_ZOOM_BAZOOKA, + L4D1_ACT_DOD_CROUCHWALK_ZOOM_BAZOOKA, + L4D1_ACT_DOD_WALK_ZOOM_BAZOOKA, + L4D1_ACT_DOD_RUN_ZOOM_BAZOOKA, + L4D1_ACT_DOD_PRONE_ZOOM_BAZOOKA, + L4D1_ACT_DOD_STAND_ZOOM_PSCHRECK, + L4D1_ACT_DOD_CROUCH_ZOOM_PSCHRECK, + L4D1_ACT_DOD_CROUCHWALK_ZOOM_PSCHRECK, + L4D1_ACT_DOD_WALK_ZOOM_PSCHRECK, + L4D1_ACT_DOD_RUN_ZOOM_PSCHRECK, + L4D1_ACT_DOD_PRONE_ZOOM_PSCHRECK, + L4D1_ACT_DOD_DEPLOY_RIFLE, + L4D1_ACT_DOD_DEPLOY_TOMMY, + L4D1_ACT_DOD_DEPLOY_MG, + L4D1_ACT_DOD_DEPLOY_30CAL, + L4D1_ACT_DOD_PRONE_DEPLOY_RIFLE, + L4D1_ACT_DOD_PRONE_DEPLOY_TOMMY, + L4D1_ACT_DOD_PRONE_DEPLOY_MG, + L4D1_ACT_DOD_PRONE_DEPLOY_30CAL, + L4D1_ACT_DOD_PRIMARYATTACK_RIFLE, + L4D1_ACT_DOD_SECONDARYATTACK_RIFLE, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_RIFLE, + L4D1_ACT_DOD_SECONDARYATTACK_PRONE_RIFLE, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_RIFLE, + L4D1_ACT_DOD_PRIMARYATTACK_DEPLOYED_RIFLE, + L4D1_ACT_DOD_PRIMARYATTACK_BOLT, + L4D1_ACT_DOD_SECONDARYATTACK_BOLT, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_BOLT, + L4D1_ACT_DOD_SECONDARYATTACK_PRONE_BOLT, + L4D1_ACT_DOD_PRIMARYATTACK_TOMMY, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_TOMMY, + L4D1_ACT_DOD_SECONDARYATTACK_TOMMY, + L4D1_ACT_DOD_SECONDARYATTACK_PRONE_TOMMY, + L4D1_ACT_DOD_PRIMARYATTACK_MP40, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_MP40, + L4D1_ACT_DOD_SECONDARYATTACK_MP40, + L4D1_ACT_DOD_SECONDARYATTACK_PRONE_MP40, + L4D1_ACT_DOD_PRIMARYATTACK_MP44, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_MP44, + L4D1_ACT_DOD_PRIMARYATTACK_GREASE, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_GREASE, + L4D1_ACT_DOD_PRIMARYATTACK_PISTOL, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_PISTOL, + L4D1_ACT_DOD_PRIMARYATTACK_C96, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_C96, + L4D1_ACT_DOD_PRIMARYATTACK_MG, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_MG, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_MG, + L4D1_ACT_DOD_PRIMARYATTACK_DEPLOYED_MG, + L4D1_ACT_DOD_PRIMARYATTACK_30CAL, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_30CAL, + L4D1_ACT_DOD_PRIMARYATTACK_DEPLOYED_30CAL, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_30CAL, + L4D1_ACT_DOD_PRIMARYATTACK_GREN_FRAG, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_GREN_FRAG, + L4D1_ACT_DOD_PRIMARYATTACK_GREN_STICK, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_GREN_STICK, + L4D1_ACT_DOD_PRIMARYATTACK_KNIFE, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_KNIFE, + L4D1_ACT_DOD_PRIMARYATTACK_SPADE, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_SPADE, + L4D1_ACT_DOD_PRIMARYATTACK_BAZOOKA, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_BAZOOKA, + L4D1_ACT_DOD_PRIMARYATTACK_PSCHRECK, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_PSCHRECK, + L4D1_ACT_DOD_PRIMARYATTACK_BAR, + L4D1_ACT_DOD_PRIMARYATTACK_PRONE_BAR, + L4D1_ACT_DOD_RELOAD_GARAND, + L4D1_ACT_DOD_RELOAD_K43, + L4D1_ACT_DOD_RELOAD_BAR, + L4D1_ACT_DOD_RELOAD_MP40, + L4D1_ACT_DOD_RELOAD_MP44, + L4D1_ACT_DOD_RELOAD_BOLT, + L4D1_ACT_DOD_RELOAD_M1CARBINE, + L4D1_ACT_DOD_RELOAD_TOMMY, + L4D1_ACT_DOD_RELOAD_GREASEGUN, + L4D1_ACT_DOD_RELOAD_PISTOL, + L4D1_ACT_DOD_RELOAD_FG42, + L4D1_ACT_DOD_RELOAD_RIFLE, + L4D1_ACT_DOD_RELOAD_RIFLEGRENADE, + L4D1_ACT_DOD_RELOAD_C96, + L4D1_ACT_DOD_RELOAD_CROUCH_BAR, + L4D1_ACT_DOD_RELOAD_CROUCH_RIFLE, + L4D1_ACT_DOD_RELOAD_CROUCH_RIFLEGRENADE, + L4D1_ACT_DOD_RELOAD_CROUCH_BOLT, + L4D1_ACT_DOD_RELOAD_CROUCH_MP44, + L4D1_ACT_DOD_RELOAD_CROUCH_MP40, + L4D1_ACT_DOD_RELOAD_CROUCH_TOMMY, + L4D1_ACT_DOD_RELOAD_CROUCH_BAZOOKA, + L4D1_ACT_DOD_RELOAD_CROUCH_PSCHRECK, + L4D1_ACT_DOD_RELOAD_CROUCH_PISTOL, + L4D1_ACT_DOD_RELOAD_CROUCH_M1CARBINE, + L4D1_ACT_DOD_RELOAD_CROUCH_C96, + L4D1_ACT_DOD_RELOAD_BAZOOKA, + L4D1_ACT_DOD_ZOOMLOAD_BAZOOKA, + L4D1_ACT_DOD_RELOAD_PSCHRECK, + L4D1_ACT_DOD_ZOOMLOAD_PSCHRECK, + L4D1_ACT_DOD_RELOAD_DEPLOYED_FG42, + L4D1_ACT_DOD_RELOAD_DEPLOYED_30CAL, + L4D1_ACT_DOD_RELOAD_DEPLOYED_MG, + L4D1_ACT_DOD_RELOAD_DEPLOYED_MG34, + L4D1_ACT_DOD_RELOAD_DEPLOYED_BAR, + L4D1_ACT_DOD_RELOAD_PRONE_PISTOL, + L4D1_ACT_DOD_RELOAD_PRONE_GARAND, + L4D1_ACT_DOD_RELOAD_PRONE_M1CARBINE, + L4D1_ACT_DOD_RELOAD_PRONE_BOLT, + L4D1_ACT_DOD_RELOAD_PRONE_K43, + L4D1_ACT_DOD_RELOAD_PRONE_MP40, + L4D1_ACT_DOD_RELOAD_PRONE_MP44, + L4D1_ACT_DOD_RELOAD_PRONE_BAR, + L4D1_ACT_DOD_RELOAD_PRONE_GREASEGUN, + L4D1_ACT_DOD_RELOAD_PRONE_TOMMY, + L4D1_ACT_DOD_RELOAD_PRONE_FG42, + L4D1_ACT_DOD_RELOAD_PRONE_RIFLE, + L4D1_ACT_DOD_RELOAD_PRONE_RIFLEGRENADE, + L4D1_ACT_DOD_RELOAD_PRONE_C96, + L4D1_ACT_DOD_RELOAD_PRONE_BAZOOKA, + L4D1_ACT_DOD_ZOOMLOAD_PRONE_BAZOOKA, + L4D1_ACT_DOD_RELOAD_PRONE_PSCHRECK, + L4D1_ACT_DOD_ZOOMLOAD_PRONE_PSCHRECK, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED_BAR, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED_FG42, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED_30CAL, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED_MG, + L4D1_ACT_DOD_RELOAD_PRONE_DEPLOYED_MG34, + L4D1_ACT_DOD_PRONE_ZOOM_FORWARD_RIFLE, + L4D1_ACT_DOD_PRONE_ZOOM_FORWARD_BOLT, + L4D1_ACT_DOD_PRONE_ZOOM_FORWARD_BAZOOKA, + L4D1_ACT_DOD_PRONE_ZOOM_FORWARD_PSCHRECK, + L4D1_ACT_DOD_PRIMARYATTACK_CROUCH, + L4D1_ACT_DOD_PRIMARYATTACK_CROUCH_SPADE, + L4D1_ACT_DOD_PRIMARYATTACK_CROUCH_KNIFE, + L4D1_ACT_DOD_PRIMARYATTACK_CROUCH_GREN_FRAG, + L4D1_ACT_DOD_PRIMARYATTACK_CROUCH_GREN_STICK, + L4D1_ACT_DOD_SECONDARYATTACK_CROUCH, + L4D1_ACT_DOD_SECONDARYATTACK_CROUCH_TOMMY, + L4D1_ACT_DOD_SECONDARYATTACK_CROUCH_MP40, + L4D1_ACT_DOD_HS_IDLE, + L4D1_ACT_DOD_HS_CROUCH, + L4D1_ACT_DOD_HS_IDLE_30CAL, + L4D1_ACT_DOD_HS_IDLE_BAZOOKA, + L4D1_ACT_DOD_HS_IDLE_PSCHRECK, + L4D1_ACT_DOD_HS_IDLE_KNIFE, + L4D1_ACT_DOD_HS_IDLE_MG42, + L4D1_ACT_DOD_HS_IDLE_PISTOL, + L4D1_ACT_DOD_HS_IDLE_STICKGRENADE, + L4D1_ACT_DOD_HS_IDLE_TOMMY, + L4D1_ACT_DOD_HS_IDLE_MP44, + L4D1_ACT_DOD_HS_IDLE_K98, + L4D1_ACT_DOD_HS_CROUCH_30CAL, + L4D1_ACT_DOD_HS_CROUCH_BAZOOKA, + L4D1_ACT_DOD_HS_CROUCH_PSCHRECK, + L4D1_ACT_DOD_HS_CROUCH_KNIFE, + L4D1_ACT_DOD_HS_CROUCH_MG42, + L4D1_ACT_DOD_HS_CROUCH_PISTOL, + L4D1_ACT_DOD_HS_CROUCH_STICKGRENADE, + L4D1_ACT_DOD_HS_CROUCH_TOMMY, + L4D1_ACT_DOD_HS_CROUCH_MP44, + L4D1_ACT_DOD_HS_CROUCH_K98, + L4D1_ACT_DOD_STAND_IDLE_TNT, + L4D1_ACT_DOD_CROUCH_IDLE_TNT, + L4D1_ACT_DOD_CROUCHWALK_IDLE_TNT, + L4D1_ACT_DOD_WALK_IDLE_TNT, + L4D1_ACT_DOD_RUN_IDLE_TNT, + L4D1_ACT_DOD_SPRINT_IDLE_TNT, + L4D1_ACT_DOD_PRONEWALK_IDLE_TNT, + L4D1_ACT_DOD_PLANT_TNT, + L4D1_ACT_DOD_DEFUSE_TNT, + L4D1_ACT_HL2MP_IDLE, + L4D1_ACT_HL2MP_RUN, + L4D1_ACT_HL2MP_IDLE_CROUCH, + L4D1_ACT_HL2MP_WALK_CROUCH, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK, + L4D1_ACT_HL2MP_GESTURE_RELOAD, + L4D1_ACT_HL2MP_JUMP, + L4D1_ACT_HL2MP_IDLE_PISTOL, + L4D1_ACT_HL2MP_RUN_PISTOL, + L4D1_ACT_HL2MP_IDLE_CROUCH_PISTOL, + L4D1_ACT_HL2MP_WALK_CROUCH_PISTOL, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL, + L4D1_ACT_HL2MP_GESTURE_RELOAD_PISTOL, + L4D1_ACT_HL2MP_JUMP_PISTOL, + L4D1_ACT_HL2MP_IDLE_SMG1, + L4D1_ACT_HL2MP_RUN_SMG1, + L4D1_ACT_HL2MP_IDLE_CROUCH_SMG1, + L4D1_ACT_HL2MP_WALK_CROUCH_SMG1, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_SMG1, + L4D1_ACT_HL2MP_GESTURE_RELOAD_SMG1, + L4D1_ACT_HL2MP_JUMP_SMG1, + L4D1_ACT_HL2MP_IDLE_AR2, + L4D1_ACT_HL2MP_RUN_AR2, + L4D1_ACT_HL2MP_IDLE_CROUCH_AR2, + L4D1_ACT_HL2MP_WALK_CROUCH_AR2, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_AR2, + L4D1_ACT_HL2MP_GESTURE_RELOAD_AR2, + L4D1_ACT_HL2MP_JUMP_AR2, + L4D1_ACT_HL2MP_IDLE_SHOTGUN, + L4D1_ACT_HL2MP_RUN_SHOTGUN, + L4D1_ACT_HL2MP_IDLE_CROUCH_SHOTGUN, + L4D1_ACT_HL2MP_WALK_CROUCH_SHOTGUN, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_SHOTGUN, + L4D1_ACT_HL2MP_GESTURE_RELOAD_SHOTGUN, + L4D1_ACT_HL2MP_JUMP_SHOTGUN, + L4D1_ACT_HL2MP_IDLE_RPG, + L4D1_ACT_HL2MP_RUN_RPG, + L4D1_ACT_HL2MP_IDLE_CROUCH_RPG, + L4D1_ACT_HL2MP_WALK_CROUCH_RPG, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_RPG, + L4D1_ACT_HL2MP_GESTURE_RELOAD_RPG, + L4D1_ACT_HL2MP_JUMP_RPG, + L4D1_ACT_HL2MP_IDLE_GRENADE, + L4D1_ACT_HL2MP_RUN_GRENADE, + L4D1_ACT_HL2MP_IDLE_CROUCH_GRENADE, + L4D1_ACT_HL2MP_WALK_CROUCH_GRENADE, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_GRENADE, + L4D1_ACT_HL2MP_GESTURE_RELOAD_GRENADE, + L4D1_ACT_HL2MP_JUMP_GRENADE, + L4D1_ACT_HL2MP_IDLE_PHYSGUN, + L4D1_ACT_HL2MP_RUN_PHYSGUN, + L4D1_ACT_HL2MP_IDLE_CROUCH_PHYSGUN, + L4D1_ACT_HL2MP_WALK_CROUCH_PHYSGUN, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_PHYSGUN, + L4D1_ACT_HL2MP_GESTURE_RELOAD_PHYSGUN, + L4D1_ACT_HL2MP_JUMP_PHYSGUN, + L4D1_ACT_HL2MP_IDLE_CROSSBOW, + L4D1_ACT_HL2MP_RUN_CROSSBOW, + L4D1_ACT_HL2MP_IDLE_CROUCH_CROSSBOW, + L4D1_ACT_HL2MP_WALK_CROUCH_CROSSBOW, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_CROSSBOW, + L4D1_ACT_HL2MP_GESTURE_RELOAD_CROSSBOW, + L4D1_ACT_HL2MP_JUMP_CROSSBOW, + L4D1_ACT_HL2MP_IDLE_MELEE, + L4D1_ACT_HL2MP_RUN_MELEE, + L4D1_ACT_HL2MP_IDLE_CROUCH_MELEE, + L4D1_ACT_HL2MP_WALK_CROUCH_MELEE, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_MELEE, + L4D1_ACT_HL2MP_GESTURE_RELOAD_MELEE, + L4D1_ACT_HL2MP_JUMP_MELEE, + L4D1_ACT_HL2MP_IDLE_SLAM, + L4D1_ACT_HL2MP_RUN_SLAM, + L4D1_ACT_HL2MP_IDLE_CROUCH_SLAM, + L4D1_ACT_HL2MP_WALK_CROUCH_SLAM, + L4D1_ACT_HL2MP_GESTURE_RANGE_ATTACK_SLAM, + L4D1_ACT_HL2MP_GESTURE_RELOAD_SLAM, + L4D1_ACT_HL2MP_JUMP_SLAM, + L4D1_ACT_VM_SHRIEK, + L4D1_ACT_VM_VOMIT, + L4D1_ACT_VM_COUGH, + L4D1_ACT_VM_LUNGE, + L4D1_ACT_IDLE_INJURED, + L4D1_ACT_IDLE_INCAP, + L4D1_ACT_WALK_INJURED, + L4D1_ACT_RUN_INJURED, + L4D1_ACT_RUN_PULLED, + L4D1_ACT_IDLE_CALM, + L4D1_ACT_WALK_CALM, + L4D1_ACT_RUN_CALM, + L4D1_ACT_JUMP_SHOTGUN, + L4D1_ACT_JUMP_RIFLE, + L4D1_ACT_JUMP_SMG, + L4D1_ACT_JUMP_PISTOL, + L4D1_ACT_JUMP_DUAL_PISTOL, + L4D1_ACT_JUMP_ITEM, + L4D1_ACT_TERROR_HIT_BY_TANKPUNCH, + L4D1_ACT_TERROR_IDLE_FALL_FROM_TANKPUNCH, + L4D1_ACT_TERROR_TANKPUNCH_LAND, + L4D1_ACT_TERROR_HEAL_SELF, + L4D1_ACT_TERROR_HEAL_FRIEND, + L4D1_ACT_TERROR_HEAL_INCAPACITATED, + L4D1_ACT_TERROR_CROUCH_HEAL_SELF, + L4D1_ACT_TERROR_CROUCH_HEAL_FRIEND, + L4D1_ACT_TERROR_CROUCH_HEAL_INCAPACITATED, + L4D1_ACT_TERROR_HEAL_INCAPACITATED_ABOVE, + L4D1_ACT_TERROR_CROUCH_HEAL_INCAPACITATED_ABOVE, + L4D1_ACT_TERROR_USE_PILLS, + L4D1_ACT_TERROR_IDLE_NEUTRAL, + L4D1_ACT_TERROR_IDLE_ALERT, + L4D1_ACT_TERROR_IDLE_INTENSE, + L4D1_ACT_TERROR_IDLE_ALERT_INJURED_AHEAD, + L4D1_ACT_TERROR_IDLE_ALERT_AHEAD, + L4D1_ACT_TERROR_IDLE_ALERT_INJURED_BEHIND, + L4D1_ACT_TERROR_IDLE_ALERT_BEHIND, + L4D1_ACT_TERROR_IDLE_ALERT_INJURED_LEFT, + L4D1_ACT_TERROR_IDLE_ALERT_LEFT, + L4D1_ACT_TERROR_IDLE_ALERT_INJURED_RIGHT, + L4D1_ACT_TERROR_IDLE_ALERT_RIGHT, + L4D1_ACT_TERROR_IDLE_ACQUIRE, + L4D1_ACT_TERROR_LEAN_FORWARD_IDLE, + L4D1_ACT_TERROR_LEAN_BACKWARD_IDLE, + L4D1_ACT_TERROR_LEAN_LEFTWARD_IDLE, + L4D1_ACT_TERROR_LEAN_RIGHTWARD_IDLE, + L4D1_ACT_TERROR_FIDGET, + L4D1_ACT_TERROR_NEUTRAL_TO_ALERT, + L4D1_ACT_TERROR_ALERT_TO_NEUTRAL, + L4D1_ACT_TERROR_FACE_LEFT_NEUTRAL, + L4D1_ACT_TERROR_FACE_LEFT_ALERT, + L4D1_ACT_TERROR_FACE_LEFT_INTENSE, + L4D1_ACT_TERROR_FACE_RIGHT_NEUTRAL, + L4D1_ACT_TERROR_FACE_RIGHT_ALERT, + L4D1_ACT_TERROR_FACE_RIGHT_INTENSE, + L4D1_ACT_TERROR_ABOUT_FACE_NEUTRAL, + L4D1_ACT_TERROR_ABOUT_FACE_ALERT, + L4D1_ACT_TERROR_ABOUT_FACE_INTENSE, + L4D1_ACT_TERROR_WALK_NEUTRAL, + L4D1_ACT_TERROR_WALK_ALERT, + L4D1_ACT_TERROR_WALK_INTENSE, + L4D1_ACT_TERROR_RUN_NEUTRAL, + L4D1_ACT_TERROR_RUN_ALERT, + L4D1_ACT_TERROR_RUN_INTENSE, + L4D1_ACT_TERROR_RUN_ON_FIRE_INTENSE, + L4D1_ACT_TERROR_RUN_INTENSE_TO_STAND_ALERT, + L4D1_ACT_TERROR_CROUCH_IDLE_NEUTRAL, + L4D1_ACT_TERROR_CROUCH_IDLE_ALERT, + L4D1_ACT_TERROR_CROUCH_IDLE_INTENSE, + L4D1_ACT_TERROR_CROUCH_WALK_NEUTRAL, + L4D1_ACT_TERROR_CROUCH_WALK_ALERT, + L4D1_ACT_TERROR_CROUCH_WALK_INTENSE, + L4D1_ACT_TERROR_CROUCH_RUN_NEUTRAL, + L4D1_ACT_TERROR_CROUCH_RUN_ALERT, + L4D1_ACT_TERROR_CROUCH_RUN_INTENSE, + L4D1_ACT_TERROR_IDLE_ON_FIRE, + L4D1_ACT_TERROR_WALK_ON_FIRE, + L4D1_ACT_TERROR_RUN_ON_FIRE, + L4D1_ACT_TERROR_ATTACK, + L4D1_ACT_TERROR_ATTACK_CONTINUOUSLY, + L4D1_ACT_TERROR_ATTACK_LOW, + L4D1_ACT_TERROR_ATTACK_LOW_CONTINUOUSLY, + L4D1_ACT_TERROR_ATTACK_DOOR, + L4D1_ACT_TERROR_ATTACK_DOOR_CONTINUOUSLY, + L4D1_ACT_TERROR_UNABLE_TO_REACH_TARGET, + L4D1_ACT_TERROR_REACH_THROUGH_DOOR, + L4D1_ACT_TERROR_SHOVED_FORWARD, + L4D1_ACT_TERROR_SHOVED_BACKWARD, + L4D1_ACT_TERROR_SHOVED_LEFTWARD, + L4D1_ACT_TERROR_SHOVED_RIGHTWARD, + L4D1_ACT_TERROR_SHOVED_BACKWARD_INTO_WALL, + L4D1_ACT_TERROR_SHOVED_FORWARD_INTO_WALL, + L4D1_ACT_TERROR_SHOVED_LEFTWARD_INTO_WALL, + L4D1_ACT_TERROR_SHOVED_RIGHTWARD_INTO_WALL, + L4D1_ACT_TERROR_SHOVED_BACKWARD_FROM_SIT, + L4D1_ACT_TERROR_SHOVED_RIGHTWARD_FROM_SIT, + L4D1_ACT_TERROR_SHOVED_LEFTWARD_FROM_SIT, + L4D1_ACT_TERROR_TUGGED_FORWARD, + L4D1_ACT_TERROR_TUGGED_BACKWARD, + L4D1_ACT_TERROR_TUGGED_LEFTWARD, + L4D1_ACT_TERROR_TUGGED_RIGHTWARD, + L4D1_ACT_TERROR_SIT_IDLE, + L4D1_ACT_TERROR_SIT_FROM_STAND, + L4D1_ACT_TERROR_SIT_TO_STAND, + L4D1_ACT_TERROR_SIT_TO_STAND_ALERT, + L4D1_ACT_TERROR_SIT_TO_LIE, + L4D1_ACT_TERROR_LIE_IDLE, + L4D1_ACT_TERROR_LIE_FROM_STAND, + L4D1_ACT_TERROR_LIE_TO_STAND, + L4D1_ACT_TERROR_LIE_TO_STAND_ALERT, + L4D1_ACT_TERROR_LIE_TO_SIT, + L4D1_ACT_TERROR_JUMP, + L4D1_ACT_TERROR_JUMP_UP_TO_LEDGE, + L4D1_ACT_TERROR_JUMP_DOWN_FROM_LEDGE, + L4D1_ACT_TERROR_JUMP_OVER_GAP, + L4D1_ACT_TERROR_JUMP_LANDING, + L4D1_ACT_TERROR_JUMP_LANDING_HARD, + L4D1_ACT_TERROR_JUMP_LANDING_NEUTRAL, + L4D1_ACT_TERROR_JUMP_LANDING_HARD_NEUTRAL, + L4D1_ACT_TERROR_FALL, + L4D1_ACT_TERROR_DIE_FROM_STAND, + L4D1_ACT_TERROR_DIE_FROM_CROUCH, + L4D1_ACT_TERROR_DIE_WHILE_RUNNING, + L4D1_ACT_TERROR_DIE_BACKWARD_FROM_SHOTGUN, + L4D1_ACT_TERROR_DIE_FORWARD_FROM_SHOTGUN, + L4D1_ACT_TERROR_DIE_LEFTWARD_FROM_SHOTGUN, + L4D1_ACT_TERROR_DIE_RIGHTWARD_FROM_SHOTGUN, + L4D1_ACT_TERROR_WITCH_ANGRY, + L4D1_ACT_TERROR_WITCH_ANGRY_HIGH, + L4D1_ACT_TERROR_WITCH_IDLE, + L4D1_ACT_TERROR_WITCH_IDLE_PRE_RETREAT, + L4D1_ACT_TERROR_WITCH_RETREAT, + L4D1_ACT_TERROR_WITCH_KILL_DISPLAY, + L4D1_ACT_TERROR_WITCH_KILL_LOOP, + L4D1_ACT_TERROR_TUG, + L4D1_ACT_TERROR_FLINCH, + L4D1_ACT_TERROR_FLINCH_LEDGE, + L4D1_ACT_SECONDARYATTACK, + L4D1_ACT_TERROR_INCAP_CRAWL, + L4D1_ACT_TERROR_INCAP_TO_STAND, + L4D1_ACT_TERROR_INCAP_TO_CROUCH, + L4D1_ACT_TERROR_ITEM_PICKUP, + L4D1_ACT_IDLE_INCAP_PISTOL, + L4D1_ACT_IDLE_INCAP_ELITES, + L4D1_ACT_FALL, + L4D1_ACT_CALL_FOR_RESCUE, + L4D1_ACT_PUSH, + L4D1_ACT_IDLE_MINIGUN, + L4D1_ACT_PRIMARYATTACK_MINIGUN, + L4D1_ACT_TERROR_LEDGE_CLIMB, + L4D1_ACT_TERROR_LEDGE_CLIMB_TO_CROUCH, + L4D1_ACT_TERROR_FALL_GRAB_LEDGE, + L4D1_ACT_TERROR_LEDGE_HANG_FIRM, + L4D1_ACT_TERROR_LEDGE_HANG_WEAK, + L4D1_ACT_TERROR_LEDGE_HANG_DANGLE, + L4D1_ACT_TERROR_IDLE_LADDER, + L4D1_ACT_TERROR_LADDER_DISMOUNT, + L4D1_ACT_TERROR_CLIMB_24_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_36_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_48_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_60_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_70_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_72_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_84_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_96_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_108_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_115_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_120_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_130_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_132_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_144_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_150_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_156_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_166_FROM_STAND, + L4D1_ACT_TERROR_CLIMB_168_FROM_STAND, + L4D1_ACT_TERROR_HUNTER_LUNGE_INTO_SURVIVOR, + L4D1_ACT_TERROR_HUNTER_LUNGE, + L4D1_ACT_TERROR_HUNTER_LUNGE_WHILE_RUNNING, + L4D1_ACT_TERROR_HUNTER_LANDING_HARD, + L4D1_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_SPIN_RIGHT, + L4D1_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_SPIN_LEFT, + L4D1_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_BACK, + L4D1_ACT_TERROR_HUNTER_LUNGE_IDLE, + L4D1_ACT_TERROR_HUNTER_LUNGE_ONTO_WALL, + L4D1_ACT_TERROR_HUNTER_POUNCE, + L4D1_ACT_TERROR_HUNTER_POUNCE_IDLE, + L4D1_ACT_TERROR_SMOKER_PREPARE_TONGUE_LAUNCH, + L4D1_ACT_TERROR_SMOKER_SENDING_OUT_TONGUE, + L4D1_ACT_TERROR_SMOKER_SENDING_OUT_TONGUE_IDLE, + L4D1_ACT_TERROR_SMOKER_REELING_IN_TONGUE, + L4D1_ACT_TERROR_SMOKER_REELING_IN_TONGUE_IDLE, + L4D1_ACT_TERROR_SMOKER_CRITICAL_ATTACK, + L4D1_ACT_TERROR_SMOKER_CRITICAL_ATTACK_IDLE, + L4D1_ACT_TERROR_SMOKER_END_TONGUE_ATTACK, + L4D1_ACT_TERROR_GUARD, + L4D1_ACT_HULK_THROW, + L4D1_ACT_TANK_OVERHEAD_THROW, + L4D1_ACT_HULK_ATTACK_LOW, + L4D1_ACT_TERROR_HUNTER_POUNCE_MELEE, + L4D1_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_L, + L4D1_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_R, + L4D1_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_BACKWARD, + L4D1_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_FORWARD, + L4D1_ACT_IDLE_POUNCED, + L4D1_ACT_TERROR_POUNCED_TO_STAND, + L4D1_ACT_TERROR_INCAP_FROM_POUNCE, + L4D1_ACT_TERROR_INCAP_FROM_TONGUE, + L4D1_ACT_TERROR_IDLE_FALL_FROM_TONGUE, + L4D1_ACT_TERROR_HANGING_FROM_TONGUE, + L4D1_ACT_TERROR_HANGING_FROM_TONGUE_MALE, + L4D1_ACT_TERROR_HANGING_FROM_TONGUE_FEMALE, + L4D1_ACT_TERROR_STANDING_CHOKE_FROM_TONGUE, + L4D1_ACT_TERROR_DRAGGING_FROM_TONGUE, + L4D1_ACT_TERROR_DRAGGING_FROM_TONGUE_MALE, + L4D1_ACT_TERROR_DRAGGING_FROM_TONGUE_FEMALE, + L4D1_ACT_TERROR_DRAGGING_FROM_TONGUE_DEPLOY, + L4D1_ACT_TERROR_CHOKING_TONGUE_GROUND, + L4D1_ACT_TERROR_CHOKING_TONGUE_GROUND_MALE, + L4D1_ACT_TERROR_CHOKING_TONGUE_GROUND_FEMALE, + L4D1_ACT_TERROR_INCAP_FROM_TONGUE_GERMANY, + L4D1_ACT_TERROR_HANGING_FROM_TONGUE_GERMANY, + L4D1_ACT_TERROR_IDLE_FALL_FROM_TONGUE_GERMANY, + L4D1_ACT_TERROR_STANDING_CHOKE_FROM_TONGUE_GERMANY, + L4D1_ACT_TERROR_ATTACK_MOVING, + L4D1_ACT_TERROR_TANKROCK_TO_STAND, + L4D1_ACT_TERROR_HULK_VICTORY, + L4D1_ACT_TERROR_HULK_VICTORY_B, + L4D1_ACT_TERROR_RAGE_AT_ENEMY, + L4D1_ACT_TERROR_RAGE_AT_KNOCKDOWN, + L4D1_ACT_TERROR_SMASH_LEFT, + L4D1_ACT_TERROR_SMASH_RIGHT, + L4D1_ACT_VM_LUNGE_LAYER, + L4D1_ACT_VM_LUNGE_PUSH, + L4D1_ACT_VM_LUNGE_PUSH_LAYER, + L4D1_ACT_VM_LUNGE_OFFWALL, + L4D1_ACT_VM_LUNGE_OFFWALL_LAYER, + L4D1_ACT_VM_LUNGE_POUNCE, + L4D1_ACT_VM_LUNGE_POUNCE_LAYER, + L4D1_ACT_VM_POUNCE, + L4D1_ACT_VM_POUNCE_LAYER, + L4D1_ACT_VM_VOMIT_LAYER, + L4D1_ACT_VM_TONGUE, + L4D1_ACT_VM_TONGUE_LAYER, + L4D1_ACT_VM_BITE, + L4D1_ACT_VM_BITE_LAYER, + L4D1_ACT_VM_COUGH_LAYER, + L4D1_ACT_VM_FIDGET_LAYER, + L4D1_ACT_DOOR_OPEN, + L4D1_ACT_DOOR_OPENFAIL, + L4D1_ACT_DOOR_ANIMTOLOCK, + L4D1_ACT_DOOR_ANIMTOUNLOCK, + L4D1_ACT_VM_ITEMPICKUP_EXTEND, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP, + L4D1_ACT_VM_ITEMPICKUP_LOOP_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND, + L4D1_ACT_VM_HELPINGHAND_EXTEND_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP, + L4D1_ACT_VM_HELPINGHAND_LOOP_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT, + L4D1_ACT_VM_HELPINGHAND_RETRACT_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_PISTOL, + L4D1_ACT_VM_HELPINGHAND_LOOP_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PISTOL, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PISTOL, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_DUAL_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_LOOP_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_DUAL_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_DUAL_PISTOL, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_DUAL_PISTOL, + L4D1_ACT_VM_HELPINGHAND_LOOP_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_DUAL_PISTOL, + L4D1_ACT_VM_HELPINGHAND_EXTEND_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_DUAL_PISTOL, + L4D1_ACT_VM_HELPINGHAND_RETRACT_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_RIFLE, + L4D1_ACT_VM_ITEMPICKUP_LOOP_RIFLE_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_RIFLE, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_RIFLE_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_RIFLE, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_RIFLE_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_RIFLE, + L4D1_ACT_VM_HELPINGHAND_LOOP_RIFLE_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_RIFLE, + L4D1_ACT_VM_HELPINGHAND_EXTEND_RIFLE_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_RIFLE, + L4D1_ACT_VM_HELPINGHAND_RETRACT_RIFLE_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SMG, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SMG_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SMG, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SMG_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SMG, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SMG_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_SMG, + L4D1_ACT_VM_HELPINGHAND_LOOP_SMG_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SMG, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SMG_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SMG, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SMG_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_SHOTGUN, + L4D1_ACT_VM_HELPINGHAND_LOOP_SHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SHOTGUN, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SHOTGUN, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_AUTOSHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_LOOP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_AUTOSHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_AUTOSHOTGUN, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_AUTOSHOTGUN, + L4D1_ACT_VM_HELPINGHAND_LOOP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_AUTOSHOTGUN, + L4D1_ACT_VM_HELPINGHAND_EXTEND_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_AUTOSHOTGUN, + L4D1_ACT_VM_HELPINGHAND_RETRACT_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SNIPER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_SNIPER_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SNIPER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_SNIPER_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SNIPER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_SNIPER_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_SNIPER, + L4D1_ACT_VM_HELPINGHAND_LOOP_SNIPER_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SNIPER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_SNIPER_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SNIPER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_SNIPER_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PIPEBOMB, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PIPEBOMB_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PIPEBOMB, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PIPEBOMB_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PIPEBOMB, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PIPEBOMB_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_PIPEBOMB, + L4D1_ACT_VM_HELPINGHAND_LOOP_PIPEBOMB_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PIPEBOMB, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PIPEBOMB_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PIPEBOMB, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PIPEBOMB_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_MOLOTOV, + L4D1_ACT_VM_ITEMPICKUP_LOOP_MOLOTOV_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_MOLOTOV, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_MOLOTOV_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_MOLOTOV, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_MOLOTOV_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_MOLOTOV, + L4D1_ACT_VM_HELPINGHAND_LOOP_MOLOTOV_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_MOLOTOV, + L4D1_ACT_VM_HELPINGHAND_EXTEND_MOLOTOV_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_MOLOTOV, + L4D1_ACT_VM_HELPINGHAND_RETRACT_MOLOTOV_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_MEDKIT, + L4D1_ACT_VM_ITEMPICKUP_LOOP_MEDKIT_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_MEDKIT, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_MEDKIT_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_MEDKIT, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_MEDKIT_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_MEDKIT, + L4D1_ACT_VM_HELPINGHAND_LOOP_MEDKIT_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_MEDKIT, + L4D1_ACT_VM_HELPINGHAND_EXTEND_MEDKIT_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_MEDKIT, + L4D1_ACT_VM_HELPINGHAND_RETRACT_MEDKIT_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PAINPILLS, + L4D1_ACT_VM_ITEMPICKUP_LOOP_PAINPILLS_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PAINPILLS, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_PAINPILLS_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PAINPILLS, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_PAINPILLS_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_PAINPILLS, + L4D1_ACT_VM_HELPINGHAND_LOOP_PAINPILLS_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PAINPILLS, + L4D1_ACT_VM_HELPINGHAND_EXTEND_PAINPILLS_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PAINPILLS, + L4D1_ACT_VM_HELPINGHAND_RETRACT_PAINPILLS_LAYER, + L4D1_ACT_VM_CANCEL, + L4D1_ACT_VM_CANCEL_LAYER, + L4D1_ACT_CROUCHIDLE_RIFLE, + L4D1_ACT_IDLE_INJURED_RIFLE, + L4D1_ACT_WALK_INJURED_RIFLE, + L4D1_ACT_RUN_INJURED_RIFLE, + L4D1_ACT_DEPLOY_RIFLE, + L4D1_ACT_PRIMARYATTACK_RIFLE, + L4D1_ACT_RELOAD_RIFLE, + L4D1_ACT_IDLE_CALM_RIFLE, + L4D1_ACT_WALK_CALM_RIFLE, + L4D1_ACT_RUN_CALM_RIFLE, + L4D1_ACT_MELEE_SWEEP_RIFLE_IDLE, + L4D1_ACT_MELEE_SHOVE_RIFLE_IDLE, + L4D1_ACT_MELEE_STRAIGHT_RIFLE_IDLE, + L4D1_ACT_MELEE_SWEEP_RIFLE_RUN, + L4D1_ACT_MELEE_SHOVE_RIFLE_RUN, + L4D1_ACT_MELEE_STRAIGHT_RIFLE_RUN, + L4D1_ACT_TERROR_PULLED_RUN_RIFLE, + L4D1_ACT_MELEE_STOMP_RIFLE_IDLE, + L4D1_ACT_MELEE_STOMP_RIFLE_WALK, + L4D1_ACT_IDLE_SHOTGUN, + L4D1_ACT_WALK_SHOTGUN, + L4D1_ACT_RUN_SHOTGUN, + L4D1_ACT_IDLE_CALM_SHOTGUN, + L4D1_ACT_CROUCHIDLE_SHOTGUN, + L4D1_ACT_RUN_CROUCH_SHOTGUN, + L4D1_ACT_DEPLOY_SHOTGUN, + L4D1_ACT_PRIMARYATTACK_SHOTGUN, + L4D1_ACT_RELOAD_SHOTGUN_START, + L4D1_ACT_RELOAD_SHOTGUN_LOOP, + L4D1_ACT_RELOAD_SHOTGUN_END, + L4D1_ACT_IDLE_PUMPSHOTGUN, + L4D1_ACT_CROUCHIDLE_PUMPSHOTGUN, + L4D1_ACT_IDLE_CALM_PUMPSHOTGUN, + L4D1_ACT_IDLE_INJURED_PUMPSHOTGUN, + L4D1_ACT_WALK_PUMPSHOTGUN, + L4D1_ACT_RUN_CROUCH_PUMPSHOTGUN, + L4D1_ACT_RUN_PUMPSHOTGUN, + L4D1_ACT_WALK_CALM_PUMPSHOTGUN, + L4D1_ACT_RUN_CALM_PUMPSHOTGUN, + L4D1_ACT_WALK_INJURED_PUMPSHOTGUN, + L4D1_ACT_RUN_INJURED_PUMPSHOTGUN, + L4D1_ACT_PRIMARYATTACK_PUMPSHOTGUN, + L4D1_ACT_RELOAD_PUMPSHOTGUN_START, + L4D1_ACT_RELOAD_PUMPSHOTGUN_LOOP, + L4D1_ACT_RELOAD_PUMPSHOTGUN_END, + L4D1_ACT_IDLE_GREN, + L4D1_ACT_CROUCHIDLE_GREN, + L4D1_ACT_IDLE_INJURED_GREN, + L4D1_ACT_RUN_GREN, + L4D1_ACT_WALK_GREN, + L4D1_ACT_RUN_CROUCH_GREN, + L4D1_ACT_DEPLOY_GREN, + L4D1_ACT_WALK_INJURED_GREN, + L4D1_ACT_RUN_INJURED_GREN, + L4D1_ACT_PRIMARYATTACK_GREN1_IDLE, + L4D1_ACT_PRIMARYATTACK_GREN2_IDLE, + L4D1_ACT_PRIMARYATTACK_GREN1_RUN, + L4D1_ACT_PRIMARYATTACK_GREN2_RUN, + L4D1_ACT_IDLE_GREN_PULL_BACK, + L4D1_ACT_CROUCHIDLE_GREN_PULL_BACK, + L4D1_ACT_IDLE_INJURED_GREN_PULL_BACK, + L4D1_ACT_RUN_GREN_PULL_BACK, + L4D1_ACT_WALK_GREN_PULL_BACK, + L4D1_ACT_RUN_CROUCH_GREN_PULL_BACK, + L4D1_ACT_WALK_INJURED_GREN_PULL_BACK, + L4D1_ACT_RUN_INJURED_GREN_PULL_BACK, + L4D1_ACT_IDLE_SNIPER, + L4D1_ACT_CROUCHIDLE_SNIPER, + L4D1_ACT_IDLE_CALM_SNIPER, + L4D1_ACT_IDLE_INJURED_SNIPER, + L4D1_ACT_WALK_SNIPER, + L4D1_ACT_RUN_CROUCH_SNIPER, + L4D1_ACT_RUN_SNIPER, + L4D1_ACT_WALK_CALM_SNIPER, + L4D1_ACT_RUN_CALM_SNIPER, + L4D1_ACT_WALK_INJURED_SNIPER, + L4D1_ACT_RUN_INJURED_SNIPER, + L4D1_ACT_IDLE_SNIPER_ZOOMED, + L4D1_ACT_CROUCHIDLE_SNIPER_ZOOMED, + L4D1_ACT_IDLE_INJURED_SNIPER_ZOOMED, + L4D1_ACT_IDLE_SMG, + L4D1_ACT_WALK_SMG, + L4D1_ACT_RUN_SMG, + L4D1_ACT_CROUCHIDLE_SMG, + L4D1_ACT_RUN_CROUCH_SMG, + L4D1_ACT_IDLE_INJURED_SMG, + L4D1_ACT_WALK_INJURED_SMG, + L4D1_ACT_RUN_INJURED_SMG, + L4D1_ACT_IDLE_CALM_SMG, + L4D1_ACT_WALK_CALM_SMG, + L4D1_ACT_RUN_CALM_SMG, + L4D1_ACT_PRIMARYATTACK_SMG, + L4D1_ACT_RELOAD_SMG, + L4D1_ACT_IDLE_FIRSTAIDKIT, + L4D1_ACT_CROUCHIDLE_FIRSTAIDKIT, + L4D1_ACT_IDLE_INJURED_FIRSTAIDKIT, + L4D1_ACT_RUN_FIRSTAIDKIT, + L4D1_ACT_WALK_FIRSTAIDKIT, + L4D1_ACT_RUN_CROUCH_FIRSTAIDKIT, + L4D1_ACT_WALK_INJURED_FIRSTAIDKIT, + L4D1_ACT_RUN_INJURED_FIRSTAIDKIT, + L4D1_ACT_CROUCHIDLE_PISTOL, + L4D1_ACT_RUN_CROUCH_PISTOL, + L4D1_ACT_IDLE_INJURED_PISTOL, + L4D1_ACT_WALK_INJURED_PISTOL, + L4D1_ACT_RUN_INJURED_PISTOL, + L4D1_ACT_DEPLOY_PISTOL, + L4D1_ACT_PRIMARYATTACK_PISTOL, + L4D1_ACT_IDLE_CALM_PISTOL, + L4D1_ACT_WALK_CALM_PISTOL, + L4D1_ACT_RUN_CALM_PISTOL, + L4D1_ACT_IDLE_ELITES, + L4D1_ACT_WALK_ELITES, + L4D1_ACT_RUN_ELITES, + L4D1_ACT_CROUCHIDLE_ELITES, + L4D1_ACT_RUN_CROUCH_ELITES, + L4D1_ACT_IDLE_INJURED_ELITES, + L4D1_ACT_WALK_INJURED_ELITES, + L4D1_ACT_RUN_INJURED_ELITES, + L4D1_ACT_DEPLOY_ELITES, + L4D1_ACT_PRIMARYATTACK_ELITES_R, + L4D1_ACT_PRIMARYATTACK_ELITES_L, + L4D1_ACT_IDLE_CALM_ELITES, + L4D1_ACT_WALK_CALM_ELITES, + L4D1_ACT_RUN_CALM_ELITES, + L4D1_ACT_RELOAD_ELITES, + L4D1_ACT_RELOAD_M4, + L4D1_ACT_PRIMARYATTACK_XM1014, + L4D1_ACT_PRIMARYATTACK_M3S90, + L4D1_ACT_IDLE_GASCAN, + L4D1_ACT_CROUCHIDLE_GASCAN, + L4D1_ACT_IDLE_CALM_GASCAN, + L4D1_ACT_IDLE_INJURED_GASCAN, + L4D1_ACT_RUN_GASCAN, + L4D1_ACT_WALK_GASCAN, + L4D1_ACT_RUN_CROUCH_GASCAN, + L4D1_ACT_RUN_INJURED_GASCAN, + L4D1_ACT_JUMP_GASCAN, + L4D1_ACT_MELEE_SWEEP_GASCAN, + L4D1_ACT_IDLE_O2, + L4D1_ACT_CROUCHIDLE_O2, + L4D1_ACT_IDLE_CALM_O2, + L4D1_ACT_IDLE_INJURED_O2, + L4D1_ACT_RUN_O2, + L4D1_ACT_WALK_O2, + L4D1_ACT_RUN_CROUCH_O2, + L4D1_ACT_RUN_INJURED_O2, + L4D1_ACT_JUMP_O2, + L4D1_ACT_MELEE_SWEEP_O2, + L4D1_ACT_VM_MELEE, + L4D1_ACT_VM_SHOOT_LAYER, + L4D1_ACT_VM_SECONDARYATTACK_LAYER, + L4D1_ACT_VM_MELEE_LAYER, + L4D1_ACT_VM_PICKUP_LAYER, + L4D1_ACT_VM_PICKUP_CLIPIN, + L4D1_ACT_VM_PICKUP_CLIPIN_LAYER, + L4D1_ACT_VM_PICKUP_CHARGING, + L4D1_ACT_VM_PICKUP_CHARGING_LAYER, + L4D1_ACT_VM_PICKUP_FASSIST, + L4D1_ACT_VM_PICKUP_FASSIST_LAYER, + L4D1_ACT_VM_RELOAD_PUMP, + L4D1_ACT_VM_RELOAD_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT, + L4D1_ACT_VM_RELOAD_CLIPOUT_LAYER, + L4D1_ACT_VM_RELOAD_CLIPIN, + L4D1_ACT_VM_RELOAD_CLIPIN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN2, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN2_LAYER, + L4D1_ACT_VM_DEPLOY_LAYER, + L4D1_ACT_VM_THROW_LAYER, + L4D1_ACT_VM_PULLPIN_LAYER, + L4D1_ACT_VM_IDLE_BAREHAND, + L4D1_ACT_VM_DEPLOY_BAREHAND, + L4D1_ACT_VM_DEPLOY_BAREHAND_LAYER, + L4D1_ACT_VM_MELEE_BAREHAND, + L4D1_ACT_VM_MELEE_BAREHAND_LAYER, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_BAREHAND, + L4D1_ACT_VM_ITEMPICKUP_EXTEND_BAREHAND_LAYER, + L4D1_ACT_VM_ITEMPICKUP_LOOP_BAREHAND, + L4D1_ACT_VM_ITEMPICKUP_LOOP_BAREHAND_LAYER, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_BAREHAND, + L4D1_ACT_VM_ITEMPICKUP_RETRACT_BAREHAND_LAYER, + L4D1_ACT_VM_HELPINGHAND_EXTEND_BAREHAND, + L4D1_ACT_VM_HELPINGHAND_EXTEND_BAREHAND_LAYER, + L4D1_ACT_VM_HELPINGHAND_LOOP_BAREHAND, + L4D1_ACT_VM_HELPINGHAND_LOOP_BAREHAND_LAYER, + L4D1_ACT_VM_HELPINGHAND_RETRACT_BAREHAND, + L4D1_ACT_VM_HELPINGHAND_RETRACT_BAREHAND_LAYER, + L4D1_ACT_VM_IDLE_DUAL_PISTOL, + L4D1_ACT_VM_DEPLOY_DUAL_PISTOL, + L4D1_ACT_VM_DEPLOY_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_DUAL_PISTOL, + L4D1_ACT_VM_SHOOT_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_SECONDARYATTACK_DUAL_PISTOL, + L4D1_ACT_VM_SECONDARYATTACK_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_CLIPOUT_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_CLIPIN_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_CLIPIN_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN2_DUAL_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN2_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_PICKUP_DUAL_PISTOL, + L4D1_ACT_VM_PICKUP_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_PICKUP_CLIPIN_DUAL_PISTOL, + L4D1_ACT_VM_PICKUP_CLIPIN_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_PICKUP_CHARGING_DUAL_PISTOL, + L4D1_ACT_VM_PICKUP_CHARGING_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_MELEE_DUAL_PISTOL, + L4D1_ACT_VM_MELEE_DUAL_PISTOL_LAYER, + L4D1_ACT_VM_IDLE_PISTOL, + L4D1_ACT_VM_DEPLOY_PISTOL, + L4D1_ACT_VM_DEPLOY_PISTOL_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_PISTOL, + L4D1_ACT_VM_SHOOT_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_PISTOL, + L4D1_ACT_VM_RELOAD_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT_PISTOL, + L4D1_ACT_VM_RELOAD_CLIPOUT_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_PISTOL_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_PISTOL, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_PISTOL_LAYER, + L4D1_ACT_VM_MELEE_PISTOL, + L4D1_ACT_VM_MELEE_PISTOL_LAYER, + L4D1_ACT_VM_IDLE_RIFLE, + L4D1_ACT_VM_PICKUP_RIFLE, + L4D1_ACT_VM_PICKUP_RIFLE_LAYER, + L4D1_ACT_VM_PICKUP_CLIPIN_RIFLE, + L4D1_ACT_VM_PICKUP_CLIPIN_RIFLE_LAYER, + L4D1_ACT_VM_PICKUP_CHARGING_RIFLE, + L4D1_ACT_VM_PICKUP_CHARGING_RIFLE_LAYER, + L4D1_ACT_VM_PICKUP_FASSIST_RIFLE, + L4D1_ACT_VM_PICKUP_FASSIST_RIFLE_LAYER, + L4D1_ACT_VM_DEPLOY_RIFLE, + L4D1_ACT_VM_DEPLOY_RIFLE_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_RIFLE, + L4D1_ACT_VM_SHOOT_RIFLE_LAYER, + L4D1_ACT_VM_RELOAD_RIFLE, + L4D1_ACT_VM_RELOAD_RIFLE_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT_RIFLE, + L4D1_ACT_VM_RELOAD_CLIPOUT_RIFLE_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_RIFLE, + L4D1_ACT_VM_RELOAD_EMPTY_RIFLE_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_RIFLE, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_RIFLE_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_RIFLE, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_RIFLE_LAYER, + L4D1_ACT_VM_MELEE_RIFLE, + L4D1_ACT_VM_MELEE_RIFLE_LAYER, + L4D1_ACT_VM_FIDGET_RIFLE_LAYER, + L4D1_ACT_VM_IDLE_SMG, + L4D1_ACT_VM_PICKUP_SMG, + L4D1_ACT_VM_PICKUP_SMG_LAYER, + L4D1_ACT_VM_PICKUP_CLIPIN_SMG, + L4D1_ACT_VM_PICKUP_CLIPIN_SMG_LAYER, + L4D1_ACT_VM_PICKUP_CHARGING_SMG, + L4D1_ACT_VM_PICKUP_CHARGING_SMG_LAYER, + L4D1_ACT_VM_DEPLOY_SMG, + L4D1_ACT_VM_DEPLOY_SMG_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_SMG, + L4D1_ACT_VM_SHOOT_SMG_LAYER, + L4D1_ACT_VM_RELOAD_SMG, + L4D1_ACT_VM_RELOAD_SMG_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT_SMG, + L4D1_ACT_VM_RELOAD_CLIPOUT_SMG_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_SMG, + L4D1_ACT_VM_RELOAD_EMPTY_SMG_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_SMG, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_SMG_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_SMG, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_SMG_LAYER, + L4D1_ACT_VM_MELEE_SMG, + L4D1_ACT_VM_MELEE_SMG_LAYER, + L4D1_ACT_VM_FIDGET_SMG_LAYER, + L4D1_ACT_VM_IDLE_SNIPER, + L4D1_ACT_VM_PICKUP_SNIPER, + L4D1_ACT_VM_PICKUP_SNIPER_LAYER, + L4D1_ACT_VM_PICKUP_CLIPIN_SNIPER, + L4D1_ACT_VM_PICKUP_CLIPIN_SNIPER_LAYER, + L4D1_ACT_VM_PICKUP_CHARGING_SNIPER, + L4D1_ACT_VM_PICKUP_CHARGING_SNIPER_LAYER, + L4D1_ACT_VM_DEPLOY_SNIPER, + L4D1_ACT_VM_DEPLOY_SNIPER_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_SNIPER, + L4D1_ACT_VM_SHOOT_SNIPER_LAYER, + L4D1_ACT_VM_RELOAD_SNIPER, + L4D1_ACT_VM_RELOAD_SNIPER_LAYER, + L4D1_ACT_VM_RELOAD_CLIPOUT_SNIPER, + L4D1_ACT_VM_RELOAD_CLIPOUT_SNIPER_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_SNIPER, + L4D1_ACT_VM_RELOAD_EMPTY_SNIPER_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_SNIPER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPOUT_SNIPER_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_SNIPER, + L4D1_ACT_VM_RELOAD_EMPTY_CLIPIN_SNIPER_LAYER, + L4D1_ACT_VM_MELEE_SNIPER, + L4D1_ACT_VM_MELEE_SNIPER_LAYER, + L4D1_ACT_VM_FIDGET_SNIPER_LAYER, + L4D1_ACT_VM_IDLE_SHOTGUN, + L4D1_ACT_VM_DEPLOY_SHOTGUN, + L4D1_ACT_VM_DEPLOY_SHOTGUN_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_SHOTGUN, + L4D1_ACT_VM_SHOOT_SHOTGUN_LAYER, + L4D1_ACT_VM_MELEE_SHOTGUN, + L4D1_ACT_VM_MELEE_SHOTGUN_LAYER, + L4D1_ACT_VM_PICKUP_SHOTGUN, + L4D1_ACT_VM_PICKUP_SHOTGUN_LAYER, + L4D1_ACT_VM_PUMP_SHOTGUN, + L4D1_ACT_VM_PUMP_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_START_SHOTGUN, + L4D1_ACT_VM_RELOAD_START_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_INSERT_SHOTGUN, + L4D1_ACT_VM_RELOAD_INSERT_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_NOPUMP_SHOTGUN, + L4D1_ACT_VM_RELOAD_NOPUMP_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_START_SHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_START_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_INSERT_SHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_INSERT_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_PUMP_SHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_PUMP_SHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_PUMPREADY_SHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_PUMPREADY_SHOTGUN_LAYER, + L4D1_ACT_VM_IDLE_AUTOSHOTGUN, + L4D1_ACT_VM_DEPLOY_AUTOSHOTGUN, + L4D1_ACT_VM_DEPLOY_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_PRIMARYATTACK_AUTOSHOTGUN, + L4D1_ACT_VM_SHOOT_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_MELEE_AUTOSHOTGUN, + L4D1_ACT_VM_MELEE_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_PICKUP_AUTOSHOTGUN, + L4D1_ACT_VM_PICKUP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_PUMP_AUTOSHOTGUN, + L4D1_ACT_VM_PUMP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_START_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_START_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_INSERT_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_INSERT_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_NOPUMP_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_NOPUMP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_START_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_START_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_INSERT_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_INSERT_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_PUMP_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_PUMP_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_RELOAD_EMPTY_PUMPREADY_AUTOSHOTGUN, + L4D1_ACT_VM_RELOAD_EMPTY_PUMPREADY_AUTOSHOTGUN_LAYER, + L4D1_ACT_VM_IDLE_PIPEBOMB, + L4D1_ACT_VM_DEPLOY_PIPEBOMB, + L4D1_ACT_VM_DEPLOY_PIPEBOMB_LAYER, + L4D1_ACT_VM_PULLPIN_PIPEBOMB, + L4D1_ACT_VM_PULLPIN_PIPEBOMB_LAYER, + L4D1_ACT_VM_THROW_PIPEBOMB, + L4D1_ACT_VM_THROW_PIPEBOMB_LAYER, + L4D1_ACT_VM_MELEE_PIPEBOMB, + L4D1_ACT_VM_MELEE_PIPEBOMB_LAYER, + L4D1_ACT_VM_IDLE_MOLOTOV, + L4D1_ACT_VM_DEPLOY_MOLOTOV, + L4D1_ACT_VM_DEPLOY_MOLOTOV_LAYER, + L4D1_ACT_VM_PULLPIN_MOLOTOV, + L4D1_ACT_VM_PULLPIN_MOLOTOV_LAYER, + L4D1_ACT_VM_THROW_MOLOTOV, + L4D1_ACT_VM_THROW_MOLOTOV_LAYER, + L4D1_ACT_VM_MELEE_MOLOTOV, + L4D1_ACT_VM_MELEE_MOLOTOV_LAYER, + L4D1_ACT_VM_IDLE_PAINPILLS, + L4D1_ACT_VM_DEPLOY_PAINPILLS, + L4D1_ACT_VM_DEPLOY_PAINPILLS_LAYER, + L4D1_ACT_VM_MELEE_PAINPILLS, + L4D1_ACT_VM_MELEE_PAINPILLS_LAYER, + L4D1_ACT_VM_USE_PAINPILLS, + L4D1_ACT_VM_USE_PAINPILLS_LAYER, + L4D1_ACT_VM_IDLE_MEDKIT, + L4D1_ACT_VM_DEPLOY_MEDKIT, + L4D1_ACT_VM_DEPLOY_MEDKIT_LAYER, + L4D1_ACT_VM_MELEE_MEDKIT, + L4D1_ACT_VM_MELEE_MEDKIT_LAYER, + L4D1_ACT_VM_IDLE_GASCAN, + L4D1_ACT_VM_DEPLOY_GASCAN, + L4D1_ACT_VM_PULLPIN_GASCAN, + L4D1_ACT_VM_THROW_GASCAN, + L4D1_ACT_VM_MELEE_GASCAN, + L4D1_ACT_VM_FIZZLE, + L4D1_ACT_MP_STAND_IDLE, + L4D1_ACT_MP_CROUCH_IDLE, + L4D1_ACT_MP_CROUCH_DEPLOYED_IDLE, + L4D1_ACT_MP_CROUCH_DEPLOYED, + L4D1_ACT_MP_DEPLOYED_IDLE, + L4D1_ACT_MP_RUN, + L4D1_ACT_MP_WALK, + L4D1_ACT_MP_AIRWALK, + L4D1_ACT_MP_CROUCHWALK, + L4D1_ACT_MP_SPRINT, + L4D1_ACT_MP_JUMP, + L4D1_ACT_MP_JUMP_START, + L4D1_ACT_MP_JUMP_FLOAT, + L4D1_ACT_MP_JUMP_LAND, + L4D1_ACT_MP_DOUBLEJUMP, + L4D1_ACT_MP_SWIM, + L4D1_ACT_MP_DEPLOYED, + L4D1_ACT_MP_SWIM_DEPLOYED, + L4D1_ACT_MP_VCD, + L4D1_ACT_MP_ATTACK_STAND_PRIMARYFIRE, + L4D1_ACT_MP_ATTACK_STAND_PRIMARYFIRE_DEPLOYED, + L4D1_ACT_MP_ATTACK_STAND_SECONDARYFIRE, + L4D1_ACT_MP_ATTACK_STAND_GRENADE, + L4D1_ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, + L4D1_ACT_MP_ATTACK_CROUCH_PRIMARYFIRE_DEPLOYED, + L4D1_ACT_MP_ATTACK_CROUCH_SECONDARYFIRE, + L4D1_ACT_MP_ATTACK_CROUCH_GRENADE, + L4D1_ACT_MP_ATTACK_SWIM_PRIMARYFIRE, + L4D1_ACT_MP_ATTACK_SWIM_SECONDARYFIRE, + L4D1_ACT_MP_ATTACK_SWIM_GRENADE, + L4D1_ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE, + L4D1_ACT_MP_ATTACK_AIRWALK_SECONDARYFIRE, + L4D1_ACT_MP_ATTACK_AIRWALK_GRENADE, + L4D1_ACT_MP_RELOAD_STAND, + L4D1_ACT_MP_RELOAD_STAND_LOOP, + L4D1_ACT_MP_RELOAD_STAND_END, + L4D1_ACT_MP_RELOAD_CROUCH, + L4D1_ACT_MP_RELOAD_CROUCH_LOOP, + L4D1_ACT_MP_RELOAD_CROUCH_END, + L4D1_ACT_MP_RELOAD_SWIM, + L4D1_ACT_MP_RELOAD_SWIM_LOOP, + L4D1_ACT_MP_RELOAD_SWIM_END, + L4D1_ACT_MP_RELOAD_AIRWALK, + L4D1_ACT_MP_RELOAD_AIRWALK_LOOP, + L4D1_ACT_MP_RELOAD_AIRWALK_END, + L4D1_ACT_MP_ATTACK_STAND_PREFIRE, + L4D1_ACT_MP_ATTACK_STAND_POSTFIRE, + L4D1_ACT_MP_ATTACK_STAND_STARTFIRE, + L4D1_ACT_MP_ATTACK_CROUCH_PREFIRE, + L4D1_ACT_MP_ATTACK_CROUCH_POSTFIRE, + L4D1_ACT_MP_ATTACK_SWIM_PREFIRE, + L4D1_ACT_MP_ATTACK_SWIM_POSTFIRE, + L4D1_ACT_MP_STAND_PRIMARY, + L4D1_ACT_MP_CROUCH_PRIMARY, + L4D1_ACT_MP_RUN_PRIMARY, + L4D1_ACT_MP_WALK_PRIMARY, + L4D1_ACT_MP_AIRWALK_PRIMARY, + L4D1_ACT_MP_CROUCHWALK_PRIMARY, + L4D1_ACT_MP_JUMP_PRIMARY, + L4D1_ACT_MP_JUMP_START_PRIMARY, + L4D1_ACT_MP_JUMP_FLOAT_PRIMARY, + L4D1_ACT_MP_JUMP_LAND_PRIMARY, + L4D1_ACT_MP_SWIM_PRIMARY, + L4D1_ACT_MP_DEPLOYED_PRIMARY, + L4D1_ACT_MP_SWIM_DEPLOYED_PRIMARY, + L4D1_ACT_MP_ATTACK_STAND_PRIMARY, + L4D1_ACT_MP_ATTACK_STAND_PRIMARY_DEPLOYED, + L4D1_ACT_MP_ATTACK_CROUCH_PRIMARY, + L4D1_ACT_MP_ATTACK_CROUCH_PRIMARY_DEPLOYED, + L4D1_ACT_MP_ATTACK_SWIM_PRIMARY, + L4D1_ACT_MP_ATTACK_AIRWALK_PRIMARY, + L4D1_ACT_MP_RELOAD_STAND_PRIMARY, + L4D1_ACT_MP_RELOAD_STAND_PRIMARY_LOOP, + L4D1_ACT_MP_RELOAD_STAND_PRIMARY_END, + L4D1_ACT_MP_RELOAD_CROUCH_PRIMARY, + L4D1_ACT_MP_RELOAD_CROUCH_PRIMARY_LOOP, + L4D1_ACT_MP_RELOAD_CROUCH_PRIMARY_END, + L4D1_ACT_MP_RELOAD_SWIM_PRIMARY, + L4D1_ACT_MP_RELOAD_SWIM_PRIMARY_LOOP, + L4D1_ACT_MP_RELOAD_SWIM_PRIMARY_END, + L4D1_ACT_MP_RELOAD_AIRWALK_PRIMARY, + L4D1_ACT_MP_RELOAD_AIRWALK_PRIMARY_LOOP, + L4D1_ACT_MP_RELOAD_AIRWALK_PRIMARY_END, + L4D1_ACT_MP_ATTACK_STAND_GRENADE_PRIMARY, + L4D1_ACT_MP_ATTACK_CROUCH_GRENADE_PRIMARY, + L4D1_ACT_MP_ATTACK_SWIM_GRENADE_PRIMARY, + L4D1_ACT_MP_ATTACK_AIRWALK_GRENADE_PRIMARY, + L4D1_ACT_MP_STAND_SECONDARY, + L4D1_ACT_MP_CROUCH_SECONDARY, + L4D1_ACT_MP_RUN_SECONDARY, + L4D1_ACT_MP_WALK_SECONDARY, + L4D1_ACT_MP_AIRWALK_SECONDARY, + L4D1_ACT_MP_CROUCHWALK_SECONDARY, + L4D1_ACT_MP_JUMP_SECONDARY, + L4D1_ACT_MP_JUMP_START_SECONDARY, + L4D1_ACT_MP_JUMP_FLOAT_SECONDARY, + L4D1_ACT_MP_JUMP_LAND_SECONDARY, + L4D1_ACT_MP_SWIM_SECONDARY, + L4D1_ACT_MP_ATTACK_STAND_SECONDARY, + L4D1_ACT_MP_ATTACK_CROUCH_SECONDARY, + L4D1_ACT_MP_ATTACK_SWIM_SECONDARY, + L4D1_ACT_MP_ATTACK_AIRWALK_SECONDARY, + L4D1_ACT_MP_RELOAD_STAND_SECONDARY, + L4D1_ACT_MP_RELOAD_STAND_SECONDARY_LOOP, + L4D1_ACT_MP_RELOAD_STAND_SECONDARY_END, + L4D1_ACT_MP_RELOAD_CROUCH_SECONDARY, + L4D1_ACT_MP_RELOAD_CROUCH_SECONDARY_LOOP, + L4D1_ACT_MP_RELOAD_CROUCH_SECONDARY_END, + L4D1_ACT_MP_RELOAD_SWIM_SECONDARY, + L4D1_ACT_MP_RELOAD_SWIM_SECONDARY_LOOP, + L4D1_ACT_MP_RELOAD_SWIM_SECONDARY_END, + L4D1_ACT_MP_RELOAD_AIRWALK_SECONDARY, + L4D1_ACT_MP_RELOAD_AIRWALK_SECONDARY_LOOP, + L4D1_ACT_MP_RELOAD_AIRWALK_SECONDARY_END, + L4D1_ACT_MP_ATTACK_STAND_GRENADE_SECONDARY, + L4D1_ACT_MP_ATTACK_CROUCH_GRENADE_SECONDARY, + L4D1_ACT_MP_ATTACK_SWIM_GRENADE_SECONDARY, + L4D1_ACT_MP_ATTACK_AIRWALK_GRENADE_SECONDARY, + L4D1_ACT_MP_STAND_MELEE, + L4D1_ACT_MP_CROUCH_MELEE, + L4D1_ACT_MP_RUN_MELEE, + L4D1_ACT_MP_WALK_MELEE, + L4D1_ACT_MP_AIRWALK_MELEE, + L4D1_ACT_MP_CROUCHWALK_MELEE, + L4D1_ACT_MP_JUMP_MELEE, + L4D1_ACT_MP_JUMP_START_MELEE, + L4D1_ACT_MP_JUMP_FLOAT_MELEE, + L4D1_ACT_MP_JUMP_LAND_MELEE, + L4D1_ACT_MP_SWIM_MELEE, + L4D1_ACT_MP_ATTACK_STAND_MELEE, + L4D1_ACT_MP_ATTACK_STAND_MELEE_SECONDARY, + L4D1_ACT_MP_ATTACK_CROUCH_MELEE, + L4D1_ACT_MP_ATTACK_CROUCH_MELEE_SECONDARY, + L4D1_ACT_MP_ATTACK_SWIM_MELEE, + L4D1_ACT_MP_ATTACK_AIRWALK_MELEE, + L4D1_ACT_MP_ATTACK_STAND_GRENADE_MELEE, + L4D1_ACT_MP_ATTACK_CROUCH_GRENADE_MELEE, + L4D1_ACT_MP_ATTACK_SWIM_GRENADE_MELEE, + L4D1_ACT_MP_ATTACK_AIRWALK_GRENADE_MELEE, + L4D1_ACT_MP_GESTURE_FLINCH, + L4D1_ACT_MP_GESTURE_FLINCH_PRIMARY, + L4D1_ACT_MP_GESTURE_FLINCH_SECONDARY, + L4D1_ACT_MP_GESTURE_FLINCH_MELEE, + L4D1_ACT_MP_GESTURE_FLINCH_HEAD, + L4D1_ACT_MP_GESTURE_FLINCH_CHEST, + L4D1_ACT_MP_GESTURE_FLINCH_STOMACH, + L4D1_ACT_MP_GESTURE_FLINCH_LEFTARM, + L4D1_ACT_MP_GESTURE_FLINCH_RIGHTARM, + L4D1_ACT_MP_GESTURE_FLINCH_LEFTLEG, + L4D1_ACT_MP_GESTURE_FLINCH_RIGHTLEG, + L4D1_ACT_MP_GRENADE1_DRAW, + L4D1_ACT_MP_GRENADE1_IDLE, + L4D1_ACT_MP_GRENADE1_ATTACK, + L4D1_ACT_MP_GRENADE2_DRAW, + L4D1_ACT_MP_GRENADE2_IDLE, + L4D1_ACT_MP_GRENADE2_ATTACK, + L4D1_ACT_MP_PRIMARY_GRENADE1_DRAW, + L4D1_ACT_MP_PRIMARY_GRENADE1_IDLE, + L4D1_ACT_MP_PRIMARY_GRENADE1_ATTACK, + L4D1_ACT_MP_PRIMARY_GRENADE2_DRAW, + L4D1_ACT_MP_PRIMARY_GRENADE2_IDLE, + L4D1_ACT_MP_PRIMARY_GRENADE2_ATTACK, + L4D1_ACT_MP_SECONDARY_GRENADE1_DRAW, + L4D1_ACT_MP_SECONDARY_GRENADE1_IDLE, + L4D1_ACT_MP_SECONDARY_GRENADE1_ATTACK, + L4D1_ACT_MP_SECONDARY_GRENADE2_DRAW, + L4D1_ACT_MP_SECONDARY_GRENADE2_IDLE, + L4D1_ACT_MP_SECONDARY_GRENADE2_ATTACK, + L4D1_ACT_MP_MELEE_GRENADE1_DRAW, + L4D1_ACT_MP_MELEE_GRENADE1_IDLE, + L4D1_ACT_MP_MELEE_GRENADE1_ATTACK, + L4D1_ACT_MP_MELEE_GRENADE2_DRAW, + L4D1_ACT_MP_MELEE_GRENADE2_IDLE, + L4D1_ACT_MP_MELEE_GRENADE2_ATTACK, + L4D1_ACT_MP_STAND_BUILDING, + L4D1_ACT_MP_CROUCH_BUILDING, + L4D1_ACT_MP_RUN_BUILDING, + L4D1_ACT_MP_WALK_BUILDING, + L4D1_ACT_MP_AIRWALK_BUILDING, + L4D1_ACT_MP_CROUCHWALK_BUILDING, + L4D1_ACT_MP_JUMP_BUILDING, + L4D1_ACT_MP_JUMP_START_BUILDING, + L4D1_ACT_MP_JUMP_FLOAT_BUILDING, + L4D1_ACT_MP_JUMP_LAND_BUILDING, + L4D1_ACT_MP_SWIM_BUILDING, + L4D1_ACT_MP_ATTACK_STAND_BUILDING, + L4D1_ACT_MP_ATTACK_CROUCH_BUILDING, + L4D1_ACT_MP_ATTACK_SWIM_BUILDING, + L4D1_ACT_MP_ATTACK_AIRWALK_BUILDING, + L4D1_ACT_MP_ATTACK_STAND_GRENADE_BUILDING, + L4D1_ACT_MP_ATTACK_CROUCH_GRENADE_BUILDING, + L4D1_ACT_MP_ATTACK_SWIM_GRENADE_BUILDING, + L4D1_ACT_MP_ATTACK_AIRWALK_GRENADE_BUILDING, + L4D1_ACT_MP_STAND_PDA, + L4D1_ACT_MP_CROUCH_PDA, + L4D1_ACT_MP_RUN_PDA, + L4D1_ACT_MP_WALK_PDA, + L4D1_ACT_MP_AIRWALK_PDA, + L4D1_ACT_MP_CROUCHWALK_PDA, + L4D1_ACT_MP_JUMP_PDA, + L4D1_ACT_MP_JUMP_START_PDA, + L4D1_ACT_MP_JUMP_FLOAT_PDA, + L4D1_ACT_MP_JUMP_LAND_PDA, + L4D1_ACT_MP_SWIM_PDA, + L4D1_ACT_MP_ATTACK_STAND_PDA, + L4D1_ACT_MP_ATTACK_SWIM_PDA, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP, + L4D1_ACT_MP_GESTURE_VC_NODYES, + L4D1_ACT_MP_GESTURE_VC_NODNO, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_NODYES_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_NODNO_PRIMARY, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_NODYES_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_NODNO_SECONDARY, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH_MELEE, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT_MELEE, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP_MELEE, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP_MELEE, + L4D1_ACT_MP_GESTURE_VC_NODYES_MELEE, + L4D1_ACT_MP_GESTURE_VC_NODNO_MELEE, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH_BUILDING, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT_BUILDING, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP_BUILDING, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP_BUILDING, + L4D1_ACT_MP_GESTURE_VC_NODYES_BUILDING, + L4D1_ACT_MP_GESTURE_VC_NODNO_BUILDING, + L4D1_ACT_MP_GESTURE_VC_HANDMOUTH_PDA, + L4D1_ACT_MP_GESTURE_VC_FINGERPOINT_PDA, + L4D1_ACT_MP_GESTURE_VC_FISTPUMP_PDA, + L4D1_ACT_MP_GESTURE_VC_THUMBSUP_PDA, + L4D1_ACT_MP_GESTURE_VC_NODYES_PDA, + L4D1_ACT_MP_GESTURE_VC_NODNO_PDA, + L4D1_ACT_VM_UNUSABLE, + L4D1_ACT_VM_UNUSABLE_TO_USABLE, + L4D1_ACT_VM_USABLE_TO_UNUSABLE +} + + + +// ==================================================================================================== +// LEFT 4 DEAD 2 +// ==================================================================================================== +enum +{ + L4D2_ACT_RESET, + L4D2_ACT_IDLE, + L4D2_ACT_TRANSITION, + L4D2_ACT_COVER, + L4D2_ACT_COVER_MED, + L4D2_ACT_COVER_LOW, + L4D2_ACT_WALK, + L4D2_ACT_WALK_AIM, + L4D2_ACT_WALK_CROUCH, + L4D2_ACT_WALK_CROUCH_AIM, + L4D2_ACT_RUN, + L4D2_ACT_RUN_AIM, + L4D2_ACT_RUN_CROUCH, + L4D2_ACT_RUN_CROUCH_AIM, + L4D2_ACT_RUN_PROTECTED, + L4D2_ACT_SCRIPT_CUSTOM_MOVE, + L4D2_ACT_RANGE_ATTACK1, + L4D2_ACT_RANGE_ATTACK2, + L4D2_ACT_RANGE_ATTACK1_LOW, + L4D2_ACT_RANGE_ATTACK2_LOW, + L4D2_ACT_DIESIMPLE, + L4D2_ACT_DIEBACKWARD, + L4D2_ACT_DIEFORWARD, + L4D2_ACT_DIEVIOLENT, + L4D2_ACT_DIERAGDOLL, + L4D2_ACT_FLY, + L4D2_ACT_HOVER, + L4D2_ACT_GLIDE, + L4D2_ACT_SWIM, + L4D2_ACT_JUMP, + L4D2_ACT_HOP, + L4D2_ACT_LEAP, + L4D2_ACT_LAND, + L4D2_ACT_CLIMB_UP, + L4D2_ACT_CLIMB_DOWN, + L4D2_ACT_CLIMB_DISMOUNT, + L4D2_ACT_SHIPLADDER_UP, + L4D2_ACT_SHIPLADDER_DOWN, + L4D2_ACT_STRAFE_LEFT, + L4D2_ACT_STRAFE_RIGHT, + L4D2_ACT_ROLL_LEFT, + L4D2_ACT_ROLL_RIGHT, + L4D2_ACT_TURN_LEFT, + L4D2_ACT_TURN_RIGHT, + L4D2_ACT_CROUCH, + L4D2_ACT_CROUCHIDLE, + L4D2_ACT_STAND, + L4D2_ACT_USE, + L4D2_ACT_SIGNAL1, + L4D2_ACT_SIGNAL2, + L4D2_ACT_SIGNAL3, + L4D2_ACT_SIGNAL_ADVANCE, + L4D2_ACT_SIGNAL_FORWARD, + L4D2_ACT_SIGNAL_GROUP, + L4D2_ACT_SIGNAL_HALT, + L4D2_ACT_SIGNAL_LEFT, + L4D2_ACT_SIGNAL_RIGHT, + L4D2_ACT_SIGNAL_TAKECOVER, + L4D2_ACT_LOOKBACK_RIGHT, + L4D2_ACT_LOOKBACK_LEFT, + L4D2_ACT_COWER, + L4D2_ACT_SMALL_FLINCH, + L4D2_ACT_BIG_FLINCH, + L4D2_ACT_MELEE_ATTACK1, + L4D2_ACT_MELEE_ATTACK2, + L4D2_ACT_RELOAD, + L4D2_ACT_RELOAD_START, + L4D2_ACT_RELOAD_FINISH, + L4D2_ACT_RELOAD_LOW, + L4D2_ACT_ARM, + L4D2_ACT_DISARM, + L4D2_ACT_DROP_WEAPON, + L4D2_ACT_DROP_WEAPON_SHOTGUN, + L4D2_ACT_PICKUP_GROUND, + L4D2_ACT_PICKUP_RACK, + L4D2_ACT_IDLE_ANGRY, + L4D2_ACT_IDLE_RELAXED, + L4D2_ACT_IDLE_STIMULATED, + L4D2_ACT_IDLE_AGITATED, + L4D2_ACT_IDLE_STEALTH, + L4D2_ACT_IDLE_HURT, + L4D2_ACT_WALK_RELAXED, + L4D2_ACT_WALK_STIMULATED, + L4D2_ACT_WALK_AGITATED, + L4D2_ACT_WALK_STEALTH, + L4D2_ACT_RUN_RELAXED, + L4D2_ACT_RUN_STIMULATED, + L4D2_ACT_RUN_AGITATED, + L4D2_ACT_RUN_STEALTH, + L4D2_ACT_IDLE_AIM_RELAXED, + L4D2_ACT_IDLE_AIM_STIMULATED, + L4D2_ACT_IDLE_AIM_AGITATED, + L4D2_ACT_IDLE_AIM_STEALTH, + L4D2_ACT_WALK_AIM_RELAXED, + L4D2_ACT_WALK_AIM_STIMULATED, + L4D2_ACT_WALK_AIM_AGITATED, + L4D2_ACT_WALK_AIM_STEALTH, + L4D2_ACT_RUN_AIM_RELAXED, + L4D2_ACT_RUN_AIM_STIMULATED, + L4D2_ACT_RUN_AIM_AGITATED, + L4D2_ACT_RUN_AIM_STEALTH, + L4D2_ACT_CROUCHIDLE_STIMULATED, + L4D2_ACT_CROUCHIDLE_AIM_STIMULATED, + L4D2_ACT_CROUCHIDLE_AGITATED, + L4D2_ACT_WALK_HURT, + L4D2_ACT_RUN_HURT, + L4D2_ACT_SPECIAL_ATTACK1, + L4D2_ACT_SPECIAL_ATTACK2, + L4D2_ACT_COMBAT_IDLE, + L4D2_ACT_WALK_SCARED, + L4D2_ACT_RUN_SCARED, + L4D2_ACT_VICTORY_DANCE, + L4D2_ACT_DIE_HEADSHOT, + L4D2_ACT_DIE_CHESTSHOT, + L4D2_ACT_DIE_GUTSHOT, + L4D2_ACT_DIE_BACKSHOT, + L4D2_ACT_FLINCH_HEAD, + L4D2_ACT_FLINCH_CHEST, + L4D2_ACT_FLINCH_STOMACH, + L4D2_ACT_FLINCH_LEFTARM, + L4D2_ACT_FLINCH_RIGHTARM, + L4D2_ACT_FLINCH_LEFTLEG, + L4D2_ACT_FLINCH_RIGHTLEG, + L4D2_ACT_FLINCH_PHYSICS, + L4D2_ACT_FLINCH_HEAD_BACK, + L4D2_ACT_FLINCH_CHEST_BACK, + L4D2_ACT_FLINCH_STOMACH_BACK, + L4D2_ACT_FLINCH_CROUCH_FRONT, + L4D2_ACT_FLINCH_CROUCH_BACK, + L4D2_ACT_FLINCH_CROUCH_LEFT, + L4D2_ACT_FLINCH_CROUCH_RIGHT, + L4D2_ACT_IDLE_ON_FIRE, + L4D2_ACT_WALK_ON_FIRE, + L4D2_ACT_RUN_ON_FIRE, + L4D2_ACT_RAPPEL_LOOP, + L4D2_ACT_180_LEFT, + L4D2_ACT_180_RIGHT, + L4D2_ACT_90_LEFT, + L4D2_ACT_90_RIGHT, + L4D2_ACT_STEP_LEFT, + L4D2_ACT_STEP_RIGHT, + L4D2_ACT_STEP_BACK, + L4D2_ACT_STEP_FORE, + L4D2_ACT_GESTURE_RANGE_ATTACK1, + L4D2_ACT_GESTURE_RANGE_ATTACK2, + L4D2_ACT_GESTURE_MELEE_ATTACK1, + L4D2_ACT_GESTURE_MELEE_ATTACK2, + L4D2_ACT_GESTURE_RANGE_ATTACK1_LOW, + L4D2_ACT_GESTURE_RANGE_ATTACK2_LOW, + L4D2_ACT_MELEE_ATTACK_SWING_GESTURE, + L4D2_ACT_GESTURE_SMALL_FLINCH, + L4D2_ACT_GESTURE_BIG_FLINCH, + L4D2_ACT_GESTURE_FLINCH_BLAST, + L4D2_ACT_GESTURE_FLINCH_BLAST_SHOTGUN, + L4D2_ACT_GESTURE_FLINCH_BLAST_DAMAGED, + L4D2_ACT_GESTURE_FLINCH_BLAST_DAMAGED_SHOTGUN, + L4D2_ACT_GESTURE_FLINCH_HEAD, + L4D2_ACT_GESTURE_FLINCH_CHEST, + L4D2_ACT_GESTURE_FLINCH_STOMACH, + L4D2_ACT_GESTURE_FLINCH_LEFTARM, + L4D2_ACT_GESTURE_FLINCH_RIGHTARM, + L4D2_ACT_GESTURE_FLINCH_LEFTLEG, + L4D2_ACT_GESTURE_FLINCH_RIGHTLEG, + L4D2_ACT_GESTURE_TURN_LEFT, + L4D2_ACT_GESTURE_TURN_RIGHT, + L4D2_ACT_GESTURE_TURN_LEFT45, + L4D2_ACT_GESTURE_TURN_RIGHT45, + L4D2_ACT_GESTURE_TURN_LEFT90, + L4D2_ACT_GESTURE_TURN_RIGHT90, + L4D2_ACT_GESTURE_TURN_LEFT45_FLAT, + L4D2_ACT_GESTURE_TURN_RIGHT45_FLAT, + L4D2_ACT_GESTURE_TURN_LEFT90_FLAT, + L4D2_ACT_GESTURE_TURN_RIGHT90_FLAT, + L4D2_ACT_BARNACLE_HIT, + L4D2_ACT_BARNACLE_PULL, + L4D2_ACT_BARNACLE_CHOMP, + L4D2_ACT_BARNACLE_CHEW, + L4D2_ACT_DO_NOT_DISTURB, + L4D2_ACT_SPECIFIC_SEQUENCE, + L4D2_ACT_VM_DEPLOY, + L4D2_ACT_VM_RELOAD_EMPTY, + L4D2_ACT_VM_DRAW, + L4D2_ACT_VM_HOLSTER, + L4D2_ACT_VM_IDLE, + L4D2_ACT_VM_FIDGET, + L4D2_ACT_VM_PULLBACK, + L4D2_ACT_VM_PULLBACK_HIGH, + L4D2_ACT_VM_PULLBACK_LOW, + L4D2_ACT_VM_THROW, + L4D2_ACT_VM_DROP, + L4D2_ACT_VM_PULLPIN, + L4D2_ACT_VM_PRIMARYATTACK, + L4D2_ACT_VM_SECONDARYATTACK, + L4D2_ACT_VM_RELOAD, + L4D2_ACT_VM_DRYFIRE, + L4D2_ACT_VM_HITLEFT, + L4D2_ACT_VM_HITLEFT2, + L4D2_ACT_VM_HITRIGHT, + L4D2_ACT_VM_HITRIGHT2, + L4D2_ACT_VM_HITCENTER, + L4D2_ACT_VM_HITCENTER2, + L4D2_ACT_VM_MISSLEFT, + L4D2_ACT_VM_MISSLEFT2, + L4D2_ACT_VM_MISSRIGHT, + L4D2_ACT_VM_MISSRIGHT2, + L4D2_ACT_VM_MISSCENTER, + L4D2_ACT_VM_MISSCENTER2, + L4D2_ACT_VM_HAULBACK, + L4D2_ACT_VM_SWINGHARD, + L4D2_ACT_VM_SWINGMISS, + L4D2_ACT_VM_SWINGHIT, + L4D2_ACT_VM_IDLE_TO_LOWERED, + L4D2_ACT_VM_IDLE_LOWERED, + L4D2_ACT_VM_LOWERED_TO_IDLE, + L4D2_ACT_VM_RECOIL1, + L4D2_ACT_VM_RECOIL2, + L4D2_ACT_VM_RECOIL3, + L4D2_ACT_VM_PICKUP, + L4D2_ACT_VM_RELEASE, + L4D2_ACT_VM_MAUL_LOOP, + L4D2_ACT_VM_ATTACH_SILENCER, + L4D2_ACT_VM_DETACH_SILENCER, + L4D2_ACT_SLAM_STICKWALL_IDLE, + L4D2_ACT_SLAM_STICKWALL_ND_IDLE, + L4D2_ACT_SLAM_STICKWALL_ATTACH, + L4D2_ACT_SLAM_STICKWALL_ATTACH2, + L4D2_ACT_SLAM_STICKWALL_ND_ATTACH, + L4D2_ACT_SLAM_STICKWALL_ND_ATTACH2, + L4D2_ACT_SLAM_STICKWALL_DETONATE, + L4D2_ACT_SLAM_STICKWALL_DETONATOR_HOLSTER, + L4D2_ACT_SLAM_STICKWALL_DRAW, + L4D2_ACT_SLAM_STICKWALL_ND_DRAW, + L4D2_ACT_SLAM_STICKWALL_TO_THROW, + L4D2_ACT_SLAM_STICKWALL_TO_THROW_ND, + L4D2_ACT_SLAM_STICKWALL_TO_TRIPMINE_ND, + L4D2_ACT_SLAM_THROW_IDLE, + L4D2_ACT_SLAM_THROW_ND_IDLE, + L4D2_ACT_SLAM_THROW_THROW, + L4D2_ACT_SLAM_THROW_THROW2, + L4D2_ACT_SLAM_THROW_THROW_ND, + L4D2_ACT_SLAM_THROW_THROW_ND2, + L4D2_ACT_SLAM_THROW_DRAW, + L4D2_ACT_SLAM_THROW_ND_DRAW, + L4D2_ACT_SLAM_THROW_TO_STICKWALL, + L4D2_ACT_SLAM_THROW_TO_STICKWALL_ND, + L4D2_ACT_SLAM_THROW_DETONATE, + L4D2_ACT_SLAM_THROW_DETONATOR_HOLSTER, + L4D2_ACT_SLAM_THROW_TO_TRIPMINE_ND, + L4D2_ACT_SLAM_TRIPMINE_IDLE, + L4D2_ACT_SLAM_TRIPMINE_DRAW, + L4D2_ACT_SLAM_TRIPMINE_ATTACH, + L4D2_ACT_SLAM_TRIPMINE_ATTACH2, + L4D2_ACT_SLAM_TRIPMINE_TO_STICKWALL_ND, + L4D2_ACT_SLAM_TRIPMINE_TO_THROW_ND, + L4D2_ACT_SLAM_DETONATOR_IDLE, + L4D2_ACT_SLAM_DETONATOR_DRAW, + L4D2_ACT_SLAM_DETONATOR_DETONATE, + L4D2_ACT_SLAM_DETONATOR_HOLSTER, + L4D2_ACT_SLAM_DETONATOR_STICKWALL_DRAW, + L4D2_ACT_SLAM_DETONATOR_THROW_DRAW, + L4D2_ACT_SHOTGUN_RELOAD_START, + L4D2_ACT_SHOTGUN_RELOAD_FINISH, + L4D2_ACT_SHOTGUN_PUMP, + L4D2_ACT_SMG2_IDLE2, + L4D2_ACT_SMG2_FIRE2, + L4D2_ACT_SMG2_DRAW2, + L4D2_ACT_SMG2_RELOAD2, + L4D2_ACT_SMG2_DRYFIRE2, + L4D2_ACT_SMG2_TOAUTO, + L4D2_ACT_SMG2_TOBURST, + L4D2_ACT_PHYSCANNON_UPGRADE, + L4D2_ACT_RANGE_ATTACK_AR1, + L4D2_ACT_RANGE_ATTACK_AR2, + L4D2_ACT_RANGE_ATTACK_AR2_LOW, + L4D2_ACT_RANGE_ATTACK_AR2_GRENADE, + L4D2_ACT_RANGE_ATTACK_HMG1, + L4D2_ACT_RANGE_ATTACK_ML, + L4D2_ACT_RANGE_ATTACK_SMG1, + L4D2_ACT_RANGE_ATTACK_SMG1_LOW, + L4D2_ACT_RANGE_ATTACK_SMG2, + L4D2_ACT_RANGE_ATTACK_SHOTGUN, + L4D2_ACT_RANGE_ATTACK_SHOTGUN_LOW, + L4D2_ACT_RANGE_ATTACK_PISTOL, + L4D2_ACT_RANGE_ATTACK_PISTOL_LOW, + L4D2_ACT_RANGE_ATTACK_SLAM, + L4D2_ACT_RANGE_ATTACK_TRIPWIRE, + L4D2_ACT_RANGE_ATTACK_THROW, + L4D2_ACT_RANGE_ATTACK_SNIPER_RIFLE, + L4D2_ACT_RANGE_ATTACK_RPG, + L4D2_ACT_MELEE_ATTACK_SWING, + L4D2_ACT_RANGE_AIM_LOW, + L4D2_ACT_RANGE_AIM_SMG1_LOW, + L4D2_ACT_RANGE_AIM_PISTOL_LOW, + L4D2_ACT_RANGE_AIM_AR2_LOW, + L4D2_ACT_COVER_PISTOL_LOW, + L4D2_ACT_COVER_SMG1_LOW, + L4D2_ACT_GESTURE_RANGE_ATTACK_AR1, + L4D2_ACT_GESTURE_RANGE_ATTACK_AR2, + L4D2_ACT_GESTURE_RANGE_ATTACK_AR2_GRENADE, + L4D2_ACT_GESTURE_RANGE_ATTACK_HMG1, + L4D2_ACT_GESTURE_RANGE_ATTACK_ML, + L4D2_ACT_GESTURE_RANGE_ATTACK_SMG1, + L4D2_ACT_GESTURE_RANGE_ATTACK_SMG1_LOW, + L4D2_ACT_GESTURE_RANGE_ATTACK_SMG2, + L4D2_ACT_GESTURE_RANGE_ATTACK_SHOTGUN, + L4D2_ACT_GESTURE_RANGE_ATTACK_PISTOL, + L4D2_ACT_GESTURE_RANGE_ATTACK_PISTOL_LOW, + L4D2_ACT_GESTURE_RANGE_ATTACK_SLAM, + L4D2_ACT_GESTURE_RANGE_ATTACK_TRIPWIRE, + L4D2_ACT_GESTURE_RANGE_ATTACK_THROW, + L4D2_ACT_GESTURE_RANGE_ATTACK_SNIPER_RIFLE, + L4D2_ACT_GESTURE_MELEE_ATTACK_SWING, + L4D2_ACT_IDLE_RIFLE, + L4D2_ACT_IDLE_SMG1, + L4D2_ACT_IDLE_ANGRY_SMG1, + L4D2_ACT_IDLE_PISTOL, + L4D2_ACT_IDLE_ANGRY_PISTOL, + L4D2_ACT_IDLE_ANGRY_SHOTGUN, + L4D2_ACT_IDLE_STEALTH_PISTOL, + L4D2_ACT_IDLE_PACKAGE, + L4D2_ACT_WALK_PACKAGE, + L4D2_ACT_IDLE_SUITCASE, + L4D2_ACT_WALK_SUITCASE, + L4D2_ACT_IDLE_SMG1_RELAXED, + L4D2_ACT_IDLE_SMG1_STIMULATED, + L4D2_ACT_WALK_RIFLE_RELAXED, + L4D2_ACT_RUN_RIFLE_RELAXED, + L4D2_ACT_WALK_RIFLE_STIMULATED, + L4D2_ACT_RUN_RIFLE_STIMULATED, + L4D2_ACT_IDLE_AIM_RIFLE_STIMULATED, + L4D2_ACT_WALK_AIM_RIFLE_STIMULATED, + L4D2_ACT_RUN_AIM_RIFLE_STIMULATED, + L4D2_ACT_IDLE_SHOTGUN_RELAXED, + L4D2_ACT_IDLE_SHOTGUN_STIMULATED, + L4D2_ACT_IDLE_SHOTGUN_AGITATED, + L4D2_ACT_WALK_ANGRY, + L4D2_ACT_POLICE_HARASS1, + L4D2_ACT_POLICE_HARASS2, + L4D2_ACT_IDLE_MANNEDGUN, + L4D2_ACT_IDLE_MELEE, + L4D2_ACT_IDLE_ANGRY_MELEE, + L4D2_ACT_IDLE_RPG_RELAXED, + L4D2_ACT_IDLE_RPG, + L4D2_ACT_IDLE_ANGRY_RPG, + L4D2_ACT_COVER_LOW_RPG, + L4D2_ACT_WALK_RPG, + L4D2_ACT_RUN_RPG, + L4D2_ACT_WALK_CROUCH_RPG, + L4D2_ACT_RUN_CROUCH_RPG, + L4D2_ACT_WALK_RPG_RELAXED, + L4D2_ACT_RUN_RPG_RELAXED, + L4D2_ACT_WALK_RIFLE, + L4D2_ACT_WALK_AIM_RIFLE, + L4D2_ACT_WALK_CROUCH_RIFLE, + L4D2_ACT_WALK_CROUCH_AIM_RIFLE, + L4D2_ACT_RUN_RIFLE, + L4D2_ACT_RUN_AIM_RIFLE, + L4D2_ACT_RUN_CROUCH_RIFLE, + L4D2_ACT_RUN_CROUCH_AIM_RIFLE, + L4D2_ACT_RUN_STEALTH_PISTOL, + L4D2_ACT_WALK_AIM_SHOTGUN, + L4D2_ACT_RUN_AIM_SHOTGUN, + L4D2_ACT_WALK_PISTOL, + L4D2_ACT_RUN_PISTOL, + L4D2_ACT_WALK_AIM_PISTOL, + L4D2_ACT_RUN_AIM_PISTOL, + L4D2_ACT_WALK_STEALTH_PISTOL, + L4D2_ACT_WALK_AIM_STEALTH_PISTOL, + L4D2_ACT_RUN_AIM_STEALTH_PISTOL, + L4D2_ACT_RELOAD_PISTOL, + L4D2_ACT_RELOAD_PISTOL_LOW, + L4D2_ACT_RELOAD_SMG1, + L4D2_ACT_RELOAD_SMG1_LOW, + L4D2_ACT_RELOAD_SHOTGUN, + L4D2_ACT_RELOAD_SHOTGUN_LOW, + L4D2_ACT_GESTURE_RELOAD, + L4D2_ACT_GESTURE_RELOAD_PISTOL, + L4D2_ACT_GESTURE_RELOAD_SMG1, + L4D2_ACT_GESTURE_RELOAD_SHOTGUN, + L4D2_ACT_BUSY_LEAN_LEFT, + L4D2_ACT_BUSY_LEAN_LEFT_ENTRY, + L4D2_ACT_BUSY_LEAN_LEFT_EXIT, + L4D2_ACT_BUSY_LEAN_BACK, + L4D2_ACT_BUSY_LEAN_BACK_ENTRY, + L4D2_ACT_BUSY_LEAN_BACK_EXIT, + L4D2_ACT_BUSY_SIT_GROUND, + L4D2_ACT_BUSY_SIT_GROUND_ENTRY, + L4D2_ACT_BUSY_SIT_GROUND_EXIT, + L4D2_ACT_BUSY_SIT_CHAIR, + L4D2_ACT_BUSY_SIT_CHAIR_ENTRY, + L4D2_ACT_BUSY_SIT_CHAIR_EXIT, + L4D2_ACT_BUSY_STAND, + L4D2_ACT_BUSY_QUEUE, + L4D2_ACT_DUCK_DODGE, + L4D2_ACT_DIE_BARNACLE_SWALLOW, + L4D2_ACT_GESTURE_BARNACLE_STRANGLE, + L4D2_ACT_PHYSCANNON_DETACH, + L4D2_ACT_PHYSCANNON_ANIMATE, + L4D2_ACT_PHYSCANNON_ANIMATE_PRE, + L4D2_ACT_PHYSCANNON_ANIMATE_POST, + L4D2_ACT_DIE_FRONTSIDE, + L4D2_ACT_DIE_RIGHTSIDE, + L4D2_ACT_DIE_BACKSIDE, + L4D2_ACT_DIE_LEFTSIDE, + L4D2_ACT_DIE_CROUCH_FRONTSIDE, + L4D2_ACT_DIE_CROUCH_RIGHTSIDE, + L4D2_ACT_DIE_CROUCH_BACKSIDE, + L4D2_ACT_DIE_CROUCH_LEFTSIDE, + L4D2_ACT_DIE_INCAP, + L4D2_ACT_DIE_STANDING, + L4D2_ACT_OPEN_DOOR, + L4D2_ACT_DI_ALYX_ZOMBIE_MELEE, + L4D2_ACT_DI_ALYX_ZOMBIE_TORSO_MELEE, + L4D2_ACT_DI_ALYX_HEADCRAB_MELEE, + L4D2_ACT_DI_ALYX_ANTLION, + L4D2_ACT_DI_ALYX_ZOMBIE_SHOTGUN64, + L4D2_ACT_DI_ALYX_ZOMBIE_SHOTGUN26, + L4D2_ACT_READINESS_RELAXED_TO_STIMULATED, + L4D2_ACT_READINESS_RELAXED_TO_STIMULATED_WALK, + L4D2_ACT_READINESS_AGITATED_TO_STIMULATED, + L4D2_ACT_READINESS_STIMULATED_TO_RELAXED, + L4D2_ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED, + L4D2_ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED_WALK, + L4D2_ACT_READINESS_PISTOL_AGITATED_TO_STIMULATED, + L4D2_ACT_READINESS_PISTOL_STIMULATED_TO_RELAXED, + L4D2_ACT_IDLE_CARRY, + L4D2_ACT_WALK_CARRY, + L4D2_ACT_STARTDYING, + L4D2_ACT_DYINGLOOP, + L4D2_ACT_DYINGTODEAD, + L4D2_ACT_RIDE_MANNED_GUN, + L4D2_ACT_VM_SPRINT_ENTER, + L4D2_ACT_VM_SPRINT_IDLE, + L4D2_ACT_VM_SPRINT_LEAVE, + L4D2_ACT_FIRE_START, + L4D2_ACT_FIRE_LOOP, + L4D2_ACT_FIRE_END, + L4D2_ACT_CROUCHING_GRENADEIDLE, + L4D2_ACT_CROUCHING_GRENADEREADY, + L4D2_ACT_CROUCHING_PRIMARYATTACK, + L4D2_ACT_OVERLAY_GRENADEIDLE, + L4D2_ACT_OVERLAY_GRENADEREADY, + L4D2_ACT_OVERLAY_PRIMARYATTACK, + L4D2_ACT_OVERLAY_SHIELD_UP, + L4D2_ACT_OVERLAY_SHIELD_DOWN, + L4D2_ACT_OVERLAY_SHIELD_UP_IDLE, + L4D2_ACT_OVERLAY_SHIELD_ATTACK, + L4D2_ACT_OVERLAY_SHIELD_KNOCKBACK, + L4D2_ACT_SHIELD_UP, + L4D2_ACT_SHIELD_DOWN, + L4D2_ACT_SHIELD_UP_IDLE, + L4D2_ACT_SHIELD_ATTACK, + L4D2_ACT_SHIELD_KNOCKBACK, + L4D2_ACT_CROUCHING_SHIELD_UP, + L4D2_ACT_CROUCHING_SHIELD_DOWN, + L4D2_ACT_CROUCHING_SHIELD_UP_IDLE, + L4D2_ACT_CROUCHING_SHIELD_ATTACK, + L4D2_ACT_CROUCHING_SHIELD_KNOCKBACK, + L4D2_ACT_TURNRIGHT45, + L4D2_ACT_TURNLEFT45, + L4D2_ACT_TURN, + L4D2_ACT_OBJ_ASSEMBLING, + L4D2_ACT_OBJ_DISMANTLING, + L4D2_ACT_OBJ_STARTUP, + L4D2_ACT_OBJ_RUNNING, + L4D2_ACT_OBJ_IDLE, + L4D2_ACT_OBJ_PLACING, + L4D2_ACT_OBJ_DETERIORATING, + L4D2_ACT_OBJ_UPGRADING, + L4D2_ACT_DEPLOY, + L4D2_ACT_DEPLOY_IDLE, + L4D2_ACT_UNDEPLOY, + L4D2_ACT_CROSSBOW_DRAW_UNLOADED, + L4D2_ACT_GAUSS_SPINUP, + L4D2_ACT_GAUSS_SPINCYCLE, + L4D2_ACT_VM_PRIMARYATTACK_SILENCED, + L4D2_ACT_VM_RELOAD_SILENCED, + L4D2_ACT_VM_DRYFIRE_SILENCED, + L4D2_ACT_VM_IDLE_SILENCED, + L4D2_ACT_VM_DRAW_SILENCED, + L4D2_ACT_VM_IDLE_EMPTY_LEFT, + L4D2_ACT_VM_DRYFIRE_LEFT, + L4D2_ACT_VM_IS_DRAW, + L4D2_ACT_VM_IS_HOLSTER, + L4D2_ACT_VM_IS_IDLE, + L4D2_ACT_VM_IS_PRIMARYATTACK, + L4D2_ACT_PLAYER_IDLE_FIRE, + L4D2_ACT_PLAYER_CROUCH_FIRE, + L4D2_ACT_PLAYER_CROUCH_WALK_FIRE, + L4D2_ACT_PLAYER_WALK_FIRE, + L4D2_ACT_PLAYER_RUN_FIRE, + L4D2_ACT_IDLETORUN, + L4D2_ACT_RUNTOIDLE, + L4D2_ACT_VM_DRAW_DEPLOYED, + L4D2_ACT_HL2MP_IDLE_MELEE, + L4D2_ACT_HL2MP_RUN_MELEE, + L4D2_ACT_HL2MP_IDLE_CROUCH_MELEE, + L4D2_ACT_HL2MP_WALK_CROUCH_MELEE, + L4D2_ACT_HL2MP_GESTURE_RANGE_ATTACK_MELEE, + L4D2_ACT_HL2MP_GESTURE_RELOAD_MELEE, + L4D2_ACT_HL2MP_JUMP_MELEE, + L4D2_ACT_VM_SHRIEK, + L4D2_ACT_VM_VOMIT, + L4D2_ACT_VM_COUGH, + L4D2_ACT_VM_LUNGE, + L4D2_ACT_VM_PUMMEL_ATTACK, + L4D2_ACT_VM_IDLE2REV, + L4D2_ACT_VM_REV2IDLE, + L4D2_ACT_IDLE_INJURED, + L4D2_ACT_IDLE_INCAP, + L4D2_ACT_WALK_INJURED, + L4D2_ACT_RUN_INJURED, + L4D2_ACT_IDLE_CALM, + L4D2_ACT_WALK_CALM, + L4D2_ACT_RUN_CALM, + L4D2_ACT_JUMP_SHOTGUN, + L4D2_ACT_JUMP_RIFLE, + L4D2_ACT_JUMP_SMG, + L4D2_ACT_JUMP_PISTOL, + L4D2_ACT_JUMP_DUAL_PISTOL, + L4D2_ACT_JUMP_ITEM, + L4D2_ACT_TERROR_HIT_BY_TANKPUNCH, + L4D2_ACT_TERROR_IDLE_FALL_FROM_TANKPUNCH, + L4D2_ACT_TERROR_TANKPUNCH_LAND, + L4D2_ACT_TERROR_HIT_BY_CHARGER, + L4D2_ACT_TERROR_IDLE_FALL_FROM_CHARGERHIT, + L4D2_ACT_TERROR_CHARGERHIT_LAND_SLOW, + L4D2_ACT_TERROR_CHARGER_PUMMELED, + L4D2_ACT_TERROR_CARRIED, + L4D2_ACT_TERROR_SLAMMED_WALL, + L4D2_ACT_TERROR_SLAMMED_GROUND, + L4D2_ACT_TERROR_CHARGER_POUNDED_NORTH, + L4D2_ACT_TERROR_CHARGER_POUNDED_UP, + L4D2_ACT_TERROR_CHARGER_POUNDED_INCAP, + L4D2_ACT_TERROR_CHARGER_POUNDED_DOWN, + L4D2_ACT_TERROR_CHARGER_PUMMEL, + L4D2_ACT_TERROR_SLAM_GROUND, + L4D2_ACT_TERROR_CHARGER_POUND_NORTH, + L4D2_ACT_TERROR_CHARGER_POUND_UP, + L4D2_ACT_TERROR_CHARGER_POUND_DOWN_PRODUCER, + L4D2_ACT_TERROR_CHARGER_POUND_DOWN_COACH, + L4D2_ACT_TERROR_CHARGER_POUND_DOWN, + L4D2_ACT_TERROR_PUMMELED_LOOP, + L4D2_ACT_TERROR_SPITTER_SPIT, + L4D2_ACT_TERROR_HEAL_SELF, + L4D2_ACT_TERROR_HEAL_FRIEND, + L4D2_ACT_TERROR_HEAL_INCAPACITATED, + L4D2_ACT_TERROR_CROUCH_HEAL_SELF, + L4D2_ACT_TERROR_CROUCH_HEAL_FRIEND, + L4D2_ACT_TERROR_CROUCH_HEAL_INCAPACITATED, + L4D2_ACT_TERROR_HEAL_INCAPACITATED_ABOVE, + L4D2_ACT_TERROR_CROUCH_HEAL_INCAPACITATED_ABOVE, + L4D2_ACT_TERROR_USE_PILLS, + L4D2_ACT_TERROR_USE_ADRENALINE, + L4D2_ACT_TERROR_USE_ADRENALINE_CROUCHING, + L4D2_ACT_TERROR_USE_DEFIBRILLATOR, + L4D2_ACT_TERROR_CROUCH_USE_DEFIBRILLATOR, + L4D2_ACT_TERROR_REVIVE_FROM_DEATH, + L4D2_ACT_TERROR_DEFIBRILLATOR_SHOCK, + L4D2_ACT_TERROR_USE_UPGRADEPACK, + L4D2_ACT_TERROR_CROUCH_USE_UPGRADEPACK, + L4D2_ACT_TERROR_USE_GAS_CAN, + L4D2_ACT_TERROR_USE_COLA, + L4D2_ACT_TERROR_IDLE_NEUTRAL, + L4D2_ACT_TERROR_IDLE_ALERT, + L4D2_ACT_TERROR_IDLE_INTENSE, + L4D2_ACT_TERROR_IDLE_ALERT_INJURED_AHEAD, + L4D2_ACT_TERROR_IDLE_ALERT_AHEAD, + L4D2_ACT_TERROR_IDLE_ALERT_INJURED_BEHIND, + L4D2_ACT_TERROR_IDLE_ALERT_BEHIND, + L4D2_ACT_TERROR_IDLE_ALERT_INJURED_LEFT, + L4D2_ACT_TERROR_IDLE_ALERT_LEFT, + L4D2_ACT_TERROR_IDLE_ALERT_INJURED_RIGHT, + L4D2_ACT_TERROR_IDLE_ALERT_RIGHT, + L4D2_ACT_TERROR_IDLE_ACQUIRE, + L4D2_ACT_TERROR_LEAN_FORWARD_IDLE, + L4D2_ACT_TERROR_LEAN_BACKWARD_IDLE, + L4D2_ACT_TERROR_LEAN_LEFTWARD_IDLE, + L4D2_ACT_TERROR_LEAN_RIGHTWARD_IDLE, + L4D2_ACT_TERROR_FIDGET, + L4D2_ACT_TERROR_NEUTRAL_TO_ALERT, + L4D2_ACT_TERROR_ALERT_TO_NEUTRAL, + L4D2_ACT_TERROR_FACE_LEFT_NEUTRAL, + L4D2_ACT_TERROR_FACE_LEFT_ALERT, + L4D2_ACT_TERROR_FACE_LEFT_INTENSE, + L4D2_ACT_TERROR_FACE_RIGHT_NEUTRAL, + L4D2_ACT_TERROR_FACE_RIGHT_ALERT, + L4D2_ACT_TERROR_FACE_RIGHT_INTENSE, + L4D2_ACT_TERROR_ABOUT_FACE_NEUTRAL, + L4D2_ACT_TERROR_ABOUT_FACE_ALERT, + L4D2_ACT_TERROR_ABOUT_FACE_INTENSE, + L4D2_ACT_TERROR_SHAMBLE, + L4D2_ACT_TERROR_WALK_NEUTRAL, + L4D2_ACT_TERROR_WALK_ALERT, + L4D2_ACT_TERROR_WALK_INTENSE, + L4D2_ACT_TERROR_RUN_NEUTRAL, + L4D2_ACT_TERROR_RUN_ALERT, + L4D2_ACT_TERROR_RUN_INTENSE, + L4D2_ACT_TERROR_RUN_ON_FIRE_INTENSE, + L4D2_ACT_TERROR_RUN_INTENSE_TO_STAND_ALERT, + L4D2_ACT_TERROR_CROUCH_IDLE_NEUTRAL, + L4D2_ACT_TERROR_CROUCH_IDLE_ALERT, + L4D2_ACT_TERROR_CROUCH_IDLE_INTENSE, + L4D2_ACT_TERROR_CROUCH_WALK_NEUTRAL, + L4D2_ACT_TERROR_CROUCH_WALK_ALERT, + L4D2_ACT_TERROR_CROUCH_WALK_INTENSE, + L4D2_ACT_TERROR_CROUCH_RUN_NEUTRAL, + L4D2_ACT_TERROR_CROUCH_RUN_ALERT, + L4D2_ACT_TERROR_CROUCH_RUN_INTENSE, + L4D2_ACT_TERROR_CRAWL_RUN, + L4D2_ACT_TERROR_IDLE_ON_FIRE, + L4D2_ACT_TERROR_WALK_ON_FIRE, + L4D2_ACT_TERROR_RUN_ON_FIRE, + L4D2_ACT_TERROR_ATTACK, + L4D2_ACT_TERROR_ATTACK_CONTINUOUSLY, + L4D2_ACT_TERROR_ATTACK_LOW, + L4D2_ACT_TERROR_ATTACK_LOW_CONTINUOUSLY, + L4D2_ACT_TERROR_ATTACK_DOOR, + L4D2_ACT_TERROR_ATTACK_DOOR_CONTINUOUSLY, + L4D2_ACT_TERROR_UNABLE_TO_REACH_TARGET, + L4D2_ACT_TERROR_REACH_THROUGH_DOOR, + L4D2_ACT_TERROR_SHOVED_FORWARD, + L4D2_ACT_TERROR_SHOVED_BACKWARD, + L4D2_ACT_TERROR_SHOVED_LEFTWARD, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD, + L4D2_ACT_TERROR_SHOVED_FORWARD_CHAINSAW, + L4D2_ACT_TERROR_SHOVED_BACKWARD_CHAINSAW, + L4D2_ACT_TERROR_SHOVED_LEFTWARD_CHAINSAW, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD_CHAINSAW, + L4D2_ACT_TERROR_SHOVED_FORWARD_BAT, + L4D2_ACT_TERROR_SHOVED_BACKWARD_BAT, + L4D2_ACT_TERROR_SHOVED_LEFTWARD_BAT, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD_BAT, + L4D2_ACT_TERROR_SHOVED_FORWARD_MELEE, + L4D2_ACT_TERROR_SHOVED_BACKWARD_MELEE, + L4D2_ACT_TERROR_SHOVED_LEFTWARD_MELEE, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD_MELEE, + L4D2_ACT_TERROR_SHOVED_BACKWARD_INTO_WALL, + L4D2_ACT_TERROR_SHOVED_FORWARD_INTO_WALL, + L4D2_ACT_TERROR_SHOVED_LEFTWARD_INTO_WALL, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD_INTO_WALL, + L4D2_ACT_TERROR_SHOVED_BACKWARD_FROM_SIT, + L4D2_ACT_TERROR_SHOVED_RIGHTWARD_FROM_SIT, + L4D2_ACT_TERROR_SHOVED_LEFTWARD_FROM_SIT, + L4D2_ACT_TERROR_TUGGED_FORWARD, + L4D2_ACT_TERROR_TUGGED_BACKWARD, + L4D2_ACT_TERROR_TUGGED_LEFTWARD, + L4D2_ACT_TERROR_TUGGED_RIGHTWARD, + L4D2_ACT_TERROR_SIT_IDLE, + L4D2_ACT_TERROR_SIT_FROM_STAND, + L4D2_ACT_TERROR_SIT_TO_STAND, + L4D2_ACT_TERROR_SIT_TO_STAND_ALERT, + L4D2_ACT_TERROR_SIT_TO_LIE, + L4D2_ACT_TERROR_LIE_IDLE, + L4D2_ACT_TERROR_LIE_FROM_STAND, + L4D2_ACT_TERROR_LIE_TO_STAND, + L4D2_ACT_TERROR_LIE_TO_STAND_ALERT, + L4D2_ACT_TERROR_LIE_TO_SIT, + L4D2_ACT_TERROR_JUMP, + L4D2_ACT_TERROR_JUMP_UP_TO_LEDGE, + L4D2_ACT_TERROR_JUMP_DOWN_FROM_LEDGE, + L4D2_ACT_TERROR_JUMP_OVER_GAP, + L4D2_ACT_TERROR_JUMP_LANDING, + L4D2_ACT_TERROR_JUMP_LANDING_HARD, + L4D2_ACT_TERROR_JUMP_LANDING_NEUTRAL, + L4D2_ACT_TERROR_JUMP_LANDING_HARD_NEUTRAL, + L4D2_ACT_TERROR_FALL, + L4D2_ACT_TERROR_DIE_FROM_STAND, + L4D2_ACT_TERROR_DIE_FROM_CROUCH, + L4D2_ACT_TERROR_DIE_WHILE_RUNNING, + L4D2_ACT_TERROR_DIE_BACKWARD_FROM_SHOTGUN, + L4D2_ACT_TERROR_DIE_FORWARD_FROM_SHOTGUN, + L4D2_ACT_TERROR_DIE_LEFTWARD_FROM_SHOTGUN, + L4D2_ACT_TERROR_DIE_RIGHTWARD_FROM_SHOTGUN, + L4D2_ACT_BLUDGEON_DEATH_BACK, + L4D2_ACT_BLUDGEON_DEATH_FORWARD, + L4D2_ACT_BLUDGEON_DEATH_LEFT, + L4D2_ACT_BLUDGEON_DEATH_RIGHT, + L4D2_ACT_SLICING_DEATH_BACK, + L4D2_ACT_SLICING_DEATH_FORWARD, + L4D2_ACT_SLICING_DEATH_LEFT, + L4D2_ACT_SLICING_DEATH_RIGHT, + L4D2_ACT_TERROR_WITCH_ANGRY, + L4D2_ACT_TERROR_WITCH_ANGRY_HIGH, + L4D2_ACT_TERROR_WITCH_IDLE, + L4D2_ACT_TERROR_WITCH_IDLE_PRE_RETREAT, + L4D2_ACT_TERROR_WITCH_RETREAT, + L4D2_ACT_TERROR_WITCH_KILL_DISPLAY, + L4D2_ACT_TERROR_WITCH_KILL_LOOP, + L4D2_ACT_TERROR_WITCH_WANDER_WALK, + L4D2_ACT_TERROR_WITCH_WANDER_IDLE, + L4D2_ACT_TERROR_WITCH_WANDER_ACQUIRE, + L4D2_ACT_TERROR_TUG, + L4D2_ACT_TERROR_FLINCH, + L4D2_ACT_TERROR_FLINCH_LEDGE, + L4D2_ACT_SECONDARYATTACK, + L4D2_ACT_TERROR_INCAP_CRAWL, + L4D2_ACT_TERROR_INCAP_TO_STAND, + L4D2_ACT_TERROR_INCAP_TO_CROUCH, + L4D2_ACT_TERROR_ITEM_PICKUP, + L4D2_ACT_IDLE_INCAP_PISTOL, + L4D2_ACT_IDLE_INCAP_ELITES, + L4D2_ACT_FALL, + L4D2_ACT_CALL_FOR_RESCUE, + L4D2_ACT_PUSH, + L4D2_ACT_IDLE_MINIGUN, + L4D2_ACT_PRIMARYATTACK_MINIGUN, + L4D2_ACT_GEST_HEAD_NOD, + L4D2_ACT_GEST_HEAD_YES, + L4D2_ACT_GEST_HEAD_NO, + L4D2_ACT_TERROR_LEDGE_CLIMB, + L4D2_ACT_TERROR_LEDGE_CLIMB_TO_CROUCH, + L4D2_ACT_TERROR_FALL_GRAB_LEDGE, + L4D2_ACT_TERROR_LEDGE_HANG_FIRM, + L4D2_ACT_TERROR_LEDGE_HANG_WEAK, + L4D2_ACT_TERROR_LEDGE_HANG_DANGLE, + L4D2_ACT_TERROR_IDLE_LADDER, + L4D2_ACT_TERROR_LADDER_DISMOUNT, + L4D2_ACT_TERROR_CLIMB_24_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_36_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_38_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_48_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_50_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_60_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_70_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_72_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_84_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_96_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_108_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_115_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_120_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_130_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_132_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_144_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_150_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_156_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_166_FROM_STAND, + L4D2_ACT_TERROR_CLIMB_168_FROM_STAND, + L4D2_ACT_TERROR_HUNTER_LUNGE_INTO_SURVIVOR, + L4D2_ACT_TERROR_HUNTER_LUNGE, + L4D2_ACT_TERROR_HUNTER_LUNGE_WHILE_RUNNING, + L4D2_ACT_TERROR_HUNTER_LANDING_HARD, + L4D2_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_SPIN_RIGHT, + L4D2_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_SPIN_LEFT, + L4D2_ACT_TERROR_HUNTER_LUNGE_OFF_WALL_BACK, + L4D2_ACT_TERROR_HUNTER_LUNGE_IDLE, + L4D2_ACT_TERROR_HUNTER_LUNGE_ONTO_WALL, + L4D2_ACT_TERROR_HUNTER_POUNCE, + L4D2_ACT_TERROR_HUNTER_POUNCE_IDLE, + L4D2_ACT_TERROR_SMOKER_PREPARE_TONGUE_LAUNCH, + L4D2_ACT_TERROR_SMOKER_SENDING_OUT_TONGUE, + L4D2_ACT_TERROR_SMOKER_SENDING_OUT_TONGUE_IDLE, + L4D2_ACT_TERROR_SMOKER_REELING_IN_TONGUE, + L4D2_ACT_TERROR_SMOKER_REELING_IN_TONGUE_IDLE, + L4D2_ACT_TERROR_SMOKER_CRITICAL_ATTACK, + L4D2_ACT_TERROR_SMOKER_CRITICAL_ATTACK_IDLE, + L4D2_ACT_TERROR_SMOKER_END_TONGUE_ATTACK, + L4D2_ACT_TERROR_RUN_LEAKER, + L4D2_ACT_TERROR_CROUCH_LEAKER, + L4D2_ACT_TERROR_CROUCHIDLE_LEAKER, + L4D2_ACT_TERROR_GUARD, + L4D2_ACT_HULK_THROW, + L4D2_ACT_TANK_OVERHEAD_THROW, + L4D2_ACT_HULK_ATTACK_LOW, + L4D2_ACT_TERROR_HUNTER_POUNCE_MELEE, + L4D2_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_L, + L4D2_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_R, + L4D2_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_BACKWARD, + L4D2_ACT_TERROR_HUNTER_POUNCE_KNOCKOFF_FORWARD, + L4D2_ACT_TERROR_CHARGER_CHARGE, + L4D2_ACT_IDLE_POUNCED, + L4D2_ACT_TERROR_POUNCED_TO_STAND, + L4D2_ACT_TERROR_INCAP_FROM_POUNCE, + L4D2_ACT_TERROR_INCAP_FROM_TONGUE, + L4D2_ACT_TERROR_IDLE_FALL_FROM_TONGUE, + L4D2_ACT_TERROR_HANGING_FROM_TONGUE, + L4D2_ACT_TERROR_HANGING_FROM_TONGUE_MALE, + L4D2_ACT_TERROR_HANGING_FROM_TONGUE_FEMALE, + L4D2_ACT_TERROR_STANDING_CHOKE_FROM_TONGUE, + L4D2_ACT_TERROR_DRAGGING_FROM_TONGUE, + L4D2_ACT_TERROR_DRAGGING_FROM_TONGUE_MALE, + L4D2_ACT_TERROR_DRAGGING_FROM_TONGUE_FEMALE, + L4D2_ACT_TERROR_DRAGGING_FROM_TONGUE_DEPLOY, + L4D2_ACT_TERROR_CHOKING_TONGUE_GROUND, + L4D2_ACT_TERROR_CHOKING_TONGUE_GROUND_MALE, + L4D2_ACT_TERROR_CHOKING_TONGUE_GROUND_FEMALE, + L4D2_ACT_TERROR_INCAP_FROM_TONGUE_GERMANY, + L4D2_ACT_TERROR_HANGING_FROM_TONGUE_GERMANY, + L4D2_ACT_TERROR_IDLE_FALL_FROM_TONGUE_GERMANY, + L4D2_ACT_TERROR_STANDING_CHOKE_FROM_TONGUE_GERMANY, + L4D2_ACT_TERROR_ATTACK_MOVING, + L4D2_ACT_TERROR_TANKROCK_TO_STAND, + L4D2_ACT_TERROR_HULK_VICTORY, + L4D2_ACT_TERROR_HULK_VICTORY_B, + L4D2_ACT_TERROR_RAGE_AT_ENEMY, + L4D2_ACT_TERROR_RAGE_AT_KNOCKDOWN, + L4D2_ACT_TERROR_SMASH_LEFT, + L4D2_ACT_TERROR_SMASH_RIGHT, + L4D2_ACT_TERROR_JOCKEY_RIDE, + L4D2_ACT_TERROR_JOCKEY_RIDDEN, + L4D2_ACT_VM_LUNGE_LAYER, + L4D2_ACT_VM_LUNGE_PUSH, + L4D2_ACT_VM_LUNGE_PUSH_LAYER, + L4D2_ACT_VM_LUNGE_OFFWALL, + L4D2_ACT_VM_LUNGE_OFFWALL_LAYER, + L4D2_ACT_VM_LUNGE_POUNCE, + L4D2_ACT_VM_LUNGE_POUNCE_LAYER, + L4D2_ACT_VM_POUNCE, + L4D2_ACT_VM_POUNCE_LAYER, + L4D2_ACT_VM_VOMIT_LAYER, + L4D2_ACT_VM_TONGUE, + L4D2_ACT_VM_TONGUE_LAYER, + L4D2_ACT_VM_BITE, + L4D2_ACT_VM_BITE_LAYER, + L4D2_ACT_VM_COUGH_LAYER, + L4D2_ACT_VM_FIDGET_LAYER, + L4D2_ACT_DOOR_OPEN, + L4D2_ACT_DOOR_OPENFAIL, + L4D2_ACT_DOOR_ANIMTOLOCK, + L4D2_ACT_DOOR_ANIMTOUNLOCK, + L4D2_ACT_VM_ITEMPICKUP_EXTEND, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP, + L4D2_ACT_VM_ITEMPICKUP_LOOP_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND, + L4D2_ACT_VM_HELPINGHAND_EXTEND_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP, + L4D2_ACT_VM_HELPINGHAND_LOOP_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT, + L4D2_ACT_VM_HELPINGHAND_RETRACT_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_PISTOL, + L4D2_ACT_VM_HELPINGHAND_LOOP_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PISTOL, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PISTOL, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_DUAL_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_LOOP_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_DUAL_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_DUAL_PISTOL, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_DUAL_PISTOL, + L4D2_ACT_VM_HELPINGHAND_LOOP_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_DUAL_PISTOL, + L4D2_ACT_VM_HELPINGHAND_EXTEND_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_DUAL_PISTOL, + L4D2_ACT_VM_HELPINGHAND_RETRACT_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_RIFLE, + L4D2_ACT_VM_ITEMPICKUP_LOOP_RIFLE_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_RIFLE, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_RIFLE_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_RIFLE, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_RIFLE_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_RIFLE, + L4D2_ACT_VM_HELPINGHAND_LOOP_RIFLE_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_RIFLE, + L4D2_ACT_VM_HELPINGHAND_EXTEND_RIFLE_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_RIFLE, + L4D2_ACT_VM_HELPINGHAND_RETRACT_RIFLE_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_SMG, + L4D2_ACT_VM_ITEMPICKUP_LOOP_SMG_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_SMG, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_SMG_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_SMG, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_SMG_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_SMG, + L4D2_ACT_VM_HELPINGHAND_LOOP_SMG_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_SMG, + L4D2_ACT_VM_HELPINGHAND_EXTEND_SMG_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_SMG, + L4D2_ACT_VM_HELPINGHAND_RETRACT_SMG_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_SNIPER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_SNIPER_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_SNIPER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_SNIPER_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_SNIPER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_SNIPER_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_SNIPER, + L4D2_ACT_VM_HELPINGHAND_LOOP_SNIPER_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_SNIPER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_SNIPER_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_SNIPER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_SNIPER_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PIPEBOMB, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PIPEBOMB_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PIPEBOMB, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PIPEBOMB_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PIPEBOMB, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PIPEBOMB_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_PIPEBOMB, + L4D2_ACT_VM_HELPINGHAND_LOOP_PIPEBOMB_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PIPEBOMB, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PIPEBOMB_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PIPEBOMB, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PIPEBOMB_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_MOLOTOV, + L4D2_ACT_VM_ITEMPICKUP_LOOP_MOLOTOV_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_MOLOTOV, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_MOLOTOV_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_MOLOTOV, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_MOLOTOV_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_MOLOTOV, + L4D2_ACT_VM_HELPINGHAND_LOOP_MOLOTOV_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_MOLOTOV, + L4D2_ACT_VM_HELPINGHAND_EXTEND_MOLOTOV_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_MOLOTOV, + L4D2_ACT_VM_HELPINGHAND_RETRACT_MOLOTOV_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_MEDKIT, + L4D2_ACT_VM_ITEMPICKUP_LOOP_MEDKIT_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_MEDKIT, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_MEDKIT_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_MEDKIT, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_MEDKIT_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_MEDKIT, + L4D2_ACT_VM_HELPINGHAND_LOOP_MEDKIT_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_MEDKIT, + L4D2_ACT_VM_HELPINGHAND_EXTEND_MEDKIT_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_MEDKIT, + L4D2_ACT_VM_HELPINGHAND_RETRACT_MEDKIT_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PAINPILLS, + L4D2_ACT_VM_ITEMPICKUP_LOOP_PAINPILLS_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PAINPILLS, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_PAINPILLS_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PAINPILLS, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_PAINPILLS_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_PAINPILLS, + L4D2_ACT_VM_HELPINGHAND_LOOP_PAINPILLS_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PAINPILLS, + L4D2_ACT_VM_HELPINGHAND_EXTEND_PAINPILLS_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PAINPILLS, + L4D2_ACT_VM_HELPINGHAND_RETRACT_PAINPILLS_LAYER, + L4D2_ACT_VM_CANCEL, + L4D2_ACT_VM_CANCEL_LAYER, + L4D2_ACT_CROUCHIDLE_RIFLE, + L4D2_ACT_IDLE_INJURED_RIFLE, + L4D2_ACT_WALK_INJURED_RIFLE, + L4D2_ACT_RUN_INJURED_RIFLE, + L4D2_ACT_DEPLOY_RIFLE, + L4D2_ACT_PRIMARYATTACK_RIFLE, + L4D2_ACT_RELOAD_RIFLE, + L4D2_ACT_IDLE_CALM_RIFLE, + L4D2_ACT_WALK_CALM_RIFLE, + L4D2_ACT_RUN_CALM_RIFLE, + L4D2_ACT_MELEE_SWEEP_RIFLE_IDLE, + L4D2_ACT_MELEE_SHOVE_RIFLE_IDLE, + L4D2_ACT_MELEE_STRAIGHT_RIFLE_IDLE, + L4D2_ACT_MELEE_SWEEP_RIFLE_RUN, + L4D2_ACT_MELEE_SHOVE_RIFLE_RUN, + L4D2_ACT_MELEE_STRAIGHT_RIFLE_RUN, + L4D2_ACT_TERROR_PULLED_RUN_RIFLE, + L4D2_ACT_MELEE_STOMP_RIFLE_IDLE, + L4D2_ACT_MELEE_STOMP_RIFLE_WALK, + L4D2_ACT_IDLE_SHOTGUN, + L4D2_ACT_WALK_SHOTGUN, + L4D2_ACT_RUN_SHOTGUN, + L4D2_ACT_IDLE_CALM_SHOTGUN, + L4D2_ACT_CROUCHIDLE_SHOTGUN, + L4D2_ACT_RUN_CROUCH_SHOTGUN, + L4D2_ACT_DEPLOY_SHOTGUN, + L4D2_ACT_PRIMARYATTACK_SHOTGUN, + L4D2_ACT_RELOAD_SHOTGUN_START, + L4D2_ACT_RELOAD_SHOTGUN_LOOP, + L4D2_ACT_RELOAD_SHOTGUN_END, + L4D2_ACT_IDLE_PUMPSHOTGUN, + L4D2_ACT_CROUCHIDLE_PUMPSHOTGUN, + L4D2_ACT_IDLE_CALM_PUMPSHOTGUN, + L4D2_ACT_IDLE_INJURED_PUMPSHOTGUN, + L4D2_ACT_WALK_PUMPSHOTGUN, + L4D2_ACT_RUN_CROUCH_PUMPSHOTGUN, + L4D2_ACT_RUN_PUMPSHOTGUN, + L4D2_ACT_WALK_CALM_PUMPSHOTGUN, + L4D2_ACT_RUN_CALM_PUMPSHOTGUN, + L4D2_ACT_WALK_INJURED_PUMPSHOTGUN, + L4D2_ACT_RUN_INJURED_PUMPSHOTGUN, + L4D2_ACT_PRIMARYATTACK_PUMPSHOTGUN, + L4D2_ACT_RELOAD_PUMPSHOTGUN_START, + L4D2_ACT_RELOAD_PUMPSHOTGUN_LOOP, + L4D2_ACT_RELOAD_PUMPSHOTGUN_END, + L4D2_ACT_RELOAD_GRENADE_LAUNCHER, + L4D2_ACT_IDLE_GREN, + L4D2_ACT_CROUCHIDLE_GREN, + L4D2_ACT_IDLE_INJURED_GREN, + L4D2_ACT_RUN_GREN, + L4D2_ACT_WALK_GREN, + L4D2_ACT_RUN_CROUCH_GREN, + L4D2_ACT_DEPLOY_GREN, + L4D2_ACT_WALK_INJURED_GREN, + L4D2_ACT_RUN_INJURED_GREN, + L4D2_ACT_PRIMARYATTACK_GREN1_IDLE, + L4D2_ACT_PRIMARYATTACK_GREN2_IDLE, + L4D2_ACT_PRIMARYATTACK_GREN1_RUN, + L4D2_ACT_PRIMARYATTACK_GREN2_RUN, + L4D2_ACT_IDLE_GREN_PULL_BACK, + L4D2_ACT_CROUCHIDLE_GREN_PULL_BACK, + L4D2_ACT_IDLE_INJURED_GREN_PULL_BACK, + L4D2_ACT_RUN_GREN_PULL_BACK, + L4D2_ACT_WALK_GREN_PULL_BACK, + L4D2_ACT_RUN_CROUCH_GREN_PULL_BACK, + L4D2_ACT_WALK_INJURED_GREN_PULL_BACK, + L4D2_ACT_RUN_INJURED_GREN_PULL_BACK, + L4D2_ACT_IDLE_SNIPER, + L4D2_ACT_CROUCHIDLE_SNIPER, + L4D2_ACT_IDLE_CALM_SNIPER, + L4D2_ACT_IDLE_INJURED_SNIPER, + L4D2_ACT_WALK_SNIPER, + L4D2_ACT_RUN_CROUCH_SNIPER, + L4D2_ACT_RUN_SNIPER, + L4D2_ACT_WALK_CALM_SNIPER, + L4D2_ACT_RUN_CALM_SNIPER, + L4D2_ACT_WALK_INJURED_SNIPER, + L4D2_ACT_RUN_INJURED_SNIPER, + L4D2_ACT_IDLE_SNIPER_ZOOMED, + L4D2_ACT_CROUCHIDLE_SNIPER_ZOOMED, + L4D2_ACT_IDLE_INJURED_SNIPER_ZOOMED, + L4D2_ACT_IDLE_SNIPER_MILITARY, + L4D2_ACT_IDLE_SNIPER_MILITARYZOOMED, + L4D2_ACT_CROUCHIDLE_SNIPER_MILITARY, + L4D2_ACT_CROUCHIDLE_SNIPER_MILITARYZOOMED, + L4D2_ACT_IDLE_CALM_SNIPER_MILITARY, + L4D2_ACT_IDLE_INJURED_SNIPER_MILITARY, + L4D2_ACT_IDLE_INJURED_SNIPER_MILITARYZOOMED, + L4D2_ACT_RUN_CROUCH_SNIPER_MILITARY, + L4D2_ACT_WALK_SNIPER_MILITARY, + L4D2_ACT_RUN_SNIPER_MILITARY, + L4D2_ACT_WALK_CALM_SNIPER_MILITARY, + L4D2_ACT_RUN_CALM_SNIPER_MILITARY, + L4D2_ACT_WALK_INJURED_SNIPER_MILITARY, + L4D2_ACT_RUN_INJURED_SNIPER_MILITARY, + L4D2_ACT_IDLE_SMG, + L4D2_ACT_WALK_SMG, + L4D2_ACT_RUN_SMG, + L4D2_ACT_CROUCHIDLE_SMG, + L4D2_ACT_RUN_CROUCH_SMG, + L4D2_ACT_IDLE_INJURED_SMG, + L4D2_ACT_WALK_INJURED_SMG, + L4D2_ACT_RUN_INJURED_SMG, + L4D2_ACT_IDLE_CALM_SMG, + L4D2_ACT_WALK_CALM_SMG, + L4D2_ACT_RUN_CALM_SMG, + L4D2_ACT_PRIMARYATTACK_SMG, + L4D2_ACT_RELOAD_SMG, + L4D2_ACT_IDLE_FIRSTAIDKIT, + L4D2_ACT_CROUCHIDLE_FIRSTAIDKIT, + L4D2_ACT_IDLE_INJURED_FIRSTAIDKIT, + L4D2_ACT_RUN_FIRSTAIDKIT, + L4D2_ACT_WALK_FIRSTAIDKIT, + L4D2_ACT_RUN_CROUCH_FIRSTAIDKIT, + L4D2_ACT_WALK_INJURED_FIRSTAIDKIT, + L4D2_ACT_RUN_INJURED_FIRSTAIDKIT, + L4D2_ACT_MELEE_SWEEP_FIRSTAIDKIT, + L4D2_ACT_MELEE_SWEEP_COLA, + L4D2_ACT_MELEE_SWEEP_DEFIBRILLATOR, + L4D2_ACT_MELEE_SWEEP_UPGRADE_PACK, + L4D2_ACT_CROUCHIDLE_PISTOL, + L4D2_ACT_RUN_CROUCH_PISTOL, + L4D2_ACT_IDLE_INJURED_PISTOL, + L4D2_ACT_WALK_INJURED_PISTOL, + L4D2_ACT_RUN_INJURED_PISTOL, + L4D2_ACT_DEPLOY_PISTOL, + L4D2_ACT_PRIMARYATTACK_PISTOL, + L4D2_ACT_IDLE_CALM_PISTOL, + L4D2_ACT_WALK_CALM_PISTOL, + L4D2_ACT_RUN_CALM_PISTOL, + L4D2_ACT_IDLE_ELITES, + L4D2_ACT_WALK_ELITES, + L4D2_ACT_RUN_ELITES, + L4D2_ACT_CROUCHIDLE_ELITES, + L4D2_ACT_RUN_CROUCH_ELITES, + L4D2_ACT_IDLE_INJURED_ELITES, + L4D2_ACT_WALK_INJURED_ELITES, + L4D2_ACT_RUN_INJURED_ELITES, + L4D2_ACT_DEPLOY_ELITES, + L4D2_ACT_PRIMARYATTACK_ELITES_R, + L4D2_ACT_PRIMARYATTACK_ELITES_L, + L4D2_ACT_IDLE_CALM_ELITES, + L4D2_ACT_WALK_CALM_ELITES, + L4D2_ACT_RUN_CALM_ELITES, + L4D2_ACT_RELOAD_ELITES, + L4D2_ACT_RELOAD_M4, + L4D2_ACT_PRIMARYATTACK_XM1014, + L4D2_ACT_PRIMARYATTACK_M3S90, + L4D2_ACT_IDLE_GASCAN, + L4D2_ACT_CROUCHIDLE_GASCAN, + L4D2_ACT_IDLE_CALM_GASCAN, + L4D2_ACT_IDLE_INJURED_GASCAN, + L4D2_ACT_RUN_GASCAN, + L4D2_ACT_WALK_GASCAN, + L4D2_ACT_RUN_CROUCH_GASCAN, + L4D2_ACT_RUN_INJURED_GASCAN, + L4D2_ACT_JUMP_GASCAN, + L4D2_ACT_MELEE_SWEEP_GASCAN, + L4D2_ACT_IDLE_O2, + L4D2_ACT_CROUCHIDLE_O2, + L4D2_ACT_IDLE_CALM_O2, + L4D2_ACT_IDLE_INJURED_O2, + L4D2_ACT_RUN_O2, + L4D2_ACT_WALK_O2, + L4D2_ACT_RUN_CROUCH_O2, + L4D2_ACT_RUN_INJURED_O2, + L4D2_ACT_JUMP_O2, + L4D2_ACT_MELEE_SWEEP_O2, + L4D2_ACT_IDLE_GNOME, + L4D2_ACT_CROUCHIDLE_GNOME, + L4D2_ACT_IDLE_CALM_GNOME, + L4D2_ACT_IDLE_INJURED_GNOME, + L4D2_ACT_RUN_CROUCH_GNOME, + L4D2_ACT_WALK_GNOME, + L4D2_ACT_RUN_GNOME, + L4D2_ACT_WALK_CALM_GNOME, + L4D2_ACT_RUN_CALM_GNOME, + L4D2_ACT_WALK_INJURED_GNOME, + L4D2_ACT_RUN_INJURED_GNOME, + L4D2_ACT_JUMP_GNOME, + L4D2_ACT_MELEE_SWEEP_GNOME, + L4D2_ACT_SHOOT_E2W_AXE, + L4D2_ACT_SHOOT_E2W_IDLE_AXE, + L4D2_ACT_SHOOT_W2E_AXE, + L4D2_ACT_SHOOT_W2E_IDLE_AXE, + L4D2_ACT_SHOOT_N2S_AXE, + L4D2_ACT_SHOOT_N2S_IDLE_AXE, + L4D2_ACT_SHOOT_S2N_AXE, + L4D2_ACT_SHOOT_S2N_IDLE_AXE, + L4D2_ACT_SHOOT_STRONG_AXE, + L4D2_ACT_SHOOT_STRONG_IDLE_AXE, + L4D2_ACT_SHOOT_SECONDARY_AXE, + L4D2_ACT_SHOOT_SECONDARY_IDLE_AXE, + L4D2_ACT_IDLE_AXE, + L4D2_ACT_CROUCHIDLE_AXE, + L4D2_ACT_IDLE_CALM_AXE, + L4D2_ACT_IDLE_INJURED_AXE, + L4D2_ACT_RUN_AXE, + L4D2_ACT_WALK_AXE, + L4D2_ACT_WALK_INJURED_AXE, + L4D2_ACT_RUN_CROUCH_AXE, + L4D2_ACT_RUN_INJURED_AXE, + L4D2_ACT_JUMP_AXE, + L4D2_ACT_SHOOT_E2W_BAT, + L4D2_ACT_SHOOT_E2W_IDLE_BAT, + L4D2_ACT_SHOOT_W2E_BAT, + L4D2_ACT_SHOOT_W2E_IDLE_BAT, + L4D2_ACT_SHOOT_N2S_BAT, + L4D2_ACT_SHOOT_N2S_IDLE_BAT, + L4D2_ACT_SHOOT_S2N_BAT, + L4D2_ACT_SHOOT_S2N_IDLE_BAT, + L4D2_ACT_SHOOT_STRONG_BAT, + L4D2_ACT_SHOOT_STRONG_IDLE_BAT, + L4D2_ACT_SHOOT_SECONDARY_BAT, + L4D2_ACT_SHOOT_SECONDARY_IDLE_BAT, + L4D2_ACT_IDLE_BAT, + L4D2_ACT_CROUCHIDLE_BAT, + L4D2_ACT_IDLE_CALM_BAT, + L4D2_ACT_IDLE_INJURED_BAT, + L4D2_ACT_RUN_BAT, + L4D2_ACT_WALK_BAT, + L4D2_ACT_WALK_INJURED_BAT, + L4D2_ACT_RUN_CROUCH_BAT, + L4D2_ACT_RUN_INJURED_BAT, + L4D2_ACT_JUMP_BAT, + L4D2_ACT_SHOOT_E2W_KATANA, + L4D2_ACT_SHOOT_E2W_IDLE_KATANA, + L4D2_ACT_SHOOT_W2E_KATANA, + L4D2_ACT_SHOOT_W2E_IDLE_KATANA, + L4D2_ACT_SHOOT_E2W_FRYINGPAN, + L4D2_ACT_SHOOT_E2W_IDLE_FRYINGPAN, + L4D2_ACT_SHOOT_W2E_FRYINGPAN, + L4D2_ACT_SHOOT_W2E_IDLE_FRYINGPAN, + L4D2_ACT_SHOOT_N2S_FRYINGPAN, + L4D2_ACT_SHOOT_N2S_IDLE_FRYINGPAN, + L4D2_ACT_SHOOT_S2N_FRYINGPAN, + L4D2_ACT_SHOOT_S2N_IDLE_FRYINGPAN, + L4D2_ACT_SHOOT_STRONG_FRYINGPAN, + L4D2_ACT_SHOOT_STRONG_IDLE_FRYINGPAN, + L4D2_ACT_SHOOT_SECONDARY_FRYINGPAN, + L4D2_ACT_SHOOT_SECONDARY_IDLE_FRYINGPAN, + L4D2_ACT_IDLE_FRYINGPAN, + L4D2_ACT_CROUCHIDLE_FRYINGPAN, + L4D2_ACT_IDLE_CALM_FRYINGPAN, + L4D2_ACT_IDLE_INJURED_FRYINGPAN, + L4D2_ACT_RUN_FRYINGPAN, + L4D2_ACT_WALK_FRYINGPAN, + L4D2_ACT_WALK_INJURED_FRYINGPAN, + L4D2_ACT_RUN_CROUCH_FRYINGPAN, + L4D2_ACT_RUN_INJURED_FRYINGPAN, + L4D2_ACT_JUMP_FRYINGPAN, + L4D2_ACT_SHOOT_E2W_GUITAR, + L4D2_ACT_SHOOT_E2W_IDLE_GUITAR, + L4D2_ACT_SHOOT_W2E_GUITAR, + L4D2_ACT_SHOOT_W2E_IDLE_GUITAR, + L4D2_ACT_SHOOT_N2S_GUITAR, + L4D2_ACT_SHOOT_N2S_IDLE_GUITAR, + L4D2_ACT_SHOOT_S2N_GUITAR, + L4D2_ACT_SHOOT_S2N_IDLE_GUITAR, + L4D2_ACT_SHOOT_STRONG_GUITAR, + L4D2_ACT_SHOOT_STRONG_IDLE_GUITAR, + L4D2_ACT_SHOOT_SECONDARY_GUITAR, + L4D2_ACT_SHOOT_SECONDARY_IDLE_GUITAR, + L4D2_ACT_IDLE_GUITAR, + L4D2_ACT_CROUCHIDLE_GUITAR, + L4D2_ACT_IDLE_CALM_GUITAR, + L4D2_ACT_IDLE_INJURED_GUITAR, + L4D2_ACT_RUN_GUITAR, + L4D2_ACT_WALK_GUITAR, + L4D2_ACT_WALK_INJURED_GUITAR, + L4D2_ACT_RUN_CROUCH_GUITAR, + L4D2_ACT_RUN_INJURED_GUITAR, + L4D2_ACT_JUMP_GUITAR, + L4D2_ACT_IDLE_CHAINSAW, + L4D2_ACT_IDLE_ATTACK_CHAINSAW, + L4D2_ACT_WALK_CHAINSAW, + L4D2_ACT_RUN_CHAINSAW, + L4D2_ACT_CROUCHIDLE_CHAINSAW, + L4D2_ACT_IDLE_CALM_CHAINSAW, + L4D2_ACT_IDLE_INJURED_CHAINSAW, + L4D2_ACT_RUN_CALM_CHAINSAW, + L4D2_ACT_WALK_CALM_CHAINSAW, + L4D2_ACT_WALK_INJURED_CHAINSAW, + L4D2_ACT_RUN_CROUCH_CHAINSAW, + L4D2_ACT_RUN_INJURED_CHAINSAW, + L4D2_ACT_JUMP_CHAINSAW, + L4D2_ACT_MELEE_SWEEP_CHAINSAW, + L4D2_ACT_PRIMARYATTACK_CHAINSAW, + L4D2_ACT_DEPLOY_CHAINSAW, + L4D2_ACT_TERROR_CHAINSAW_START, + L4D2_ACT_SHOOT_W2E_CHAINSAW, + L4D2_ACT_SHOOT_CHAINSAW, + L4D2_ACT_CHAINSAW_STARTUP, + L4D2_ACT_IDLE_GRENADELAUNCHER, + L4D2_ACT_WALK_GRENADELAUNCHER, + L4D2_ACT_RUN_GRENADELAUNCHER, + L4D2_ACT_CROUCHIDLE_GRENADELAUNCHER, + L4D2_ACT_IDLE_CALM_GRENADELAUNCHER, + L4D2_ACT_IDLE_INJURED_GRENADELAUNCHER, + L4D2_ACT_RUN_CALM_GRENADELAUNCHER, + L4D2_ACT_WALK_CALM_GRENADELAUNCHER, + L4D2_ACT_WALK_INJURED_GRENADELAUNCHER, + L4D2_ACT_RUN_CROUCH_GRENADELAUNCHER, + L4D2_ACT_RUN_INJURED_GRENADELAUNCHER, + L4D2_ACT_JUMP_GRENADELAUNCHER, + L4D2_ACT_MELEE_SWEEP_GRENADELAUNCHER, + L4D2_ACT_PRIMARYATTACK_GRENADELAUNCHER, + L4D2_ACT_DEPLOY_GRENADELAUNCHER, + L4D2_ACT_VM_MELEE, + L4D2_ACT_VM_SHOOT_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_LAYER, + L4D2_ACT_VM_SECONDARYATTACK_LAYER, + L4D2_ACT_VM_MELEE_LAYER, + L4D2_ACT_VM_PICKUP_LAYER, + L4D2_ACT_VM_PICKUP_CLIPIN, + L4D2_ACT_VM_PICKUP_CLIPIN_LAYER, + L4D2_ACT_VM_PICKUP_CHARGING, + L4D2_ACT_VM_PICKUP_CHARGING_LAYER, + L4D2_ACT_VM_PICKUP_FASSIST, + L4D2_ACT_VM_PICKUP_FASSIST_LAYER, + L4D2_ACT_VM_RELOAD_PUMP, + L4D2_ACT_VM_RELOAD_PUMP_LAYER, + L4D2_ACT_VM_RELOAD_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT, + L4D2_ACT_VM_RELOAD_CLIPOUT_LAYER, + L4D2_ACT_VM_RELOAD_CLIPIN, + L4D2_ACT_VM_RELOAD_CLIPIN_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN2, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN2_LAYER, + L4D2_ACT_VM_DEPLOY_LAYER, + L4D2_ACT_VM_THROW_LAYER, + L4D2_ACT_VM_PULLPIN_LAYER, + L4D2_ACT_VM_IDLE_BAREHAND, + L4D2_ACT_VM_DEPLOY_BAREHAND, + L4D2_ACT_VM_DEPLOY_BAREHAND_LAYER, + L4D2_ACT_VM_MELEE_BAREHAND, + L4D2_ACT_VM_MELEE_BAREHAND_LAYER, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_BAREHAND, + L4D2_ACT_VM_ITEMPICKUP_EXTEND_BAREHAND_LAYER, + L4D2_ACT_VM_ITEMPICKUP_LOOP_BAREHAND, + L4D2_ACT_VM_ITEMPICKUP_LOOP_BAREHAND_LAYER, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_BAREHAND, + L4D2_ACT_VM_ITEMPICKUP_RETRACT_BAREHAND_LAYER, + L4D2_ACT_VM_HELPINGHAND_EXTEND_BAREHAND, + L4D2_ACT_VM_HELPINGHAND_EXTEND_BAREHAND_LAYER, + L4D2_ACT_VM_HELPINGHAND_LOOP_BAREHAND, + L4D2_ACT_VM_HELPINGHAND_LOOP_BAREHAND_LAYER, + L4D2_ACT_VM_HELPINGHAND_RETRACT_BAREHAND, + L4D2_ACT_VM_HELPINGHAND_RETRACT_BAREHAND_LAYER, + L4D2_ACT_VM_IDLE_DUAL_PISTOL, + L4D2_ACT_VM_DEPLOY_DUAL_PISTOL, + L4D2_ACT_VM_DEPLOY_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_DUAL_PISTOL, + L4D2_ACT_VM_SHOOT_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_SECONDARYATTACK_DUAL_PISTOL, + L4D2_ACT_VM_SECONDARYATTACK_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_CLIPOUT_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_CLIPIN_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_CLIPIN_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN2_DUAL_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN2_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_PICKUP_DUAL_PISTOL, + L4D2_ACT_VM_PICKUP_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_PICKUP_CLIPIN_DUAL_PISTOL, + L4D2_ACT_VM_PICKUP_CLIPIN_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_PICKUP_CHARGING_DUAL_PISTOL, + L4D2_ACT_VM_PICKUP_CHARGING_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_MELEE_DUAL_PISTOL, + L4D2_ACT_VM_MELEE_DUAL_PISTOL_LAYER, + L4D2_ACT_VM_IDLE_PISTOL, + L4D2_ACT_VM_DEPLOY_PISTOL, + L4D2_ACT_VM_DEPLOY_PISTOL_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_PISTOL, + L4D2_ACT_VM_SHOOT_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_PISTOL, + L4D2_ACT_VM_RELOAD_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT_PISTOL, + L4D2_ACT_VM_RELOAD_CLIPOUT_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_PISTOL_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_PISTOL, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_PISTOL_LAYER, + L4D2_ACT_VM_MELEE_PISTOL, + L4D2_ACT_VM_MELEE_PISTOL_LAYER, + L4D2_ACT_VM_IDLE_RIFLE, + L4D2_ACT_VM_PICKUP_RIFLE, + L4D2_ACT_VM_PICKUP_RIFLE_LAYER, + L4D2_ACT_VM_PICKUP_CLIPIN_RIFLE, + L4D2_ACT_VM_PICKUP_CLIPIN_RIFLE_LAYER, + L4D2_ACT_VM_PICKUP_CHARGING_RIFLE, + L4D2_ACT_VM_PICKUP_CHARGING_RIFLE_LAYER, + L4D2_ACT_VM_PICKUP_FASSIST_RIFLE, + L4D2_ACT_VM_PICKUP_FASSIST_RIFLE_LAYER, + L4D2_ACT_VM_DEPLOY_RIFLE, + L4D2_ACT_VM_DEPLOY_RIFLE_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_RIFLE, + L4D2_ACT_VM_SHOOT_RIFLE_LAYER, + L4D2_ACT_VM_RELOAD_RIFLE, + L4D2_ACT_VM_RELOAD_RIFLE_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT_RIFLE, + L4D2_ACT_VM_RELOAD_CLIPOUT_RIFLE_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_RIFLE, + L4D2_ACT_VM_RELOAD_EMPTY_RIFLE_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_RIFLE, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_RIFLE_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_RIFLE, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_RIFLE_LAYER, + L4D2_ACT_VM_MELEE_RIFLE, + L4D2_ACT_VM_MELEE_RIFLE_LAYER, + L4D2_ACT_VM_FIDGET_RIFLE_LAYER, + L4D2_ACT_VM_IDLE_SMG, + L4D2_ACT_VM_PICKUP_SMG, + L4D2_ACT_VM_PICKUP_SMG_LAYER, + L4D2_ACT_VM_PICKUP_CLIPIN_SMG, + L4D2_ACT_VM_PICKUP_CLIPIN_SMG_LAYER, + L4D2_ACT_VM_PICKUP_CHARGING_SMG, + L4D2_ACT_VM_PICKUP_CHARGING_SMG_LAYER, + L4D2_ACT_VM_DEPLOY_SMG, + L4D2_ACT_VM_DEPLOY_SMG_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_SMG, + L4D2_ACT_VM_SHOOT_SMG_LAYER, + L4D2_ACT_VM_RELOAD_SMG, + L4D2_ACT_VM_RELOAD_SMG_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT_SMG, + L4D2_ACT_VM_RELOAD_CLIPOUT_SMG_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_SMG, + L4D2_ACT_VM_RELOAD_EMPTY_SMG_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_SMG, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_SMG_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_SMG, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_SMG_LAYER, + L4D2_ACT_VM_MELEE_SMG, + L4D2_ACT_VM_MELEE_SMG_LAYER, + L4D2_ACT_VM_FIDGET_SMG_LAYER, + L4D2_ACT_VM_IDLE_SNIPER, + L4D2_ACT_VM_PICKUP_SNIPER, + L4D2_ACT_VM_PICKUP_SNIPER_LAYER, + L4D2_ACT_VM_PICKUP_CLIPIN_SNIPER, + L4D2_ACT_VM_PICKUP_CLIPIN_SNIPER_LAYER, + L4D2_ACT_VM_PICKUP_CHARGING_SNIPER, + L4D2_ACT_VM_PICKUP_CHARGING_SNIPER_LAYER, + L4D2_ACT_VM_DEPLOY_SNIPER, + L4D2_ACT_VM_DEPLOY_SNIPER_LAYER, + L4D2_ACT_VM_PRIMARYATTACK_SNIPER, + L4D2_ACT_VM_SHOOT_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_SNIPER, + L4D2_ACT_VM_RELOAD_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_CLIPOUT_SNIPER, + L4D2_ACT_VM_RELOAD_CLIPOUT_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_SNIPER, + L4D2_ACT_VM_RELOAD_EMPTY_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_SNIPER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPOUT_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_SNIPER, + L4D2_ACT_VM_RELOAD_EMPTY_CLIPIN_SNIPER_LAYER, + L4D2_ACT_VM_MELEE_SNIPER, + L4D2_ACT_VM_MELEE_SNIPER_LAYER, + L4D2_ACT_VM_FIDGET_SNIPER_LAYER, + L4D2_ACT_VM_RELOAD_LOOP, + L4D2_ACT_VM_RELOAD_LOOP_LAYER, + L4D2_ACT_VM_RELOAD_END, + L4D2_ACT_VM_RELOAD_END_LAYER, + L4D2_ACT_VM_IDLE_PIPEBOMB, + L4D2_ACT_VM_DEPLOY_PIPEBOMB, + L4D2_ACT_VM_DEPLOY_PIPEBOMB_LAYER, + L4D2_ACT_VM_PULLPIN_PIPEBOMB, + L4D2_ACT_VM_PULLPIN_PIPEBOMB_LAYER, + L4D2_ACT_VM_THROW_PIPEBOMB, + L4D2_ACT_VM_THROW_PIPEBOMB_LAYER, + L4D2_ACT_VM_MELEE_PIPEBOMB, + L4D2_ACT_VM_MELEE_PIPEBOMB_LAYER, + L4D2_ACT_VM_IDLE_MOLOTOV, + L4D2_ACT_VM_DEPLOY_MOLOTOV, + L4D2_ACT_VM_DEPLOY_MOLOTOV_LAYER, + L4D2_ACT_VM_PULLPIN_MOLOTOV, + L4D2_ACT_VM_PULLPIN_MOLOTOV_LAYER, + L4D2_ACT_VM_THROW_MOLOTOV, + L4D2_ACT_VM_THROW_MOLOTOV_LAYER, + L4D2_ACT_VM_MELEE_MOLOTOV, + L4D2_ACT_VM_MELEE_MOLOTOV_LAYER, + L4D2_ACT_VM_IDLE_PAINPILLS, + L4D2_ACT_VM_DEPLOY_PAINPILLS, + L4D2_ACT_VM_DEPLOY_PAINPILLS_LAYER, + L4D2_ACT_VM_MELEE_PAINPILLS, + L4D2_ACT_VM_MELEE_PAINPILLS_LAYER, + L4D2_ACT_VM_USE_PAINPILLS, + L4D2_ACT_VM_USE_PAINPILLS_LAYER, + L4D2_ACT_VM_IDLE_MEDKIT, + L4D2_ACT_VM_DEPLOY_MEDKIT, + L4D2_ACT_VM_DEPLOY_MEDKIT_LAYER, + L4D2_ACT_VM_MELEE_MEDKIT, + L4D2_ACT_VM_MELEE_MEDKIT_LAYER, + L4D2_ACT_VM_IDLE_GASCAN, + L4D2_ACT_VM_DEPLOY_GASCAN, + L4D2_ACT_VM_PULLPIN_GASCAN, + L4D2_ACT_VM_THROW_GASCAN, + L4D2_ACT_VM_MELEE_GASCAN, + L4D2_ACT_GEST_OVERHERE, + L4D2_ACT_GEST_POINTLEFT, + L4D2_ACT_GEST_POINTLEFT_QUICK, + L4D2_ACT_GEST_HEAD_TWISTLEFT, + L4D2_ACT_GEST_HEAD_DOWN, + L4D2_ACT_GEST_GOGOGO, + L4D2_ACT_GEST_WAVE, + L4D2_ACT_GEST_COUGH, + L4D2_ACT_GEST_COUGH01, + L4D2_ACT_GEST_COUGH02, + L4D2_ACT_GEST_COUGH03, + L4D2_ACT_GEST_COUGH1, + L4D2_ACT_GEST_COUGH2, + L4D2_ACT_GEST_COUGH3, + L4D2_ACT_GEST_VOMIT, + L4D2_ACT_GEST_VOMIT01, + L4D2_ACT_GEST_INTRO_CALM, + L4D2_ACT_GEST_INTRO_WAVE, + L4D2_ACT_DLCINTRO_01, + L4D2_ACT_DLCINTRO_02, + L4D2_ACT_DLCINTRO_03, + L4D2_ACT_DLCINTRO_04, + L4D2_ACT_DLCFI_FRANCIS_HLD, + L4D2_ACT_DLCFI_FRANCIS_017MB, + L4D2_ACT_DLCFI_FRANCIS_018MB, + L4D2_ACT_DLCFI_FRANCIS_01, + L4D2_ACT_DLCFI_FRANCIS_02, + L4D2_ACT_DLCFI_FRANCIS_03, + L4D2_ACT_DLCFI_FRANCIS_04, + L4D2_ACT_DLCFI_FRANCIS_05, + L4D2_ACT_DLCFI_FRANCIS_06, + L4D2_ACT_DLCFI_FRANCIS_07, + L4D2_ACT_DLCFI_FRANCIS_08, + L4D2_ACT_DLCFI_FRANCIS_08b, + L4D2_ACT_DLCFI_FRANCIS_09, + L4D2_ACT_DLCFI_FRANCIS_09b, + L4D2_ACT_DLCFI_FRANCIS_10, + L4D2_ACT_DLCFI_FRANCIS_10b, + L4D2_ACT_DLCFI_FRANCIS_11, + L4D2_ACT_DLCFI_FRANCIS_11b, + L4D2_ACT_DLCFI_FRANCIS_12AH, + L4D2_ACT_DLCFI_FRANCIS_12mr, + L4D2_ACT_DLCFI_FRANCIS_13mr, + L4D2_ACT_DLCFI_FRANCIS_13AH, + L4D2_ACT_DLCFI_FRANCIS_14AH, + L4D2_ACT_DLCFI_FRANCIS_15AH, + L4D2_ACT_DLCFI_FRANCIS_16AH, + L4D2_ACT_DLCFI_FRANCIS_17AH, + L4D2_ACT_DLCFI_FRANCIS_18AH, + L4D2_ACT_DLCFI_FRANCIS_19AH, + L4D2_ACT_DLCFI_FRANCIS_20AH, + L4D2_ACT_DLCFI_FRANCIS_21AH, + L4D2_ACT_DLCFI_FRANCIS_14mr, + L4D2_ACT_DLCFI_FRANCIS_15mr, + L4D2_ACT_DLCFI_FRANCIS_16mr, + L4D2_ACT_DLCFI_FRANCIS_17mr, + L4D2_ACT_DLCFI_FRANCIS_014MB, + L4D2_ACT_DLCFI_FRANCIS_014MBX, + L4D2_ACT_DLCFI_FRANCIS_13nm, + L4D2_ACT_DLCFI_LOUIS_01, + L4D2_ACT_DLCFI_LOUIS_02, + L4D2_ACT_DLCFI_LOUIS_03, + L4D2_ACT_DLCFI_LOUIS_04, + L4D2_ACT_DLCFI_LOUIS_05, + L4D2_ACT_DLCFI_LOUIS_06, + L4D2_ACT_DLCFI_LOUIS_07MB, + L4D2_ACT_DLCFI_LOUIS_08MB, + L4D2_ACT_DLCFI_LOUIS_09MB, + L4D2_ACT_DLCFI_LOUIS_10MB, + L4D2_ACT_DLCFI_LOUIS_11, + L4D2_ACT_DLCFI_LOUIS_11MB, + L4D2_ACT_DLCFI_LOUIS_11AH, + L4D2_ACT_DLCFI_LOUIS_12, + L4D2_ACT_DLCFI_LOUIS_012MB, + L4D2_ACT_DLCFI_LOUIS_012MR, + L4D2_ACT_DLCFI_LOUIS_13, + L4D2_ACT_DLCFI_LOUIS_013MB, + L4D2_ACT_DLCFI_LOUIS_013MR, + L4D2_ACT_DLCFI_LOUIS_14, + L4D2_ACT_DLCFI_LOUIS_014MB, + L4D2_ACT_DLCFI_LOUIS_14MR, + L4D2_ACT_DLCFI_LOUIS_15, + L4D2_ACT_DLCFI_LOUIS_015MB, + L4D2_ACT_DLCFI_LOUIS_016MB, + L4D2_ACT_DLCFI_LOUIS_16JM, + L4D2_ACT_DLCFI_LOUIS_16AJM, + L4D2_ACT_DLCFI_LOUIS_017MB, + L4D2_ACT_DLCFI_ZOEY_01, + L4D2_ACT_DLCFI_ZOEY_02, + L4D2_ACT_DLCFI_ZOEY_03, + L4D2_ACT_DLCFI_ZOEY_04, + L4D2_ACT_DLCFI_ZOEY_05, + L4D2_ACT_DLCFI_ZOEY_06, + L4D2_ACT_DLCFI_ZOEY_07MB, + L4D2_ACT_DLCFI_ZOEY_08MB, + L4D2_ACT_DLCFI_ZOEY_09MB, + L4D2_ACT_DLCFI_ZOEY_10MB, + L4D2_ACT_DLCFI_ZOEY_11MB, + L4D2_ACT_DLCFI_ZOEY_06AH, + L4D2_ACT_DLCFI_ZOEY_07AH, + L4D2_ACT_DLCFI_ZOEY_07mr, + L4D2_ACT_DLCFI_ZOEY_12MB, + L4D2_ACT_DLCFI_ZOEY_08mr, + L4D2_ACT_DLCFI_ZOEY_10MR, + L4D2_ACT_DLCINTRO_ZOEY_01, + L4D2_ACT_DLCINTRO_ZOEY_02, + L4D2_ACT_DLCINTRO_ZOEY_03, + L4D2_ACT_DLCINTRO_ZOEY_04, + L4D2_ACT_DLCINTRO_ZOEY_05, + L4D2_ACT_DLCINTRO_ZOEY_06, + L4D2_ACT_VM_FIZZLE, + L4D2_ACT_MP_STAND_IDLE, + L4D2_ACT_MP_CROUCH_IDLE, + L4D2_ACT_MP_CROUCH_DEPLOYED_IDLE, + L4D2_ACT_MP_CROUCH_DEPLOYED, + L4D2_ACT_MP_DEPLOYED_IDLE, + L4D2_ACT_MP_RUN, + L4D2_ACT_MP_WALK, + L4D2_ACT_MP_AIRWALK, + L4D2_ACT_MP_CROUCHWALK, + L4D2_ACT_MP_SPRINT, + L4D2_ACT_MP_JUMP, + L4D2_ACT_MP_JUMP_START, + L4D2_ACT_MP_JUMP_FLOAT, + L4D2_ACT_MP_JUMP_LAND, + L4D2_ACT_MP_DOUBLEJUMP, + L4D2_ACT_MP_SWIM, + L4D2_ACT_MP_DEPLOYED, + L4D2_ACT_MP_SWIM_DEPLOYED, + L4D2_ACT_MP_VCD, + L4D2_ACT_MP_ATTACK_STAND_PRIMARYFIRE, + L4D2_ACT_MP_ATTACK_STAND_PRIMARYFIRE_DEPLOYED, + L4D2_ACT_MP_ATTACK_STAND_SECONDARYFIRE, + L4D2_ACT_MP_ATTACK_STAND_GRENADE, + L4D2_ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, + L4D2_ACT_MP_ATTACK_CROUCH_PRIMARYFIRE_DEPLOYED, + L4D2_ACT_MP_ATTACK_CROUCH_SECONDARYFIRE, + L4D2_ACT_MP_ATTACK_CROUCH_GRENADE, + L4D2_ACT_MP_ATTACK_SWIM_PRIMARYFIRE, + L4D2_ACT_MP_ATTACK_SWIM_SECONDARYFIRE, + L4D2_ACT_MP_ATTACK_SWIM_GRENADE, + L4D2_ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE, + L4D2_ACT_MP_ATTACK_AIRWALK_SECONDARYFIRE, + L4D2_ACT_MP_ATTACK_AIRWALK_GRENADE, + L4D2_ACT_MP_RELOAD_STAND, + L4D2_ACT_MP_RELOAD_STAND_LOOP, + L4D2_ACT_MP_RELOAD_STAND_END, + L4D2_ACT_MP_RELOAD_CROUCH, + L4D2_ACT_MP_RELOAD_CROUCH_LOOP, + L4D2_ACT_MP_RELOAD_CROUCH_END, + L4D2_ACT_MP_RELOAD_SWIM, + L4D2_ACT_MP_RELOAD_SWIM_LOOP, + L4D2_ACT_MP_RELOAD_SWIM_END, + L4D2_ACT_MP_RELOAD_AIRWALK, + L4D2_ACT_MP_RELOAD_AIRWALK_LOOP, + L4D2_ACT_MP_RELOAD_AIRWALK_END, + L4D2_ACT_MP_ATTACK_STAND_PREFIRE, + L4D2_ACT_MP_ATTACK_STAND_POSTFIRE, + L4D2_ACT_MP_ATTACK_STAND_STARTFIRE, + L4D2_ACT_MP_ATTACK_CROUCH_PREFIRE, + L4D2_ACT_MP_ATTACK_CROUCH_POSTFIRE, + L4D2_ACT_MP_ATTACK_SWIM_PREFIRE, + L4D2_ACT_MP_ATTACK_SWIM_POSTFIRE, + L4D2_ACT_MP_STAND_PRIMARY, + L4D2_ACT_MP_CROUCH_PRIMARY, + L4D2_ACT_MP_RUN_PRIMARY, + L4D2_ACT_MP_WALK_PRIMARY, + L4D2_ACT_MP_AIRWALK_PRIMARY, + L4D2_ACT_MP_CROUCHWALK_PRIMARY, + L4D2_ACT_MP_JUMP_PRIMARY, + L4D2_ACT_MP_JUMP_START_PRIMARY, + L4D2_ACT_MP_JUMP_FLOAT_PRIMARY, + L4D2_ACT_MP_JUMP_LAND_PRIMARY, + L4D2_ACT_MP_SWIM_PRIMARY, + L4D2_ACT_MP_DEPLOYED_PRIMARY, + L4D2_ACT_MP_SWIM_DEPLOYED_PRIMARY, + L4D2_ACT_MP_ATTACK_STAND_PRIMARY, + L4D2_ACT_MP_ATTACK_STAND_PRIMARY_DEPLOYED, + L4D2_ACT_MP_ATTACK_CROUCH_PRIMARY, + L4D2_ACT_MP_ATTACK_CROUCH_PRIMARY_DEPLOYED, + L4D2_ACT_MP_ATTACK_SWIM_PRIMARY, + L4D2_ACT_MP_ATTACK_AIRWALK_PRIMARY, + L4D2_ACT_MP_RELOAD_STAND_PRIMARY, + L4D2_ACT_MP_RELOAD_STAND_PRIMARY_LOOP, + L4D2_ACT_MP_RELOAD_STAND_PRIMARY_END, + L4D2_ACT_MP_RELOAD_CROUCH_PRIMARY, + L4D2_ACT_MP_RELOAD_CROUCH_PRIMARY_LOOP, + L4D2_ACT_MP_RELOAD_CROUCH_PRIMARY_END, + L4D2_ACT_MP_RELOAD_SWIM_PRIMARY, + L4D2_ACT_MP_RELOAD_SWIM_PRIMARY_LOOP, + L4D2_ACT_MP_RELOAD_SWIM_PRIMARY_END, + L4D2_ACT_MP_RELOAD_AIRWALK_PRIMARY, + L4D2_ACT_MP_RELOAD_AIRWALK_PRIMARY_LOOP, + L4D2_ACT_MP_RELOAD_AIRWALK_PRIMARY_END, + L4D2_ACT_MP_ATTACK_STAND_GRENADE_PRIMARY, + L4D2_ACT_MP_ATTACK_CROUCH_GRENADE_PRIMARY, + L4D2_ACT_MP_ATTACK_SWIM_GRENADE_PRIMARY, + L4D2_ACT_MP_ATTACK_AIRWALK_GRENADE_PRIMARY, + L4D2_ACT_MP_STAND_SECONDARY, + L4D2_ACT_MP_CROUCH_SECONDARY, + L4D2_ACT_MP_RUN_SECONDARY, + L4D2_ACT_MP_WALK_SECONDARY, + L4D2_ACT_MP_AIRWALK_SECONDARY, + L4D2_ACT_MP_CROUCHWALK_SECONDARY, + L4D2_ACT_MP_JUMP_SECONDARY, + L4D2_ACT_MP_JUMP_START_SECONDARY, + L4D2_ACT_MP_JUMP_FLOAT_SECONDARY, + L4D2_ACT_MP_JUMP_LAND_SECONDARY, + L4D2_ACT_MP_SWIM_SECONDARY, + L4D2_ACT_MP_ATTACK_STAND_SECONDARY, + L4D2_ACT_MP_ATTACK_CROUCH_SECONDARY, + L4D2_ACT_MP_ATTACK_SWIM_SECONDARY, + L4D2_ACT_MP_ATTACK_AIRWALK_SECONDARY, + L4D2_ACT_MP_RELOAD_STAND_SECONDARY, + L4D2_ACT_MP_RELOAD_STAND_SECONDARY_LOOP, + L4D2_ACT_MP_RELOAD_STAND_SECONDARY_END, + L4D2_ACT_MP_RELOAD_CROUCH_SECONDARY, + L4D2_ACT_MP_RELOAD_CROUCH_SECONDARY_LOOP, + L4D2_ACT_MP_RELOAD_CROUCH_SECONDARY_END, + L4D2_ACT_MP_RELOAD_SWIM_SECONDARY, + L4D2_ACT_MP_RELOAD_SWIM_SECONDARY_LOOP, + L4D2_ACT_MP_RELOAD_SWIM_SECONDARY_END, + L4D2_ACT_MP_RELOAD_AIRWALK_SECONDARY, + L4D2_ACT_MP_RELOAD_AIRWALK_SECONDARY_LOOP, + L4D2_ACT_MP_RELOAD_AIRWALK_SECONDARY_END, + L4D2_ACT_MP_ATTACK_STAND_GRENADE_SECONDARY, + L4D2_ACT_MP_ATTACK_CROUCH_GRENADE_SECONDARY, + L4D2_ACT_MP_ATTACK_SWIM_GRENADE_SECONDARY, + L4D2_ACT_MP_ATTACK_AIRWALK_GRENADE_SECONDARY, + L4D2_ACT_MP_STAND_MELEE, + L4D2_ACT_MP_CROUCH_MELEE, + L4D2_ACT_MP_RUN_MELEE, + L4D2_ACT_MP_WALK_MELEE, + L4D2_ACT_MP_AIRWALK_MELEE, + L4D2_ACT_MP_CROUCHWALK_MELEE, + L4D2_ACT_MP_JUMP_MELEE, + L4D2_ACT_MP_JUMP_START_MELEE, + L4D2_ACT_MP_JUMP_FLOAT_MELEE, + L4D2_ACT_MP_JUMP_LAND_MELEE, + L4D2_ACT_MP_SWIM_MELEE, + L4D2_ACT_MP_ATTACK_STAND_MELEE, + L4D2_ACT_MP_ATTACK_STAND_MELEE_SECONDARY, + L4D2_ACT_MP_ATTACK_CROUCH_MELEE, + L4D2_ACT_MP_ATTACK_CROUCH_MELEE_SECONDARY, + L4D2_ACT_MP_ATTACK_SWIM_MELEE, + L4D2_ACT_MP_ATTACK_AIRWALK_MELEE, + L4D2_ACT_MP_ATTACK_STAND_GRENADE_MELEE, + L4D2_ACT_MP_ATTACK_CROUCH_GRENADE_MELEE, + L4D2_ACT_MP_ATTACK_SWIM_GRENADE_MELEE, + L4D2_ACT_MP_ATTACK_AIRWALK_GRENADE_MELEE, + L4D2_ACT_MP_STAND_ITEM1, + L4D2_ACT_MP_CROUCH_ITEM1, + L4D2_ACT_MP_RUN_ITEM1, + L4D2_ACT_MP_WALK_ITEM1, + L4D2_ACT_MP_AIRWALK_ITEM1, + L4D2_ACT_MP_CROUCHWALK_ITEM1, + L4D2_ACT_MP_JUMP_ITEM1, + L4D2_ACT_MP_JUMP_START_ITEM1, + L4D2_ACT_MP_JUMP_FLOAT_ITEM1, + L4D2_ACT_MP_JUMP_LAND_ITEM1, + L4D2_ACT_MP_SWIM_ITEM1, + L4D2_ACT_MP_ATTACK_STAND_ITEM1, + L4D2_ACT_MP_ATTACK_STAND_ITEM1_SECONDARY, + L4D2_ACT_MP_ATTACK_CROUCH_ITEM1, + L4D2_ACT_MP_ATTACK_CROUCH_ITEM1_SECONDARY, + L4D2_ACT_MP_ATTACK_SWIM_ITEM1, + L4D2_ACT_MP_ATTACK_AIRWALK_ITEM1, + L4D2_ACT_MP_STAND_ITEM2, + L4D2_ACT_MP_CROUCH_ITEM2, + L4D2_ACT_MP_RUN_ITEM2, + L4D2_ACT_MP_WALK_ITEM2, + L4D2_ACT_MP_AIRWALK_ITEM2, + L4D2_ACT_MP_CROUCHWALK_ITEM2, + L4D2_ACT_MP_JUMP_ITEM2, + L4D2_ACT_MP_JUMP_START_ITEM2, + L4D2_ACT_MP_JUMP_FLOAT_ITEM2, + L4D2_ACT_MP_JUMP_LAND_ITEM2, + L4D2_ACT_MP_SWIM_ITEM2, + L4D2_ACT_MP_ATTACK_STAND_ITEM2, + L4D2_ACT_MP_ATTACK_STAND_ITEM2_SECONDARY, + L4D2_ACT_MP_ATTACK_CROUCH_ITEM2, + L4D2_ACT_MP_ATTACK_CROUCH_ITEM2_SECONDARY, + L4D2_ACT_MP_ATTACK_SWIM_ITEM2, + L4D2_ACT_MP_ATTACK_AIRWALK_ITEM2, + L4D2_ACT_MP_GESTURE_FLINCH, + L4D2_ACT_MP_GESTURE_FLINCH_PRIMARY, + L4D2_ACT_MP_GESTURE_FLINCH_SECONDARY, + L4D2_ACT_MP_GESTURE_FLINCH_MELEE, + L4D2_ACT_MP_GESTURE_FLINCH_ITEM1, + L4D2_ACT_MP_GESTURE_FLINCH_ITEM2, + L4D2_ACT_MP_GESTURE_FLINCH_HEAD, + L4D2_ACT_MP_GESTURE_FLINCH_CHEST, + L4D2_ACT_MP_GESTURE_FLINCH_STOMACH, + L4D2_ACT_MP_GESTURE_FLINCH_LEFTARM, + L4D2_ACT_MP_GESTURE_FLINCH_RIGHTARM, + L4D2_ACT_MP_GESTURE_FLINCH_LEFTLEG, + L4D2_ACT_MP_GESTURE_FLINCH_RIGHTLEG, + L4D2_ACT_MP_GRENADE1_DRAW, + L4D2_ACT_MP_GRENADE1_IDLE, + L4D2_ACT_MP_GRENADE1_ATTACK, + L4D2_ACT_MP_GRENADE2_DRAW, + L4D2_ACT_MP_GRENADE2_IDLE, + L4D2_ACT_MP_GRENADE2_ATTACK, + L4D2_ACT_MP_PRIMARY_GRENADE1_DRAW, + L4D2_ACT_MP_PRIMARY_GRENADE1_IDLE, + L4D2_ACT_MP_PRIMARY_GRENADE1_ATTACK, + L4D2_ACT_MP_PRIMARY_GRENADE2_DRAW, + L4D2_ACT_MP_PRIMARY_GRENADE2_IDLE, + L4D2_ACT_MP_PRIMARY_GRENADE2_ATTACK, + L4D2_ACT_MP_SECONDARY_GRENADE1_DRAW, + L4D2_ACT_MP_SECONDARY_GRENADE1_IDLE, + L4D2_ACT_MP_SECONDARY_GRENADE1_ATTACK, + L4D2_ACT_MP_SECONDARY_GRENADE2_DRAW, + L4D2_ACT_MP_SECONDARY_GRENADE2_IDLE, + L4D2_ACT_MP_SECONDARY_GRENADE2_ATTACK, + L4D2_ACT_MP_MELEE_GRENADE1_DRAW, + L4D2_ACT_MP_MELEE_GRENADE1_IDLE, + L4D2_ACT_MP_MELEE_GRENADE1_ATTACK, + L4D2_ACT_MP_MELEE_GRENADE2_DRAW, + L4D2_ACT_MP_MELEE_GRENADE2_IDLE, + L4D2_ACT_MP_MELEE_GRENADE2_ATTACK, + L4D2_ACT_MP_ITEM1_GRENADE1_DRAW, + L4D2_ACT_MP_ITEM1_GRENADE1_IDLE, + L4D2_ACT_MP_ITEM1_GRENADE1_ATTACK, + L4D2_ACT_MP_ITEM1_GRENADE2_DRAW, + L4D2_ACT_MP_ITEM1_GRENADE2_IDLE, + L4D2_ACT_MP_ITEM1_GRENADE2_ATTACK, + L4D2_ACT_MP_ITEM2_GRENADE1_DRAW, + L4D2_ACT_MP_ITEM2_GRENADE1_IDLE, + L4D2_ACT_MP_ITEM2_GRENADE1_ATTACK, + L4D2_ACT_MP_ITEM2_GRENADE2_DRAW, + L4D2_ACT_MP_ITEM2_GRENADE2_IDLE, + L4D2_ACT_MP_ITEM2_GRENADE2_ATTACK, + L4D2_ACT_MP_STAND_BUILDING, + L4D2_ACT_MP_CROUCH_BUILDING, + L4D2_ACT_MP_RUN_BUILDING, + L4D2_ACT_MP_WALK_BUILDING, + L4D2_ACT_MP_AIRWALK_BUILDING, + L4D2_ACT_MP_CROUCHWALK_BUILDING, + L4D2_ACT_MP_JUMP_BUILDING, + L4D2_ACT_MP_JUMP_START_BUILDING, + L4D2_ACT_MP_JUMP_FLOAT_BUILDING, + L4D2_ACT_MP_JUMP_LAND_BUILDING, + L4D2_ACT_MP_SWIM_BUILDING, + L4D2_ACT_MP_ATTACK_STAND_BUILDING, + L4D2_ACT_MP_ATTACK_CROUCH_BUILDING, + L4D2_ACT_MP_ATTACK_SWIM_BUILDING, + L4D2_ACT_MP_ATTACK_AIRWALK_BUILDING, + L4D2_ACT_MP_ATTACK_STAND_GRENADE_BUILDING, + L4D2_ACT_MP_ATTACK_CROUCH_GRENADE_BUILDING, + L4D2_ACT_MP_ATTACK_SWIM_GRENADE_BUILDING, + L4D2_ACT_MP_ATTACK_AIRWALK_GRENADE_BUILDING, + L4D2_ACT_MP_STAND_PDA, + L4D2_ACT_MP_CROUCH_PDA, + L4D2_ACT_MP_RUN_PDA, + L4D2_ACT_MP_WALK_PDA, + L4D2_ACT_MP_AIRWALK_PDA, + L4D2_ACT_MP_CROUCHWALK_PDA, + L4D2_ACT_MP_JUMP_PDA, + L4D2_ACT_MP_JUMP_START_PDA, + L4D2_ACT_MP_JUMP_FLOAT_PDA, + L4D2_ACT_MP_JUMP_LAND_PDA, + L4D2_ACT_MP_SWIM_PDA, + L4D2_ACT_MP_ATTACK_STAND_PDA, + L4D2_ACT_MP_ATTACK_SWIM_PDA, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP, + L4D2_ACT_MP_GESTURE_VC_NODYES, + L4D2_ACT_MP_GESTURE_VC_NODNO, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_NODYES_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_NODNO_PRIMARY, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_NODYES_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_NODNO_SECONDARY, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_MELEE, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_MELEE, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_MELEE, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_MELEE, + L4D2_ACT_MP_GESTURE_VC_NODYES_MELEE, + L4D2_ACT_MP_GESTURE_VC_NODNO_MELEE, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_ITEM1, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_ITEM1, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_ITEM1, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_ITEM1, + L4D2_ACT_MP_GESTURE_VC_NODYES_ITEM1, + L4D2_ACT_MP_GESTURE_VC_NODNO_ITEM1, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_ITEM2, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_ITEM2, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_ITEM2, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_ITEM2, + L4D2_ACT_MP_GESTURE_VC_NODYES_ITEM2, + L4D2_ACT_MP_GESTURE_VC_NODNO_ITEM2, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_BUILDING, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_BUILDING, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_BUILDING, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_BUILDING, + L4D2_ACT_MP_GESTURE_VC_NODYES_BUILDING, + L4D2_ACT_MP_GESTURE_VC_NODNO_BUILDING, + L4D2_ACT_MP_GESTURE_VC_HANDMOUTH_PDA, + L4D2_ACT_MP_GESTURE_VC_FINGERPOINT_PDA, + L4D2_ACT_MP_GESTURE_VC_FISTPUMP_PDA, + L4D2_ACT_MP_GESTURE_VC_THUMBSUP_PDA, + L4D2_ACT_MP_GESTURE_VC_NODYES_PDA, + L4D2_ACT_MP_GESTURE_VC_NODNO_PDA, + L4D2_ACT_VM_UNUSABLE, + L4D2_ACT_VM_UNUSABLE_TO_USABLE, + L4D2_ACT_VM_USABLE_TO_UNUSABLE, + L4D2_ACT_PRIMARY_VM_DRAW, + L4D2_ACT_PRIMARY_VM_HOLSTER, + L4D2_ACT_PRIMARY_VM_IDLE, + L4D2_ACT_PRIMARY_VM_PULLBACK, + L4D2_ACT_PRIMARY_VM_PRIMARYATTACK, + L4D2_ACT_PRIMARY_VM_SECONDARYATTACK, + L4D2_ACT_PRIMARY_VM_RELOAD, + L4D2_ACT_PRIMARY_VM_DRYFIRE, + L4D2_ACT_PRIMARY_VM_IDLE_TO_LOWERED, + L4D2_ACT_PRIMARY_VM_IDLE_LOWERED, + L4D2_ACT_PRIMARY_VM_LOWERED_TO_IDLE, + L4D2_ACT_SECONDARY_VM_DRAW, + L4D2_ACT_SECONDARY_VM_HOLSTER, + L4D2_ACT_SECONDARY_VM_IDLE, + L4D2_ACT_SECONDARY_VM_PULLBACK, + L4D2_ACT_SECONDARY_VM_PRIMARYATTACK, + L4D2_ACT_SECONDARY_VM_SECONDARYATTACK, + L4D2_ACT_SECONDARY_VM_RELOAD, + L4D2_ACT_SECONDARY_VM_DRYFIRE, + L4D2_ACT_SECONDARY_VM_IDLE_TO_LOWERED, + L4D2_ACT_SECONDARY_VM_IDLE_LOWERED, + L4D2_ACT_SECONDARY_VM_LOWERED_TO_IDLE, + L4D2_ACT_MELEE_VM_DRAW, + L4D2_ACT_MELEE_VM_HOLSTER, + L4D2_ACT_MELEE_VM_IDLE, + L4D2_ACT_MELEE_VM_PULLBACK, + L4D2_ACT_MELEE_VM_PRIMARYATTACK, + L4D2_ACT_MELEE_VM_SECONDARYATTACK, + L4D2_ACT_MELEE_VM_RELOAD, + L4D2_ACT_MELEE_VM_DRYFIRE, + L4D2_ACT_MELEE_VM_IDLE_TO_LOWERED, + L4D2_ACT_MELEE_VM_IDLE_LOWERED, + L4D2_ACT_MELEE_VM_LOWERED_TO_IDLE, + L4D2_ACT_PDA_VM_DRAW, + L4D2_ACT_PDA_VM_HOLSTER, + L4D2_ACT_PDA_VM_IDLE, + L4D2_ACT_PDA_VM_PULLBACK, + L4D2_ACT_PDA_VM_PRIMARYATTACK, + L4D2_ACT_PDA_VM_SECONDARYATTACK, + L4D2_ACT_PDA_VM_RELOAD, + L4D2_ACT_PDA_VM_DRYFIRE, + L4D2_ACT_PDA_VM_IDLE_TO_LOWERED, + L4D2_ACT_PDA_VM_IDLE_LOWERED, + L4D2_ACT_PDA_VM_LOWERED_TO_IDLE, + L4D2_ACT_ITEM1_VM_DRAW, + L4D2_ACT_ITEM1_VM_HOLSTER, + L4D2_ACT_ITEM1_VM_IDLE, + L4D2_ACT_ITEM1_VM_PULLBACK, + L4D2_ACT_ITEM1_VM_PRIMARYATTACK, + L4D2_ACT_ITEM1_VM_SECONDARYATTACK, + L4D2_ACT_ITEM1_VM_RELOAD, + L4D2_ACT_ITEM1_VM_DRYFIRE, + L4D2_ACT_ITEM1_VM_IDLE_TO_LOWERED, + L4D2_ACT_ITEM1_VM_IDLE_LOWERED, + L4D2_ACT_ITEM1_VM_LOWERED_TO_IDLE, + L4D2_ACT_ITEM2_VM_DRAW, + L4D2_ACT_ITEM2_VM_HOLSTER, + L4D2_ACT_ITEM2_VM_IDLE, + L4D2_ACT_ITEM2_VM_PULLBACK, + L4D2_ACT_ITEM2_VM_PRIMARYATTACK, + L4D2_ACT_ITEM2_VM_SECONDARYATTACK, + L4D2_ACT_ITEM2_VM_RELOAD, + L4D2_ACT_ITEM2_VM_DRYFIRE, + L4D2_ACT_ITEM2_VM_IDLE_TO_LOWERED, + L4D2_ACT_ITEM2_VM_IDLE_LOWERED, + L4D2_ACT_ITEM2_VM_LOWERED_TO_IDLE +} \ No newline at end of file diff --git a/scripting/include/left4dhooks_lux_library.inc b/scripting/include/left4dhooks_lux_library.inc new file mode 100644 index 0000000..037ab5c --- /dev/null +++ b/scripting/include/left4dhooks_lux_library.inc @@ -0,0 +1,1715 @@ +/** +* Copyright (C) 2023 LuxLuma +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +**/ + +#if defined _lux_library_included +#endinput +#endif +#define _lux_library_included + +#include +#include + +#tryinclude +#tryinclude +#tryinclude + +#define LUX_LIBRARY_VERSION "0.5.7" + +#define GIMMEDATA "lux_library" + +//l4d2 +#define DMG_FULLGIB (1 << 24) + +enum OS_Type +{ + OS_Unknown = -2, + OS_invalid = -1, + OS_windows = 0, + OS_linux, + OS_mac +} + +static stock void GetGameData(Handle &hGamedata) +{ + hGamedata = LoadGameConfigFile(GIMMEDATA); + if(hGamedata == null) + LogError("Failed to load \"%s.txt\" gamedata.", GIMMEDATA); +} + +/** + * Returns the OS of the server. + * Note: Pass null to use gamedata from lux_library + * + * @param hGamedata Handle to the gamedata file to get the OS type from. + * + * @return Windows, Linux, or Mac + * @error Invalid or unknown OS type. + **/ +stock OS_Type GetOSType(Handle &hGamedata=null) +{ + static OS_Type os = OS_Unknown; + if(os == OS_Unknown) + { + if(hGamedata == null) + { + GetGameData(hGamedata); + } + + os = view_as(GameConfGetOffset(hGamedata, "OS")); + delete hGamedata; + } + return os; +} + +/** + * An alternative to TeleportEntity that maintains lerped movement client-side when setting an entity's new origin. + * Note: Does not account for parented entities, uses world space. + * + * @param iEntity Entity index to set new origin of. + * @param vec New origin of the entity. + * + * @return True on success, false on failure. + * @error Invalid entity index, signature for function not found, or SDKCall failed. + **/ +stock bool SetAbsOrigin(int iEntity, const float vec[3]) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Entity); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CBaseEntity::SetAbsOrigin")) + { + PrepSDKCall_AddParameter(SDKType_Vector, SDKPass_Pointer); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep SDKCall 'CBaseEntity::SetAbsOrigin'"); + } + else + { + LogError("Error finding the 'CBaseEntity::SetAbsOrigin' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return false; + } + SDKCall(hSDKCall, iEntity, vec); + return true; +} + +/** + * An alternative to TeleportEntity that maintains lerped movement client-side when setting an entity's new velocity. + * Note: Does not account for parented entities, uses world space. + * Note: Does not overwrite "m_vecBaseVelocity". + * + * @param iEntity Entity index to set new velocity of. + * @param vec Velocity to apply to entity. + * + * @return True on success, false on failure. + * @error Invalid entity index, signature for function not found, or SDKCall failed. + **/ +stock bool SetAbsVelocity(int iEntity, const float vec[3]) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Entity); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CBaseEntity::SetAbsVelocity")) + { + PrepSDKCall_AddParameter(SDKType_Vector, SDKPass_Pointer); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep SDKCall 'CBaseEntity::SetAbsVelocity'"); + } + else + { + LogError("Error finding the 'CBaseEntity::SetAbsVelocity' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return false; + } + SDKCall(hSDKCall, iEntity, vec); + return true; +} + +/** + * An alternative to TeleportEntity that maintains lerped movement client-side when setting an entity's new angles. + * Note: Does not account for parented entities, uses world space. + * + * @param iEntity Entity index to set new angles of. + * @param vec New angles of the entity. + * + * @return True on success, false on failure. + * @error Invalid entity index, signature for function not found, or SDKCall failed. + **/ +stock bool SetAbsAngles(int iEntity, const float vec[3]) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Entity); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CBaseEntity::SetAbsAngles")) + { + PrepSDKCall_AddParameter(SDKType_Vector, SDKPass_Pointer); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep SDKCall 'CBaseEntity::SetAbsAngles'"); + } + else + { + LogError("Error finding the 'CBaseEntity::SetAbsAngles' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return false; + } + SDKCall(hSDKCall, iEntity, vec); + return true; +} + +/** + * Copies the origin and angles vectors for world space attachment index location. + * + * @param iEntity Entity index to get origin and angles vectors of. + * @param attachmentName Name of the attachment. + * @param vecOrigin Vector to store origin in. + * @param vecAngles Vector to store angles in. + * + * @return True if attachment vectors were copied, false otherwise. + * @error Invalid entity index or invalid attachment name. + **/ +stock bool GetAttachmentVectors(int iEntity, char[] attachmentName, float vecOrigin[3], float vecAngles[3]) +{ + int iAttachmentName = LookupAttachment(iEntity, attachmentName); + if(iAttachmentName == 0) + return false; + GetAttachment(iEntity, iAttachmentName, vecOrigin, vecAngles); + return true; +} + +/** + * Looks up an entity's attachment index via its name. + * + * @param iEntity Entity index of the attachment. + * @param attachmentName Name of the attachment. + * + * @return Attachment index, 0 for not found. + * @error Invalid entity index, invalid attachment name, + * signature for function not found, or SDKCall failed. + **/ +stock int LookupAttachment(int iEntity, char[] attachmentName) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Entity); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CBaseAnimating::LookupAttachment")) + { + PrepSDKCall_AddParameter(SDKType_String, SDKPass_Pointer); + PrepSDKCall_SetReturnInfo(SDKType_PlainOldData, SDKPass_Plain); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep 'CBaseAnimating::LookupAttachment'"); + } + else + { + LogError("Error finding the 'CBaseAnimating::LookupAttachment' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return 0; + } + return SDKCall(hSDKCall, iEntity, attachmentName); +} + + +/** + * Overloaded SDKCall->CBaseAnimating::GetAttachment(int a1, int a2, float *a3, float *a4) + * Copies the origin and angles vectors for world space attachment index location. + * Note: Invalid attachments point to entitiy origin. + * + * @param iEntity Entity index to get attachment of. + * @param iAttachment Attachment index on model. + * @param vecOrigin Vector to store origin in. + * @param vecAngles Vector to store angles in. + * + * @return True if attachment vectors were copied, false otherwise. + * @error Invalid entity index or invalid attachment name, + * signature for function not found, or SDKCall failed. + **/ +stock bool GetAttachment(int iEntity, int iAttachment, float vecOrigin[3], float vecAngles[3]) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Entity); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CBaseAnimating::GetAttachment")) + { + PrepSDKCall_AddParameter(SDKType_PlainOldData, SDKPass_Plain); + PrepSDKCall_AddParameter(SDKType_Vector, SDKPass_ByRef, _, VENCODE_FLAG_COPYBACK); + PrepSDKCall_AddParameter(SDKType_QAngle, SDKPass_ByRef, _, VENCODE_FLAG_COPYBACK); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep 'CBaseAnimating::GetAttachment'"); + } + else + { + LogError("Error finding the 'CBaseAnimating::GetAttachment' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return false; + } + SDKCall(hSDKCall, iEntity, iAttachment, vecOrigin, vecAngles); + return true; +} + +/** + * Checks whether a given position is in water. + * Note: Mostly works, but some brushes seem to have water in their contents. + * Warning: Currently broken and unreliable. + * + * @param vecOrigin Position to check for. + * + * @return True if position is located in the water, false otherwise. + **/ +stock bool IsPositionInWater(float vecOrigin[3]) +{ + Handle hTrace = TR_TraceRayEx(vecOrigin, vecOrigin, CONTENTS_WATER, RayType_EndPoint); + bool bSolid = TR_StartSolid(hTrace); + delete hTrace; + return bSolid; +} + +/** + * Sets DSP effect post audio FX. + * + * @param iClient Client index of the player. + * @param flDelay Delay before sending effect. + * @param dspEffectType DSP effect type see "scripts/dsp_presets.txt" + * + * @error Invalid client index. + **/ +stock void Terror_SetPendingDspEffect(int iClient, float flDelay, int dspEffectType) +{ + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + // Get CountdownTimer address + static int timerAddress = -1; + if(timerAddress == -1) + { + if(IsEngine == Engine_Left4Dead2) + timerAddress = FindSendPropInfo("CTerrorPlayer", "m_iBloodyHandsLevel") + 8; + else + timerAddress = FindSendPropInfo("CTerrorPlayer", "m_bloodyHandsPercent") + 4; + } + + //timerAddress + 4 = Duration + //timerAddress + 8 = TimeStamp + SetEntDataFloat(iClient, timerAddress + 4, flDelay); + SetEntDataFloat(iClient, timerAddress + 8, GetGameTime() + flDelay); + SetEntData(iClient, timerAddress + 12, dspEffectType); +} + +/** + * Sets the adrenaline effect duration of a survivor. + * + * @param iClient Client index of the survivor. + * @param flDuration Duration of the adrenaline effect. + * + * @error Invalid client index. + **/ +// L4D2 only. +stock void Terror_SetAdrenalineTime(int iClient, float flDuration) +{ + // Get CountdownTimer address + static int timerAddress = -1; + if(timerAddress == -1) + { + timerAddress = FindSendPropInfo("CTerrorPlayer", "m_bAdrenalineActive") - 12; + } + + //timerAddress + 4 = Duration + //timerAddress + 8 = TimeStamp + SetEntDataFloat(iClient, timerAddress + 4, flDuration); + SetEntDataFloat(iClient, timerAddress + 8, GetGameTime() + flDuration); + SetEntProp(iClient, Prop_Send, "m_bAdrenalineActive", (flDuration <= 0.0 ? 0 : 1), 1); +} + +/** + * Returns the remaining duration of a survivor's adrenaline effect. + * + * @param iClient Client index of the survivor. + * + * @return Remaining duration or -1.0 if there's no effect. + * @error Invalid client index. + **/ +// L4D2 only. +stock float Terror_GetAdrenalineTime(int iClient) +{ + // Get CountdownTimer address + static int timerAddress = -1; + if(timerAddress == -1) + { + timerAddress = FindSendPropInfo("CTerrorPlayer", "m_bAdrenalineActive") - 12; + } + + //timerAddress + 8 = TimeStamp + float flGameTime = GetGameTime(); + float flTime = GetEntDataFloat(iClient, timerAddress + 8); + if(flTime <= flGameTime) + return -1.0; + + return flTime - flGameTime; +} + +/** + * Calls CTerrorPlayer::OnRevivedByDefibrillator() + * + * @param iRevivee Client index be revived. + * @param iReviver Client index who revived can be same as revivee. + * @param iDeathModel Death model index, dead survivor model (survivor_death_model). + * + * @return True if revive was successful false otherwise. + * @error Invalid entity index or invalid attachment name, + * signature for function not found, or SDKCall failed. + **/ +stock bool Terror_ReviveDeathModel(int iRevivee, int iReviver, int iDeathModel) +{ + static Handle hSDKCall; + if(hSDKCall == null) + { + Handle hGamedata; + GetGameData(hGamedata); + + StartPrepSDKCall(SDKCall_Player); + if(PrepSDKCall_SetFromConf(hGamedata, SDKConf_Signature, "CTerrorPlayer::OnRevivedByDefibrillator")) + { + PrepSDKCall_AddParameter(SDKType_CBasePlayer, SDKPass_Pointer); + PrepSDKCall_AddParameter(SDKType_CBaseEntity, SDKPass_Pointer); + hSDKCall = EndPrepSDKCall(); + if(hSDKCall == null) + LogError("Unable to prep 'CTerrorPlayer::OnRevivedByDefibrillator'"); + } + else + { + LogError("Error finding the 'CTerrorPlayer::OnRevivedByDefibrillator' signature."); + } + delete hGamedata; + if(hSDKCall == null) + return false; + } + SDKCall(hSDKCall, iRevivee, iReviver, iDeathModel); + return true; +} + +/** + * Create a physics explosion that does not affect players. + * + * @param vecOrigin Origin of the explosion. + * @param iMagnitude Magnitude of the explosion limit of 100, explode more than once for more power. + * @param flRadius Radius of the explosion. + * @param bDamage True to damage props, false otherwise. + * @param flInnerRadius If not zero, the LOS is calculated from a point intersecting this sphere. + * + * @error Failed to create explosion. + **/ +stock void PhysicsExplode(float vecOrigin[3], int iMagnitude, float flRadius, bool bDamage=false, float flInnerRadius=0.0) +{ + static int iBoom = INVALID_ENT_REFERENCE; + + if(iBoom == INVALID_ENT_REFERENCE || !IsValidEntity(iBoom)) + { + iBoom = EntIndexToEntRef(CreateEntityByName("env_physexplosion")); + if(iBoom == INVALID_ENT_REFERENCE) + return; + + DispatchKeyValue(iBoom, "spawnflags", "0"); + DispatchSpawn(iBoom); + } + + if(bDamage) + { + DispatchKeyValue(iBoom, "spawnflags", "8"); + } + else + { + DispatchKeyValue(iBoom, "spawnflags", "9"); + } + + char sBuf[32]; + IntToString(iMagnitude, sBuf, sizeof(sBuf)); + DispatchKeyValue(iBoom, "magnitude", sBuf); + + IntToString(RoundFloat(flRadius), sBuf, sizeof(sBuf)); + DispatchKeyValue(iBoom, "radius", sBuf); + DispatchKeyValueFloat(iBoom, "inner_radius", flInnerRadius); + + TeleportEntity(iBoom, vecOrigin, NULL_VECTOR, NULL_VECTOR); + + AcceptEntityInput(iBoom, "Explode"); + RemoveEntity(iBoom); +} + +///////////////////////////////////////Temp ents + +/** + * Sets up an invisible explosion to push client-side physics. + * Note: The grenade launcher uses this to push bodies and other objects. + * Note: Left 4 Dead 2 only. + * + * @param vecOrigin Origin of the explosion in world space. + * @param flRadius Radius of the explosion. + * @param flMagnitude Magnitude of the explosion. + * + * @error Invalid effect index. + **/ +// L4D2 only. +stock void TE_SetupExplodeForce(float vecOrigin[3], float flRadius, float flMagnitude) +{ + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ExplosionForce"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ExplosionForce index"); + + } + + TE_Start("EffectDispatch"); + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteFloat("m_vOrigin.x", vecOrigin[0]); + TE_WriteFloat("m_vOrigin.y", vecOrigin[1]); + TE_WriteFloat("m_vOrigin.z", vecOrigin[2]); + TE_WriteFloat("m_flRadius", flRadius); + TE_WriteFloat("m_flMagnitude", flMagnitude); +} + +/** + * Creates a clientside physics prop. + * + * @param vecOrigin Origin of the prop in world space. + * @param iPrecacheModel Stringtable index of the prop. + * @param vecModelAngles Angles of the prop. + * @param vecVelocity Velocity used by explosion for pushing the prop. + * @param iFlags Flags to apply to the prop. Note: A value of "1" applies auto-despawn, unsupported models will despawn next client tick. + * @param iEffects Effects to apply to the prop. + * @param iSkin Skin of the prop's model. + * @param RGB Color of the prop's model. + **/ +stock void TE_SetupPhysicsProp(float vecModelOrigin[3], + int iPrecacheModel, + float vecModelAngles[3]={0.0, ...}, + float vecVelocity[3]={0.0, ...}, + int iFlags=0, + int iEffects=0, + int iSkin=0, + int RGB[3]={255, ...}) +{ + TE_Start("physicsprop"); + TE_WriteVector("m_vecOrigin", vecModelOrigin); + TE_WriteFloat("m_angRotation[0]", vecModelAngles[0]); + TE_WriteFloat("m_angRotation[1]", vecModelAngles[1]); + TE_WriteFloat("m_angRotation[2]", vecModelAngles[2]); + TE_WriteVector("m_vecVelocity", vecVelocity); + TE_WriteNum("m_nModelIndex", iPrecacheModel); + TE_WriteNum("m_nFlags", iFlags); + TE_WriteNum("m_nEffects", iEffects); + TE_WriteNum("r", RGB[0]); + TE_WriteNum("g", RGB[1]); + TE_WriteNum("b", RGB[2]); +} + +/** + * Sets up a dynamic light. + * Note: Only one can exist client-side per tick. New lights will replace old ones. + * + * @param vecOrigin Origin of the light in world space. + * @param RGB Color of the light. + * @param flRadius Radius of the light. + * @param flTime Time until the light despawns. + * @param flDecay Radius decay speed of the light. + * @param exponent Brightness of the light. + * + * @return True on success, false on failure. + **/ +stock void TE_SetupDynamicLight(float vecOrigin[3], int RGB[3], float flRadius, float flTime, float flDecay=0.0, int exponent=0) +{ + TE_Start("Dynamic Light"); + + TE_WriteVector("m_vecOrigin", vecOrigin); + TE_WriteNum("r", RGB[0]); + TE_WriteNum("g", RGB[1]); + TE_WriteNum("b", RGB[2]); + TE_WriteNum("exponent", exponent); + TE_WriteFloat("m_fRadius", flRadius); + TE_WriteFloat("m_fTime", flTime); + TE_WriteFloat("m_fDecay", flDecay); +} + +/** + * Sets up a particle effect's attachment. + * + * @param iParticleIndex Particle index. + * @param sAttachmentName Name of attachment. + * @param iEntIndex Entity index of the particle. + * @param bFollow True to make the particle follow attachment points, false otherwise. + * + * @error Invalid effect index. + **/ +stock void TE_SetupParticleAttachment(int iParticleIndex, int iAttachmentIndex, int iEntIndex, bool bFollow=false) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecDummy[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecDummy[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", iParticleIndex); + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", iAttachmentIndex); + TE_WriteNum("m_fFlags", 1); //needed for attachments to work + + + TE_WriteVector("m_vAngles", vecDummy); + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 1.0); + TE_WriteFloat("m_flRadius", 0.0); + + if(IsEngine == Engine_Left4Dead2) + { + TE_WriteNum("m_nDamageType", bFollow ? 5 : 4); + } + else + { + TE_WriteNum("m_nDamageType", bFollow ? 4 : 3); + } +} + +/** + * Sets up a particle effect. + * Note: Particles that need an ending point to show do not use particle angles usually. + * Warning: Looping particles will last forever with no known way of removing them. + * + * @param iParticleIndex Particle index. + * @param vecParticleStartPos Starting point of the particle in world space. + * @param vecParticleEndPos Ending point of the particle in world space. + * @param vecParticleAngles Angles of the particle. + * @param iEntity Entity owner if entity dies so does particle. + * + * @error Invalid effect index. + **/ +stock void TE_SetupParticle(int iParticleIndex, float vecParticleStartPos[3], float vecParticleEndPos[3]={0.0, 0.0, 0.0}, float vecParticleAngles[3]={0.0, 0.0, 0.0}, int iEntity=0) +{ + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecParticleEndPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecParticleEndPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecParticleEndPos[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", iParticleIndex); + + TE_WriteNum("entindex", iEntity); + TE_WriteNum("m_nAttachmentIndex", 0); + TE_WriteNum("m_fFlags", 0); + + TE_WriteVector("m_vAngles", vecParticleAngles); + + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 1.0); + TE_WriteFloat("m_flRadius", 0.0); + TE_WriteNum("m_nDamageType", 0); +} + +/** + * Sets up a particle effect to follow an entity's origin (0, 0, 0). + * + * @param iParticleIndex Particle index. + * @param iEntIndex Entity index to follow. + * @param vecParticleAngles Angles of the particle. + * + * @error Invalid effect index. + **/ +stock void TE_SetupParticleFollowEntity(int iParticleIndex, int iEntIndex, float vecParticleAngles[3]={0.0, 0.0, 0.0}) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecDummy[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecDummy[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", iParticleIndex); + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", 0); + TE_WriteNum("m_fFlags", 1); + + + TE_WriteVector("m_vAngles", vecParticleAngles); + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 1.0); + TE_WriteFloat("m_flRadius", 0.0); + + TE_WriteNum("m_nDamageType", 1); +} + +/** + * Sets up a particle effect to follow an entity's origin (0, 0, 0) while maintaining offset. + * Note: Left 4 Dead 2 only maintains offset from the world origin of the parent, which is + * not reliable since this is not a server side entity, so lag can miscalculate the offset. + * + * @param iParticleIndex Particle index. + * @param iEntIndex Entity index to follow. + * @param vecParticleStartPos Starting point to maintain offset from. + * @param vecParticleAngles Angles of the particle. + * + * @error Invalid effect index. + **/ +// L4D2 only. +stock void TE_SetupParticleFollowEntity_MaintainOffset(int iParticleIndex, int iEntIndex, float vecParticleStartPos[3], float vecParticleAngles[3]={0.0, 0.0, 0.0}) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecDummy[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", iParticleIndex); + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", 0); + TE_WriteNum("m_fFlags", 1); + + + TE_WriteVector("m_vAngles", vecParticleAngles); + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 1.0); + TE_WriteFloat("m_flRadius", 0.0); + + TE_WriteNum("m_nDamageType", 3); +} + +/** + * Set up particle that attaches to points on a model that is predefined in particle i think. + * + * @param iParticleIndex Particle index. + * @param iEntIndex Entity index to attach. + * @param vecParticleStartPos Starting point valve uses it + * + * @error Invalid effect index. + **/ +stock void TE_SetupParticle_ControlPoints(int iParticleIndex, int iEntIndex, float vecParticleStartPos[3]) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecDummy[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", iParticleIndex); + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", 255); + TE_WriteNum("m_fFlags", 1); + + + TE_WriteVector("m_vAngles", vecDummy); + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 1.0); + TE_WriteFloat("m_flRadius", 0.0); + + TE_WriteNum("m_nDamageType", 0); +} + +/** + * Sets up a particle effect via its name to follow an entity's origin (0, 0, 0). + * + * @param sParticleName Name of the particle. + * @param iEntIndex Entity index to follow. + * @param vecParticleAngles Angles of the particle. + * + * @return True on success, false on failure. + * @error Invalid particle stringtable index. + **/ +stock bool TE_SetupParticleFollowEntity_Name(char[] sParticleName, int iEntIndex, float vecParticleAngles[3]={0.0, 0.0, 0.0}) +{ + int iParticleStringIndex = GetParticleIndex(sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + return false; + } + TE_SetupParticleFollowEntity(iParticleStringIndex, iEntIndex, vecParticleAngles); + return true; +} + +/** + * Sets up a particle effect via its name to follow an entity's origin (0, 0, 0) while maintaining offset. + * Note: Left 4 Dead 2 only maintains offset from the world origin of the parent, which is + * not reliable since this is not a server side entity, so lag can miscalculate the offset. + * + * @param sParticleName Name of the particle. + * @param iEntIndex Entity index to follow. + * @param vecParticleStartPos Starting point to maintain offset from. + * @param vecParticleAngles Angles of the particle. + * + * @return True on success, false on failure. + * @error Invalid particle stringtable index. + **/ +stock bool TE_SetupParticleFollowEntity_MaintainOffset_Name(char[] sParticleName, int iEntIndex, float vecParticleStartPos[3], float vecParticleAngles[3]={0.0, 0.0, 0.0}) +{ + int iParticleStringIndex = GetParticleIndex(sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + return false; + } + TE_SetupParticleFollowEntity_MaintainOffset(iParticleStringIndex, iEntIndex, vecParticleStartPos, vecParticleAngles); + return true; +} + +/** + * Sets up a particle effect via a name. + * Note: Particles that need an ending point to show do not use particle angles usually. + * Warning: Looping particles will last forever with no known way of removing them. + * + * @param sParticleName Name of the particle. + * @param vecParticleStartPos Starting point of the particle in world space. + * @param vecParticleEndPos Ending point of the particle in world space. + * @param vecParticleAngles Angles of the particle. + * @param iEntity Entity owner if entity dies so does particle. + * + * @return True on success, false on failure. + * @error Invalid effect index. + **/ +stock bool TE_SetupParticle_Name(char[] sParticleName, float vecParticleStartPos[3], float vecParticleEndPos[3]={0.0, 0.0, 0.0}, float vecParticleAngles[3]={0.0, 0.0, 0.0}, int iEntity=0) +{ + int iParticleStringIndex = GetParticleIndex(sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + return false; + } + TE_SetupParticle(iParticleStringIndex, vecParticleStartPos, vecParticleEndPos, vecParticleAngles, iEntity); + return true; +} + +/** + * Sets up a particle effect's attachment via a name. + * Note: Only follows entities that have attachment points. + * Warning: This function does not validate if the attachment is valid. + * + * @param sParticleName Name of the particle. + * @param sAttachmentName Name of the attachment. + * @param iEntIndex Entity index of the particle. + * @param bFollow True to make the particle follow attachment points, false otherwise. + * + * @return True on success, false on failure. + * @error Invalid particle stringtable index. + **/ +stock bool TE_SetupParticleAttachment_Names(char[] sParticleName, char[] sAttachmentName, int iEntIndex, bool bFollow=false) +{ + int iParticleStringIndex = GetParticleIndex(sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + return false; + } + int iAttachmentIndex = LookupAttachment(iEntIndex, sAttachmentName); + TE_SetupParticleAttachment(iParticleStringIndex, iAttachmentIndex, iEntIndex, bFollow); + return true; +} + +/** + * Stops all particle effects emitted on an entity, such as attachment followers. + * Note: Currently no way to target particles. + * + * @param iEntIndex Entity index to stop all particles from emitting on. + * + * @error Invalid effect index. + **/ +stock void TE_SetupStopAllParticles(int iEntIndex) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecDummy[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecDummy[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecDummy[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecDummy[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffectStop"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffectStop indexes"); + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", 0); + + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", 0); + TE_WriteNum("m_fFlags", 1); + TE_WriteVector("m_vAngles", vecDummy); + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 0.0); + TE_WriteFloat("m_flRadius", 0.0); + TE_WriteNum("m_nDamageType", 0); +} + +/** + * Sets up tracer sound for client-side. + * Note: Uses client-side ray from two points to play wizz sound. + * Note: Wizz sound is directional. + * + * @param vecParticleStartPos Starting position of the sound in world space. + * @param vecParticleEndPos Ending position of the sound in world space. + * + * @error Invalid effect index. + **/ +stock void TE_SetupTracerSound(float vecParticleStartPos[3], float vecParticleEndPos[3]) +{ + static float vecDummy[3]={0.0, 0.0, 0.0}; + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_Start("EffectDispatch"); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", vecParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", vecParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", vecParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", vecParticleEndPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", vecParticleEndPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", vecParticleEndPos[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "TracerSound"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/TracerSound indexes"); + + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + TE_WriteNum("m_nHitBox", 0); + + TE_WriteNum("entindex", 0); + TE_WriteNum("m_nAttachmentIndex", 0); + + TE_WriteNum("m_fFlags", 1); + + TE_WriteVector("m_vAngles", vecDummy); + + TE_WriteFloat("m_flMagnitude", 0.0); + TE_WriteFloat("m_flScale", 0.0); + TE_WriteFloat("m_flRadius", 0.0); + TE_WriteNum("m_nDamageType", 0); +} + +/** + * Credit: Dysphie for decal example + * Note to apply to static props pass 0(world) to iTarget and iHitbox is used for static prop index TR_GetHitBoxIndex() to trace it. + * + * @param vecOrigin Origin of the decal in world space. + * @param vecStart Starting point of the decal's origin. + * @param iTarget Entity index of the target to splash the decal on. + * @param iHitbox Hitbox or bodygroup to apply decal on. (Only required for static props.) + * @param iDecalIndex Decal index in the decal stringtable. + **/ +stock void TE_SetupEntityDecal(float vecOrigin[3], float vecStart[3], int iTarget, int iHitbox=0, int iPrecacheDecal) +{ + TE_Start("Entity Decal"); + TE_WriteVector("m_vecOrigin", vecOrigin); + TE_WriteVector("m_vecStart", vecStart); + TE_WriteNum("m_nEntity", iTarget); + TE_WriteNum("m_nHitbox", iHitbox); + TE_WriteNum("m_nIndex", iPrecacheDecal); +} + +/** + * Credit: Dysphie for decal example + * Sets up a world decal. + * + * @param vecOrigin Origin of the decal in world space. + * @param iDecalIndex Decal index in the decal stringtable, + **/ +stock void TE_SetupWorldDecal(float vecOrigin[3], int iPrecacheDecal) +{ + TE_Start("World Decal"); + TE_WriteVector("m_vecOrigin", vecOrigin); + TE_WriteNum("m_nIndex", iPrecacheDecal); +} + +/** + * Sets up a decal from a traceray. + * + * @param hTR Pass traceray handle or INVALID_HANDLE to use global trace result. + * @param sDecalName Name of the decal. + * + * @return true if decal was setup false otherwise. + * @error Invaid Handle. + **/ +stock bool TE_SetupDecal_FromTrace(Handle hTR=INVALID_HANDLE, char[] sDecalName) +{ + if(!TR_DidHit(hTR)) + return false; + + int iSurf = TR_GetSurfaceFlags(hTR); + if((iSurf & SURF_NODECALS) || (iSurf & SURF_NODRAW) || (iSurf & SURF_SKY)) + { + return false; + } + + int iPrecacheDecal = GetDecalIndex(sDecalName); + if(iPrecacheDecal == INVALID_STRING_TABLE) + return false; + + float vecStart[3]; + float vecEnd[3]; + int iTarget = TR_GetEntityIndex(hTR); + int iHitbox = TR_GetHitBoxIndex(hTR); + TR_GetStartPosition(hTR, vecStart); + TR_GetEndPosition(vecEnd, hTR); + + if(iTarget == 0) + { + if(iHitbox) + { + TE_SetupEntityDecal(vecEnd, vecStart, iTarget, iHitbox, iPrecacheDecal); + } + else + { + TE_SetupWorldDecal(vecEnd, iPrecacheDecal); + } + } + else + { + TE_SetupEntityDecal(vecEnd, vecStart, iTarget, iHitbox, iPrecacheDecal); + } + return true; +} + +/** + * Gets a Decal index or late precaches it. + * Note: Cache decal in OnMapStart() with PrecacheDecal to avoid them spewing errors. + * + * @param sDecalName Name of the particle system. + * + * @return The decal index or INVALID_STRING_INDEX on error. + * @error Invalid decal stringtable index. + **/ +stock int GetDecalIndex(char[] sDecalName) +{ + int iDecalIndex; + if(!IsDecalPrecached(sDecalName)) + { + iDecalIndex = PrecacheDecal(sDecalName); + +#if !defined DISABLE_PRINT_PRECACHE_ERRORS + if(iDecalIndex == INVALID_STRING_INDEX) + { + LogError("Unable to late precache of decal '%s'", sDecalName); + } + else + { + LogError("Late precache of decal '%s'", sDecalName); + } +#endif + + } + else + { + iDecalIndex = PrecacheDecal(sDecalName); + } + return iDecalIndex; +} + + +/** + * Gets a particle system index or late precaches it. + * Note: Cache particle systems in OnMapStart() with Precache_Particle_System to avoid them spewing errors. + * + * @param sParticleName Name of the particle system. + * + * @return The particle system index or INVALID_STRING_INDEX on error. + * @error Invalid particle stringtable index. + **/ +stock int GetParticleIndex(char[] sParticleName) +{ + static int iParticleTableid = INVALID_STRING_TABLE; + if(iParticleTableid == INVALID_STRING_TABLE) + { + iParticleTableid = FindStringTable("ParticleEffectNames"); + if(iParticleTableid == INVALID_STRING_TABLE) + SetFailState("Failed to find 'ParticleEffectNames' stringtable."); + } + + int iParticleStringIndex = __FindStringIndex2(iParticleTableid, sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + iParticleStringIndex = __PrecacheParticleSystem(sParticleName); + +#if !defined DISABLE_PRINT_PRECACHE_ERRORS + if(iParticleStringIndex == INVALID_STRING_INDEX) + { + LogError("Unable to late precache of particle '%s'", sParticleName); + } + else + { + LogError("Late precache of particle '%s'", sParticleName); + } +#endif + + } + return iParticleStringIndex; +} + +//Credit smlib https://github.com/bcserv/smlib +/** + * Rewrite of FindStringIndex, which failed to work correctly in previous tests. + * Searches for the index of a given string in a stringtable. + * + * @param tableidx Stringtable index. + * @param str String to find. + * @return The string index or INVALID_STRING_INDEX on error. + **/ +static stock int __FindStringIndex2(int tableidx, const char[] str) +{ + static char buf[1024]; + + int numStrings = GetStringTableNumStrings(tableidx); + for (int i=0; i < numStrings; i++) { + ReadStringTable(tableidx, i, buf, sizeof(buf)); + + if (StrEqual(buf, str)) { + return i; + } + } + + return INVALID_STRING_INDEX; +} + +//Credit smlib https://github.com/bcserv/smlib +/** + * Precaches the given particle system. + * Note: It's best to call this OnMapStart(). + * Note: Code based on Rochellecrab's, thanks. + * + * @param particleSystem Name of the particle system to precache. + * @return The particle system index or INVALID_STRING_INDEX on error. + **/ +static stock int __PrecacheParticleSystem(const char[] particleSystem) +{ + static int particleEffectNames = INVALID_STRING_TABLE; + + if (particleEffectNames == INVALID_STRING_TABLE) { + if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + } + + int index = __FindStringIndex2(particleEffectNames, particleSystem); + if (index == INVALID_STRING_INDEX) + { + int numStrings = GetStringTableNumStrings(particleEffectNames); + if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) + { + return INVALID_STRING_INDEX; + } + + AddToStringTable(particleEffectNames, particleSystem); + index = numStrings; + } + + return index; +} + +/** + * A wrapper function for SMLib's PrecacheParticleSystem to avoid include collisions. + * + * @param particlesystem Name of the particle system to precache. + * + * @return The particle system index or INVALID_STRING_INDEX on error. + **/ +stock int Precache_Particle_System(const char[] particleSystem) +{ + return __PrecacheParticleSystem(particleSystem); +} + +/** + * Get an entity's world space origin. + * Note: Not all entities may support "CollisionProperty" for getting the center. + * (https://github.com/LuxLuma/l4d2_structs/blob/master/collision_property.h) + * + * @param iEntity Entity index to get origin of. + * @param vecOrigin Vector to store origin in. + * @param bCenter True to get world space center, false otherwise. + * + * @error Invalid entity index. + **/ +stock void GetAbsOrigin(int iEntity, float vecOrigin[3], bool bCenter=false) +{ + GetEntPropVector(iEntity, Prop_Data, "m_vecAbsOrigin", vecOrigin); + + if(bCenter) + { + float vecMins[3]; + float vecMaxs[3]; + GetEntPropVector(iEntity, Prop_Send, "m_vecMins", vecMins); + GetEntPropVector(iEntity, Prop_Send, "m_vecMaxs", vecMaxs); + + vecOrigin[0] += (vecMins[0] + vecMaxs[0]) * 0.5; + vecOrigin[1] += (vecMins[1] + vecMaxs[1]) * 0.5; + vecOrigin[2] += (vecMins[2] + vecMaxs[2]) * 0.5; + } +} + + +///////////////////////////////////////Sound + + +/** + * level boost in some games maybe clamed, e.g. l4d max seems to be 150 + * pitch is clamed between 1-200, this maybe different between games. + * sndChannel static sound wont be replaced, however if overflowed it wont play any sound until static sounds have finished. + * + * @param sample sound file path. + * @param origin origin to emit sound from. + * @param entity entity to emit sound from. + * @param level sound level attenuation, the wav sound it's self matters. + * @param pitch sound pitch. + * @param sndChannel sound channel. + * @param rangeMin players within the min range sound wont be mixed. + * @param rangeCurve range curve until max mix can be achieved. + * @param levelBoost add level boost to mixed sounds max rangeCurve will apply levelBoost, half will apply half levelBoost. + * @param exponent exponent value to multiply, logarithmic. + * + * @error Invalid client index. + **/ +stock void EmitMixedAmbientSoundToAll(const char[] sample, + const float origin[3] = NULL_VECTOR, + int entity = SOUND_FROM_PLAYER, + int level = SNDLEVEL_NORMAL, + int pitch = SNDPITCH_NORMAL, + int sndChannel = SNDCHAN_AUTO, + float rangeMin, + float rangeCurve=1500.0, + int levelBoost=0, + float exponent=1.0) +{ + for(int i = 1; i <= MaxClients; ++i) + { + if(!IsClientInGame(i) || IsFakeClient(i)) + continue; + + EmitMixedAmbientSound(i, sample, origin, entity, level, pitch, sndChannel, rangeMin, rangeCurve, levelBoost, exponent); + } +} + +/** + * level boost in some games maybe clamed, e.g. l4d max seems to be 150 + * pitch is clamed between 1-200, this maybe different between games. + * sndChannel static sound wont be replaced, however if overflowed it wont play any sound until static sounds have finished. + * + * @param sample sound file path. + * @param origin origin to emit sound from. + * @param entity entity to emit sound from. + * @param level sound level attenuation, the wav sound it's self matters. + * @param pitch sound pitch. + * @param sndChannel sound channel. + * @param rangeMin players within the min range sound wont be mixed. + * @param rangeCurve range curve until max mix can be achieved, sample2 is played when 2x this value. + * @param levelBoost add level boost to mixed sounds max rangeCurve will apply levelBoost, half will apply half levelBoost. + * @param exponent exponent value to multiply, logarithmic. + * @param sample2 sound file path. + * @param level2 sound level attenuation. + * @param pitch2 sound pitch. + * + * @error Invalid client index. + **/ +stock void EmitMixedAmbientSoundToAll_FallBack(const char[] sample, + const float origin[3] = NULL_VECTOR, + int entity = SOUND_FROM_PLAYER, + int level = SNDLEVEL_NORMAL, + int pitch = SNDPITCH_NORMAL, + int sndChannel = SNDCHAN_AUTO, + float rangeMin, + float rangeCurve=1500.0, + int levelBoost=0, + float exponent=1.0, + const char[] sample2, + int level2 = SNDLEVEL_NORMAL, + int pitch2 = SNDPITCH_NORMAL) +{ + for(int i = 1; i <= MaxClients; ++i) + { + if(!IsClientInGame(i) || IsFakeClient(i)) + continue; + + EmitMixedAmbientSound_FallBack(i, sample, origin, entity, level, pitch, sndChannel, rangeMin, rangeCurve, levelBoost, exponent, sample2, level2, pitch2); + } +} + +/** + * level boost in some games maybe clamed, e.g. l4d max seems to be 150 + * pitch is clamed between 1-200, this maybe different between games. + * sndChannel static sound wont be replaced, however if overflowed it wont play any sound until static sounds have finished. + * + * @param client client index. + * @param sample sound file path. + * @param origin origin to emit sound from. + * @param entity entity to emit sound from. + * @param level sound level attenuation, the wav sound it's self matters. + * @param pitch sound pitch. + * @param sndChannel sound channel. + * @param rangeMin players within the min range sound wont be mixed. + * @param rangeCurve range curve until max mix can be achieved. + * @param levelBoost add level boost to mixed sounds max rangeCurve will apply levelBoost, half will apply half levelBoost. + * @param exponent exponent value to multiply, logarithmic. + * + * @error Invalid client index. + **/ +stock void EmitMixedAmbientSound(int client, const char[] sample, + const float origin[3] = NULL_VECTOR, + int entity = SOUND_FROM_PLAYER, + int level = SNDLEVEL_NORMAL, + int pitch = SNDPITCH_NORMAL, + int sndChannel = SNDCHAN_AUTO, + float rangeMin, + float rangeCurve=1500.0, + int levelBoost=0, + float exponent=1.0) +{ + static float vecEyePos[3]; + int newPitch; + float flDist; + float flDistPercent; + float flDistMulti; + int DistLevelBoost; + int viewEnt = -1; + + viewEnt = GetEntPropEnt(client, Prop_Send, "m_hViewEntity"); + if(viewEnt > 0) + { + GetAbsOrigin(viewEnt, vecEyePos); + } + else + { + GetClientEyePosition(client, vecEyePos); + } + flDist = GetVectorDistance(origin, vecEyePos); + + if(rangeCurve == 0.0) + { + LogError("RangeCurve == 0.0"); + return; + } + + flDist = (flDist - rangeMin < 0.0 ? 0.0 : flDist - rangeMin); + flDistPercent = (flDist / rangeCurve); + flDistMulti = (flDistPercent * 2) * exponent; + newPitch = pitch; + + if(flDistMulti > 1.0) + { + newPitch = FloatToInt(newPitch / (flDistMulti > 2.0 ? 2.0 : flDistMulti)); + } + + DistLevelBoost = FloatToInt((flDistPercent * exponent) * levelBoost); + if(DistLevelBoost > levelBoost) + DistLevelBoost = levelBoost; + + EmitSoundToClient(client, sample, entity, sndChannel, level + DistLevelBoost, _, _, newPitch, _, origin); +} + +/** + * level boost in some games maybe clamed, e.g. l4d max seems to be 150 + * pitch is clamed between 1-200, this maybe different between games. + * sndChannel static sound wont be replaced, however if overflowed it wont play any sound until static sounds have finished. + * + * @param client client index. + * @param sample sound file path. + * @param origin origin to emit sound from. + * @param entity entity to emit sound from. + * @param level sound level attenuation, the wav sound it's self matters. + * @param pitch sound pitch. + * @param sndChannel sound channel. + * @param rangeMin players within the min range sound wont be mixed. + * @param rangeCurve range curve until max mix can be achieved, sample2 is played when 2x this value. + * @param levelBoost add level boost to mixed sounds max rangeCurve will apply levelBoost, half will apply half levelBoost. + * @param exponent exponent value to multiply, logarithmic. + * @param sample2 sound file path. + * @param level2 sound level attenuation. + * @param pitch2 sound pitch. + * + * @error Invalid client index. + **/ +stock void EmitMixedAmbientSound_FallBack(int client, const char[] sample, + const float origin[3] = NULL_VECTOR, + int entity = SOUND_FROM_PLAYER, + int level = SNDLEVEL_NORMAL, + int pitch = SNDPITCH_NORMAL, + int sndChannel = SNDCHAN_AUTO, + float rangeMin, + float rangeCurve=1500.0, + int levelBoost=0, + float exponent=1.0, + const char[] sample2, + int level2 = SNDLEVEL_NORMAL, + int pitch2 = SNDPITCH_NORMAL) +{ + static float vecEyePos[3]; + int newPitch; + float flDist; + float flDistPercent; + float flDistMulti; + int DistLevelBoost; + int viewEnt = -1; + + viewEnt = GetEntPropEnt(client, Prop_Send, "m_hViewEntity"); + if(viewEnt > 0) + { + GetAbsOrigin(viewEnt, vecEyePos); + } + else + { + GetClientEyePosition(client, vecEyePos); + } + flDist = GetVectorDistance(origin, vecEyePos); + + if(rangeCurve == 0.0) + { + LogError("RangeCurve == 0.0"); + return; + } + + flDist = (flDist - rangeMin < 0.0 ? 0.0 : flDist - rangeMin); + flDistPercent = (flDist / rangeCurve); + flDistMulti = (flDistPercent * 2) * exponent; + + if(flDistMulti >= 2.0) + { + EmitSoundToClient(client, sample2, entity, sndChannel, level2, _, _, pitch2, _, origin); + return; + } + + newPitch = pitch; + if(flDistMulti > 1.0) + { + newPitch = FloatToInt(newPitch / (flDistMulti > 2.0 ? 2.0 : flDistMulti)); + } + + DistLevelBoost = FloatToInt((flDistPercent * exponent) * levelBoost); + if(DistLevelBoost > levelBoost) + DistLevelBoost = levelBoost; + + EmitSoundToClient(client, sample, entity, sndChannel, level + DistLevelBoost, _, _, newPitch, _, origin); +} + +int FloatToInt(float val) +{ + return RoundFloat(val); +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////Legacy Particle Stock/////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Creates a tempent particle. + * + * @param iParticleIndex Particle index location in the "ParticleEffectNames" stringtable. + * @param iEntIndex Entity index to attach particle to. + * @param fDelay Delay for the TE_SendToAll function. + * @param SendToAll True to send to all clients, false otherwise. You must call the send function yourself if sending to specific clients. + * @param sParticleName Name of the particle to find the index with. Only used if the particle index is invalid. + * @param iAttachmentIndex Attachment index of the particle. Decompile the model to retrieve this value. + * @param fParticleAngles Angles of the particle. Usually effects particles that have no gravity. + * @param iFlags Flags of the particle. Note: A value of "1" is required for attachment points and damage types. + * @param iDamageType The damage type of the particle. (Used in impact effect dispatches and attachment points need to be set to use.) + * @param fMagnitude The magnitude of the particle. (Needs testing; used in pipe bomb blast.) + * @param fScale The scale of the particle (doesn't apply to most particles). (Needs testing.) + * + * @return True on success, false on failure. + * @error Invalid effect index or invalid particle stringtable index. + **/ +#pragma deprecated Used for backwards compatibility. +stock bool L4D_TE_Create_Particle(float fParticleStartPos[3]={0.0, 0.0, 0.0}, + float fParticleEndPos[3]={0.0, 0.0, 0.0}, + int iParticleIndex=-1, + int iEntIndex=0, + float fDelay=0.0, + bool SendToAll=true, + char sParticleName[64]="", + int iAttachmentIndex=0, + float fParticleAngles[3]={0.0, 0.0, 0.0}, + int iFlags=0, + int iDamageType=0, + float fMagnitude=0.0, + float fScale=1.0, + float fRadius=0.0) +{ + TE_Start("EffectDispatch"); + + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vOrigin[0]", fParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vOrigin[1]", fParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vOrigin[2]", fParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vStart[0]", fParticleEndPos[0]);//end point usually for bulletparticles or ropes + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vStart[1]", fParticleEndPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vStart[2]", fParticleEndPos[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffect"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffect indexes"); + + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + + if(iParticleIndex < 0) + { + static int iParticleStringIndex = INVALID_STRING_INDEX; + iParticleStringIndex = __FindStringIndex2(FindStringTable("ParticleEffectNames"), sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + return false; + + TE_WriteNum("m_nHitBox", iParticleStringIndex); + } + else + TE_WriteNum("m_nHitBox", iParticleIndex); + + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", iAttachmentIndex); + + TE_WriteVector("m_vAngles", fParticleAngles); + + TE_WriteNum("m_fFlags", iFlags); + TE_WriteFloat("m_flMagnitude", fMagnitude);// saw this being used in pipebomb needs testing what it does probs shaking screen? + TE_WriteFloat("m_flScale", fScale); + TE_WriteFloat("m_flRadius", fRadius);// saw this being used in pipebomb needs testing what it does probs shaking screen? + TE_WriteNum("m_nDamageType", iDamageType);// this shit is required dunno why for attachpoint emitting valve probs named it wrong + + if(SendToAll) + TE_SendToAll(fDelay); + + return true; +} + +/** + * Stops a tempent particle. + * + * @param fParticleStartPos Starting position of the particle. + * @param fParticleEndPos Ending position of the particle. + * @param iParticleIndex Particle index location in the "ParticleEffectNames" stringtable. + * @param iEntIndex Entity index to attach particle to. + * @param fDelay Delay for the TE_SendToAll function. + * @param SendToAll True to send to all clients, false otherwise. You must call the send function yourself if sending to specific clients. + * @param sParticleName Name of the particle to find the index with. Only used if the particle index is invalid. + * @param iAttachmentIndex Attachment index of the particle. Decompile the model to retrieve this value. + * @param fParticleAngles Angles of the particle. Usually effects particles that have no gravity. + * @param iFlags Flags of the particle. + * @param iDamageType The damage type of the particle. (Used in impact effect dispatches and attachment points need to be set to use.) + * @param fMagnitude The magnitude of the particle. (Needs testing; used in pipe bomb blast.) + * @param fScale The scale of the particle (doesn't apply to most particles). (Needs testing.) + * @param fRadius The radius of the particle. + * + * @return True on success, false on failure. + * @error Invalid effect index or invalid particle stringtable index. + **/ +#pragma deprecated Used only for backwards compatibility. +stock bool L4D_TE_Stop_Particle(float fParticleStartPos[3]={0.0, 0.0, 0.0}, + float fParticleEndPos[3]={0.0, 0.0, 0.0}, + int iParticleIndex=-1, + int iEntIndex=0, + float fDelay=0.0, + bool SendToAll=true, + char sParticleName[64]="", + int iAttachmentIndex=0, + float fParticleAngles[3]={0.0, 0.0, 0.0}, + int iFlags=0, + int iDamageType=0, + float fMagnitude=0.0, + float fScale=1.0, + float fRadius=0.0) +{ + TE_Start("EffectDispatch"); + + static EngineVersion IsEngine; + if(IsEngine == Engine_Unknown) + IsEngine = GetEngineVersion(); + + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.x" :"m_vStart[0]", fParticleStartPos[0]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.y" :"m_vStart[1]", fParticleStartPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vOrigin.z" :"m_vStart[2]", fParticleStartPos[2]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.x" :"m_vOrigin[0]", fParticleEndPos[0]);//end point usually for bulletparticles or ropes + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.y" :"m_vOrigin[1]", fParticleEndPos[1]); + TE_WriteFloat(IsEngine == Engine_Left4Dead2 ? "m_vStart.z" :"m_vOrigin[2]", fParticleEndPos[2]); + + static int iEffectIndex = INVALID_STRING_INDEX; + if(iEffectIndex < 0) + { + iEffectIndex = __FindStringIndex2(FindStringTable("EffectDispatch"), "ParticleEffectStop"); + if(iEffectIndex == INVALID_STRING_INDEX) + SetFailState("Unable to find EffectDispatch/ParticleEffectStop indexes"); + + } + + TE_WriteNum("m_iEffectName", iEffectIndex); + + if(iParticleIndex < 0) + { + static int iParticleStringIndex = INVALID_STRING_INDEX; + iParticleStringIndex = __FindStringIndex2(FindStringTable("ParticleEffectNames"), sParticleName); + if(iParticleStringIndex == INVALID_STRING_INDEX) + return false; + + TE_WriteNum("m_nHitBox", iParticleStringIndex); + } + else + TE_WriteNum("m_nHitBox", iParticleIndex); + + TE_WriteNum("entindex", iEntIndex); + TE_WriteNum("m_nAttachmentIndex", iAttachmentIndex); + + TE_WriteVector("m_vAngles", fParticleAngles); + + TE_WriteNum("m_fFlags", iFlags); + TE_WriteFloat("m_flMagnitude", fMagnitude);// saw this being used in pipebomb needs testing what it does probs shaking screen? + TE_WriteFloat("m_flScale", fScale); + TE_WriteFloat("m_flRadius", fRadius);// saw this being used in pipebomb needs testing what it does probs shaking screen? + TE_WriteNum("m_nDamageType", iDamageType);// this shit is required dunno why for attachpoint emitting valve probs named it wrong + + if(SendToAll) + TE_SendToAll(fDelay); + + return true; +} +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/scripting/include/left4dhooks_silver.inc b/scripting/include/left4dhooks_silver.inc new file mode 100644 index 0000000..49a46ea --- /dev/null +++ b/scripting/include/left4dhooks_silver.inc @@ -0,0 +1,1254 @@ +/* +* Left 4 DHooks Direct - Stock Functions +* Copyright (C) 2023 Silvers +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +#if defined _l4d_silver_included + #endinput +#endif +#define _l4d_silver_included + +#include +#include + +#tryinclude +#tryinclude +#tryinclude + + + + + +// ==================================================================================================== +// ENUMS +// ==================================================================================================== +enum +{ + L4D_TEAM_UNASSIGNED = 0, + L4D_TEAM_SPECTATOR = 1, + L4D_TEAM_SURVIVOR = 2, + L4D_TEAM_INFECTED = 3, + L4D_TEAM_FOUR = 4 +} + +enum +{ + L4D_WEAPON_SLOT_PRIMARY = 0, + L4D_WEAPON_SLOT_SECONDARY = 1, + L4D_WEAPON_SLOT_GRENADE = 2, + L4D_WEAPON_SLOT_MEDKIT = 3, // L4D2: Also upgrade ammo packs and defibrillator + L4D_WEAPON_SLOT_PILLS = 4, // L4D2: Also Adrenaline + L4D_WEAPON_SLOT_CARRIED = 5 // Physics props such as GasCan etc. +} + +enum +{ + L4D1_ZOMBIE_CLASS_SMOKER = 1, + L4D1_ZOMBIE_CLASS_BOOMER = 2, + L4D1_ZOMBIE_CLASS_HUNTER = 3, + L4D1_ZOMBIE_CLASS_WITCH = 4, + L4D1_ZOMBIE_CLASS_TANK = 5 +} + +enum +{ + L4D2_ZOMBIE_CLASS_SMOKER = 1, + L4D2_ZOMBIE_CLASS_BOOMER = 2, + L4D2_ZOMBIE_CLASS_HUNTER = 3, + L4D2_ZOMBIE_CLASS_SPITTER = 4, + L4D2_ZOMBIE_CLASS_JOCKEY = 5, + L4D2_ZOMBIE_CLASS_CHARGER = 6, + L4D2_ZOMBIE_CLASS_WITCH = 7, + L4D2_ZOMBIE_CLASS_TANK = 8 +} + +enum +{ + SERVER_OS_WINDOWS = 0, + SERVER_OS_LINUX = 1, +} + +// Thanks to "Dragokas": +enum // m_eDoorState +{ + DOOR_STATE_CLOSED, + DOOR_STATE_OPENING_IN_PROGRESS, + DOOR_STATE_OPENED, + DOOR_STATE_CLOSING_IN_PROGRESS +} + +// Thanks to "Dragokas": +enum // m_spawnflags +{ + DOOR_FLAG_STARTS_OPEN = 1, + DOOR_FLAG_STARTS_LOCKED = 2048, + DOOR_FLAG_SILENT = 4096, + DOOR_FLAG_USE_CLOSES = 8192, + DOOR_FLAG_SILENT_NPC = 16384, + DOOR_FLAG_IGNORE_USE = 32768, + DOOR_FLAG_UNBREAKABLE = 524288 +} + + + + + +// ==================================================================================================== +// STOCKS +// ==================================================================================================== + +// ================================================== +// ENGINE STOCKS +// ================================================== +static EngineVersion g_iEngine; + +/** + * @brief Returns if the server is running on the Left 4 Dead series engine + * + * @return Returns true if the server is running on the Left 4 Dead series + */ +stock bool L4D_IsEngineLeft4Dead() +{ + if( g_iEngine == Engine_Unknown ) + { + g_iEngine = GetEngineVersion(); + } + + return (g_iEngine == Engine_Left4Dead || g_iEngine == Engine_Left4Dead2); +} + +/** + * @brief Returns if the server is running on Left 4 Dead 1 + * + * @return Returns true if server is running on Left 4 Dead 1 + */ +stock bool L4D_IsEngineLeft4Dead1() +{ + if( g_iEngine == Engine_Unknown ) + { + g_iEngine = GetEngineVersion(); + } + + return g_iEngine == Engine_Left4Dead; +} + +/** + * @brief Returns if the server is running on Left 4 Dead 2 + * + * @return Returns true if server is running on Left 4 Dead 2 + */ +stock bool L4D_IsEngineLeft4Dead2() +{ + if( g_iEngine == Engine_Unknown ) + { + g_iEngine = GetEngineVersion(); + } + + return g_iEngine == Engine_Left4Dead2; +} + + + +// ================================================== +// DOOR STOCKS +// ================================================== + +/** + * @brief Returns the specified door state. Uses the "DOOR_STATE_*" enum + * + * @param entity The "prop_door*" entity to check + * + * @return the "DOOR_STATE_*" value + */ +stock int L4D_GetDoorState(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_eDoorState"); +} + +/** + * @brief Returns the specified door flags. Uses the "DOOR_FLAG_*" enum + * + * @param entity The "prop_door*" entity to check + * + * @return the "DOOR_FLAG_*" value + */ +stock int L4D_GetDoorFlag(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_spawnflags"); +} + + + +// ================================================== +// ENTITY STOCKS +// ================================================== + +/** + * @brief Returns a players current weapon, or -1 if none. + * + * @param client Client ID of the player to check + * + * @return weapon entity index or -1 if none + */ +stock int L4D_GetPlayerCurrentWeapon(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon"); +} + +/** + * @brief Returns the Custom Ability entity of a Special Infected + * @remarks Returns the entity of "ability_vomit" (Boomer), "ability_lunge" (Hunter), "ability_tongue" (Smoker), "ability_charge" (Charger), "ability_ride" (Jockey), "ability_spit" (Spitter), "ability_throw" (Tank) + * + * @param client Client ID of the player to check + * + * @return entity index or -1 if none + */ +stock int L4D_GetPlayerCustomAbility(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_customAbility"); +} + +/** + * @brief Returns the players Use Action Target + * + * @param client Client ID of the player to check + * + * @return entity index or -1 if none + */ +stock int L4D_GetPlayerUseTarget(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_useActionTarget"); +} + +/** + * @brief Returns the parent of an entity + * + * @param client Entity index to check + * + * @return entity index or -1 if none + */ +stock int L4D_EntityParent(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_pParent"); +} + +/** + * @brief Checks if a player is using any mounted weapon (minigun or 50cal) + * + * @param client Client to check + * + * @return true if using a mounted weapon, false otherwise + */ +stock bool IsUsingMinigun(int client) +{ + return ((GetEntProp(client, Prop_Send, "m_usingMountedWeapon") > 0) || (GetEntProp(client, Prop_Send, L4D_IsEngineLeft4Dead2() ? "m_usingMountedGun" : "m_usingMinigun") > 0)); +} + +/** + * @brief Stops a client using a mounted weapon + * + * @param client Entity index to check + * + * @return entity index or -1 if none + */ +stock void StopUsingMinigun(int client) +{ + if( IsUsingMinigun(client) ) + { + int entity = GetEntPropEnt(client, Prop_Send, "m_hUseEntity"); + if( entity > 0 && entity < 2048 ) + { + SetEntPropEnt(entity, Prop_Send, "m_owner", -1); + } + + SetEntProp(client, Prop_Send, L4D_IsEngineLeft4Dead2() ? "m_usingMountedGun" : "m_usingMinigun", 0); + SetEntProp(client, Prop_Send, "m_usingMountedWeapon", 0); + SetEntPropEnt(client, Prop_Send, "m_hUseEntity", -1); + } +} + +/** + * @brief Returns if a player is on fire + * + * @param client Client index to check + * + * @return true on fire, false otherwise + */ +stock bool L4D_IsPlayerOnFire(int client) +{ + if( GetEntProp(client, Prop_Data, "m_fFlags") & FL_ONFIRE ) return true; + else return false; +} + +/** + * @brief Returns if a player is burning + * + * @param client Client index to check + * + * @return true on burning, false otherwise + */ +stock bool L4D_IsPlayerBurning(int client) +{ + float fBurning = GetEntPropFloat(client, Prop_Send, "m_burnPercent"); + return (fBurning > 0.0) ? true : false; +} + +/** + * @brief Returns true if a physics object or alarmed car can be moved by the tank + * + * @param entity Entity index to check + * + * @return true if it can be moved, false otherwise + */ +stock bool L4D_IsTankProp(int entity) +{ + static char classname[16]; + + GetEdictClassname(entity, classname, sizeof(classname)); + + if( strcmp(classname, "prop_physics") == 0 ) + { + if( GetEntProp(entity, Prop_Send, "m_hasTankGlow") ) + { + return true; + } + } + else if( strcmp(classname, "prop_car_alarm") == 0 ) + { + return true; + } + + return false; +} + + + +// ================================================== +// COMMON INFECTED STOCKS +// ================================================== + +/** + * @brief Creates a panic event mob horde + * @remarks Subject to horde cooldown timer + * @remarks Can probably reset the timer with either "L4D_ResetMobTimer();" native or using "L4D2CT_MobSpawnTimer" with the timer natives. + * + * @noreturn + */ +stock void L4D_ForcePanicEvent() +{ + static EngineVersion engine; + + if( engine == Engine_Unknown ) + { + engine = GetEngineVersion(); + } + + if( engine == Engine_Left4Dead2 ) + { + static int director = INVALID_ENT_REFERENCE; + + if( director == INVALID_ENT_REFERENCE || EntRefToEntIndex(director) == INVALID_ENT_REFERENCE ) + { + director = FindEntityByClassname(-1, "info_director"); + if( director != INVALID_ENT_REFERENCE ) + { + director = EntIndexToEntRef(director); + } + } + + if( director != INVALID_ENT_REFERENCE ) + { + AcceptEntityInput(director, "ForcePanicEvent"); + return; + } + } + + int flags = GetCommandFlags("director_force_panic_event"); + SetCommandFlags("director_force_panic_event", flags & ~FCVAR_CHEAT); + ServerCommand("director_force_panic_event"); + SetCommandFlags("director_force_panic_event", flags); +} + +/** + * @brief Returns the current number of common infected + * + * @return entity index or -1 if none + */ +stock int L4D_GetCommonsCount() +{ + int entity = -1; + int count; + while( (entity = FindEntityByClassname(entity, "infected")) != INVALID_ENT_REFERENCE ) + { + count++; + } + + return count; +} + +/** + * @brief Spawns a Common Infected at the given position + * + * @param vPos Origin vector to spawn at + * @param vAng Angles vector to spawn at (optional) + * + * @return entity index or -1 on failure + */ +stock int L4D_SpawnCommonInfected(float vPos[3], float vAng[3] = { 0.0, 0.0, 0.0 }) +{ + int entity = CreateEntityByName("infected"); + if( entity != -1 ) + { + TeleportEntity(entity, vPos, vAng, NULL_VECTOR); + DispatchSpawn(entity); + } + + return entity; +} + + + +// ================================================== +// INFECTED: GET VICTIM +// ================================================== + +/** + * @brief Returns the Survivor victim when pinned by a Hunter + * + * @param client Client ID of the Special Infected player to check + * + * @return Victim client index, or 0 if none + */ +stock int L4D_GetVictimHunter(int client) +{ + int attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pounceVictim")) > 0 ) + return attacker; + + return 0; +} + +/** + * @brief Returns the Survivor victim when pinned by a Smoker + * + * @param client Client ID of the Special Infected player to check + * + * @return Victim client index, or 0 if none + */ +stock int L4D_GetVictimSmoker(int client) +{ + int attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_tongueVictim")) > 0 ) + return attacker; + + return 0; +} + +/** + * @brief Returns the Survivor victim when pinned by a Charger + * + * @param client Client ID of the Special Infected player to check + * + * @return Victim client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetVictimCharger(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pummelVictim")) > 0 ) + return attacker; + } + + return 0; +} + +/** + * @brief Returns the Survivor victim when carried by a Charger + * + * @param client Client ID of the Special Infected player to check + * + * @return Victim client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetVictimCarry(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_carryVictim")) > 0 ) + return attacker; + } + + return 0; +} + +/** + * @brief Returns the Survivor victim when pinned by a Jockey + * + * @param client Client ID of the Special Infected player to check + * + * @return Victim client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetVictimJockey(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_jockeyVictim")) > 0 ) + return attacker; + } + + return 0; +} + + + +// ================================================== +// SURVIVOR: GET ATTACKER +// ================================================== + +/** + * @brief Returns a Survivors attacker when pinned by a Hunter + * + * @param client Client ID of the Survivor player to check + * + * @return Attacker client index, or 0 if none + */ +stock int L4D_GetAttackerHunter(int client) +{ + int attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pounceAttacker")) > 0 ) + return attacker; + + return 0; +} + +/** + * @brief Returns a Survivors attacker when pinned by a Smoker + * + * @param client Client ID of the Survivor player to check + * + * @return Attacker client index, or 0 if none + */ +stock int L4D_GetAttackerSmoker(int client) +{ + int attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_tongueOwner")) > 0 ) + return attacker; + + return 0; +} + +/** + * @brief Returns a Survivors attacker when pummelled by a Charger + * + * @param client Client ID of the Survivor player to check + * + * @return Attacker client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetAttackerCharger(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pummelAttacker")) > 0 ) + return attacker; + } + + return 0; +} + +/** + * @brief Returns a Survivors attacker when carried by a Charger + * + * @param client Client ID of the Survivor player to check + * + * @return Attacker client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetAttackerCarry(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_carryAttacker")) > 0 ) + return attacker; + } + + return 0; +} + +/** + * @brief Returns a Survivors attacker when pinned by a Jockey + * + * @param client Client ID of the Survivor player to check + * + * @return Attacker client index, or 0 if none + */ +// L4D2 only. +stock int L4D_GetAttackerJockey(int client) +{ + int attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_jockeyAttacker")) > 0 ) + return attacker; + } + + return 0; +} + + + +// ================================================== +// PINNED CHECKS +// ================================================== + +/** + * @brief Returns the attacker when a Survivor is pinned by a Special Infected + * + * @param client Client ID of the player to check + * + * @return Attacker client index, or 0 if none + */ +stock int L4D_GetPinnedInfected(int client) +{ + int attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pounceAttacker")) > 0 ) + return attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_tongueOwner")) > 0 ) + return attacker; + + if( L4D_IsEngineLeft4Dead2() ) + { + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_jockeyAttacker")) > 0 ) + return attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_pummelAttacker")) > 0 ) + return attacker; + + if( (attacker = GetEntPropEnt(client, Prop_Send, "m_carryAttacker")) > 0 ) + return attacker; + } + + return 0; +} + +/** + * @brief Returns the victim when a Survivor is pinned by a Special Infected + * + * @param client Client ID of the player to check + * + * @return Attacker client index, or 0 if none + */ +stock int L4D_GetPinnedSurvivor(int client) +{ + int class = GetEntProp(client, Prop_Send, "m_zombieClass"); + int victim; + + if( L4D_IsEngineLeft4Dead2() ) + { + switch( class ) + { + case 1: victim = GetEntPropEnt(client, Prop_Send, "m_tongueVictim"); + case 3: victim = GetEntPropEnt(client, Prop_Send, "m_pounceVictim"); + case 5: victim = GetEntPropEnt(client, Prop_Send, "m_jockeyVictim"); + case 6: + { + victim = GetEntPropEnt(client, Prop_Send, "m_pummelVictim"); + if( victim < 1 ) victim = GetEntPropEnt(client, Prop_Send, "m_carryVictim"); + } + } + } + else + { + switch( class ) + { + case 1: victim = GetEntPropEnt(client, Prop_Send, "m_tongueVictim"); + case 3: victim = GetEntPropEnt(client, Prop_Send, "m_pounceVictim"); + } + } + + if( victim > 0 ) + return victim; + + return 0; +} + +/** + * @brief Returns true when someone is being carried/pummelled by more than 1 Charger + * + * @param client Client ID of the player to check + * + * @return Returns true when someone is being carried/pummelled by more than 1 Charger + */ +// L4D2 only. +stock bool L4D2_IsMultiCharged(int victim) +{ + if( !L4D_IsEngineLeft4Dead2() ) + ThrowError("Stock only supports L4D2."); + + int count; + + for( int i = 1; i <= MaxClients; i++ ) + { + if( !IsClientInGame(i) ) + continue; + + else if( GetClientTeam(i) != 3 ) + continue; + + else if( L4D2_GetPlayerZombieClass(i) != L4D2ZombieClass_Charger ) + continue; + + if( L4D_GetVictimCarry(i) == victim || L4D_GetVictimCharger(i) == victim ) + count++; + } + + return count >= 2; +} + +/** + * @brief Returns if a Survivor is pinned by a Special Infected + * + * @param client Client ID of the player to check + * + * @return Returns true if pinned, false otherwise + */ +stock bool L4D_IsPlayerPinned(int client) +{ + return L4D_GetPinnedInfected(client) != 0; +} + +/** + * @brief Returns if a Survivor is being attacked in the Smokers arms + * + * @param client Client ID of the player to check + * + * @return Returns true if player has reached the Smoker, false otherwise + */ +stock bool L4D_HasReachedSmoker(int client) +{ + // m_isHangingFromTongue sometimes returns 1 when still being dragged, using this instead + return GetEntProp(client, Prop_Send, "m_reachedTongueOwner", 1) == 1; +} + + + +// ================================================== +// CHARGER STOCKS - Written by "Forgetest" +// ================================================== +#define QueuedPummel_Victim 0 +#define QueuedPummel_StartTime 4 +#define QueuedPummel_Attacker 8 + +/** + * @brief Internally used to get offset to the start of queued pummel field. + * + * @return Offset into CTerrorPlayer to the start of queued pummel props + */ +static stock int L4D2_OffsQueuedPummelInfo() +{ + static int m_hQueuedPummelVictim = -1; + if( m_hQueuedPummelVictim == -1 ) + m_hQueuedPummelVictim = FindSendPropInfo("CTerrorPlayer", "m_pummelAttacker") + 4; + + return m_hQueuedPummelVictim; +} + +/** + * @brief Returns the timestamp when the queued pummel begins. + * + * @param client Client ID of the charger to check + * + * @return timestamp or -1.0 if no queued pummel + */ +stock float L4D2_GetQueuedPummelStartTime(int charger) +{ + return GetEntDataFloat(charger, L4D2_OffsQueuedPummelInfo() + QueuedPummel_StartTime); +} + +/** + * @brief Sets the timestamp when the queued pummel begins. + * + * @param client Client ID of the charger to check + * @param timestamp Timestamp to set + * + * @noreturn + */ +stock void L4D2_SetQueuedPummelStartTime(int charger, float timestamp) +{ + SetEntDataFloat(charger, L4D2_OffsQueuedPummelInfo() + QueuedPummel_StartTime, timestamp); +} + +/** + * @brief Returns if a Charger is in a queued pummel. + * + * @param charger Client ID of the charger to check + * + * @return true if in queued pummel, false otherwise + */ +stock bool L4D2_IsInQueuedPummel(int charger) +{ + float flTimestamp = L4D2_GetQueuedPummelStartTime(charger); + + return flTimestamp != -1.0 && flTimestamp > GetGameTime(); +} + +/** + * @brief Returns the victim of a Charger in a queued pummel. + * + * @param client Client ID of the player to check + * + * @return client index or -1 if none + */ +stock int L4D2_GetQueuedPummelVictim(int client) +{ + return GetEntDataEnt2(client, L4D2_OffsQueuedPummelInfo() + QueuedPummel_Victim); +} + +/** + * @brief Sets the victim of a Charger in a queued pummel. + * + * @param client Client ID of the player to set + * @param target Client ID of the target to set + * + * @noreturn + */ +stock void L4D2_SetQueuedPummelVictim(int client, int target) +{ + SetEntDataEnt2(client, L4D2_OffsQueuedPummelInfo() + QueuedPummel_Victim, target); +} + +/** + * @brief Returns the attacker of a Survivor in a queued pummel. + * + * @param client Client ID of the player to check + * + * @return client index or -1 if none + */ +stock int L4D2_GetQueuedPummelAttacker(int client) +{ + return GetEntDataEnt2(client, L4D2_OffsQueuedPummelInfo() + QueuedPummel_Attacker); +} + +/** + * @brief Sets the attacker of a Survivor in a queued pummel. + * + * @param client Client ID of the player to set + * @param target Client ID of the target to set + * + * @noreturn + */ +stock void L4D2_SetQueuedPummelAttacker(int client, int target) +{ + SetEntDataEnt2(client, L4D2_OffsQueuedPummelInfo() + QueuedPummel_Attacker, target); +} + + + +// ================================================== +// LEDGE HANG STOCKS +// ================================================== + +/** + * @brief Returns if a Survivor is hanging from a ledge + * + * @param client Client ID of the player to check + * + * @return Returns true if hanging, false otherwise + */ +stock bool L4D_IsPlayerHangingFromLedge(int client) +{ + return GetEntProp(client, Prop_Send, "m_isHangingFromLedge", 1) == 1; +} + +/** + * @brief Returns if a Survivor can ledge hang + * + * @param client Client ID of the player to check + * + * @return Returns true if can hang, false otherwise + */ +stock bool L4D_CanPlayerLedgeHang(int client) +{ + // Get address + static int addy = -1; + if( addy == -1 ) + { + /* + See the function "CTerrorPlayer::InputDisableLedgeHang" + On Windows: this[16417] = 0; + m_bWasPresentAtSurvivalStart offset == 16388 + 16388 + 29 = 16417 + Offset unlikely to change unless netprops are added/removed/changed - which is very unlikely + */ + addy = FindSendPropInfo("CTerrorPlayer", "m_bWasPresentAtSurvivalStart") + 29; + } + + return GetEntData(client, addy, 1) == 1; +} + +/** + * @brief Allow a Survivor to ledge hang + * + * @param client Client ID of the player to affect + * + * @noreturn + */ +stock void L4D_LedgeHangEnable(int client) +{ + AcceptEntityInput(client, "EnableLedgeHang"); +} + +/** + * @brief Disallow a Survivor to ledge hang + * + * @param client Client ID of the player to affect + * + * @noreturn + */ +stock void L4D_LedgeHangDisable(int client) +{ + AcceptEntityInput(client, "DisableLedgeHang"); +} + +/** + * @brief Checks if a Survivor is currently staggering + * + * @param client Client ID of the player to affect + * + * @return Returns true if player is staggering, false otherwise + */ +stock bool L4D_IsPlayerStaggering(int client) +{ + static int m_iQueuedStaggerType = -1; + if( m_iQueuedStaggerType == -1 ) + m_iQueuedStaggerType = FindSendPropInfo("CTerrorPlayer", "m_staggerDist") + 4; + + if( GetEntData(client, m_iQueuedStaggerType, 4) == -1 ) + { + if( GetGameTime() >= GetEntPropFloat(client, Prop_Send, "m_staggerTimer", 1) ) + { + return false; + } + + static float vStgDist[3], vOrigin[3]; + GetEntPropVector(client, Prop_Send, "m_staggerStart", vStgDist); + GetEntPropVector(client, Prop_Send, "m_vecOrigin", vOrigin); + + static float fStgDist2; + fStgDist2 = GetEntPropFloat(client, Prop_Send, "m_staggerDist"); + + return GetVectorDistance(vStgDist, vOrigin) <= fStgDist2; + } + + return true; +} + + + +// ================================================== +// INCAP and REVIVE STOCKS +// ================================================== +/** + * @brief Set a Survivors incapacitated netprop + * @remarks When setting to false can make a Survivor have 300 health (the incapped health value) + * + * @param client Client ID of the player to affect + * @param incap True to incap, false to remove incap (not the proper way of reviving from incap, probably bypasses revive event) + * + * @noreturn + */ +stock void L4D_SetPlayerIncapped(int client, bool incap) +{ + SetEntProp(client, Prop_Send, "m_isIncapacitated", incap ? 1 : 0); +} + +/** + * @brief Incap a Survivor by giving them 100.0 damage + * + * @param client Client ID of the player to affect + * @param attacker Optionally set the attacker to credit them for the incap + * + * @noreturn + */ +stock void L4D_SetPlayerIncappedDamage(int client, int attacker = 0) +{ + SDKHooks_TakeDamage(client, attacker, attacker, 100.0); +} + +/** + * @brief Returns a Survivors revive target + * + * @param client Client ID of the player to check + * + * @return Target client index, or 0 if none + */ +stock int L4D_GetPlayerReviveTarget(int client) +{ + int target = GetEntPropEnt(client, Prop_Send, "m_reviveTarget"); + if( target > 0 ) + return target; + + return 0; +} + +/** + * @brief Returns an incapacitated Survivor's reviver + * + * @param client Client ID of the player to check + * + * @return Reviver client index, or 0 if none + */ +stock int L4D_GetPlayerReviveOwner(int client) +{ + int target = GetEntPropEnt(client, Prop_Send, "m_reviveOwner"); + if( target > 0 ) + return target; + + return 0; +} + +/** + * @brief Stops a Survivor reviving someone + * @remarks Prevents accidental freezing of player who tried to revive you + * @remarks Thanks to "Dragokas" for the stock + * + * @param client Client ID of the player to affect + * + * @noreturn + */ +stock void L4D_StopReviveAction(int client) +{ + int owner_save = -1; + int target_save = -1; + int owner = GetEntPropEnt(client, Prop_Send, "m_reviveOwner"); // when you reviving somebody, this is -1. When somebody revive you, this is somebody's id + int target = GetEntPropEnt(client, Prop_Send, "m_reviveTarget"); // when you reviving somebody, this is somebody's id. When somebody revive you, this is -1 + + SetEntPropEnt(client, Prop_Send, "m_reviveOwner", -1); + SetEntPropEnt(client, Prop_Send, "m_reviveTarget", -1); + + if( owner != -1 ) // we must reset flag for both - for you, and who you revive + { + SetEntPropEnt(owner, Prop_Send, "m_reviveOwner", -1); + SetEntPropEnt(owner, Prop_Send, "m_reviveTarget", -1); + owner_save = owner; + } + + if( target != -1 ) + { + SetEntPropEnt(target, Prop_Send, "m_reviveOwner", -1); + SetEntPropEnt(target, Prop_Send, "m_reviveTarget", -1); + target_save = target; + } + + if( L4D_IsEngineLeft4Dead2() ) + { + owner = GetEntPropEnt(client, Prop_Send, "m_useActionOwner"); // used when healing e.t.c. + target = GetEntPropEnt(client, Prop_Send, "m_useActionTarget"); + SetEntPropEnt(client, Prop_Send, "m_useActionOwner", -1); + SetEntPropEnt(client, Prop_Send, "m_useActionTarget", -1); + + if( owner != -1 ) + { + SetEntPropEnt(owner, Prop_Send, "m_useActionOwner", -1); + SetEntPropEnt(owner, Prop_Send, "m_useActionTarget", -1); + owner_save = owner; + } + + if( target > 0 && target <= MaxClients ) + { + SetEntPropEnt(target, Prop_Send, "m_useActionOwner", -1); + SetEntPropEnt(target, Prop_Send, "m_useActionTarget", -1); + target_save = target; + } + + SetEntProp(client, Prop_Send, "m_iCurrentUseAction", 0); + SetEntPropFloat(client, Prop_Send, "m_flProgressBarDuration", 0.0); + + if( owner_save != -1 ) + { + SetEntProp(owner_save, Prop_Send, "m_iCurrentUseAction", 0); + SetEntPropFloat(owner_save, Prop_Send, "m_flProgressBarDuration", 0.0); + } + + if( target_save != -1 ) + { + SetEntProp(target_save, Prop_Send, "m_iCurrentUseAction", 0); + SetEntPropFloat(target_save, Prop_Send, "m_flProgressBarDuration", 0.0); + } + } + else + { + owner = GetEntPropEnt(client, Prop_Send, "m_healOwner"); // used when healing + target = GetEntPropEnt(client, Prop_Send, "m_healTarget"); + SetEntPropEnt(client, Prop_Send, "m_healOwner", -1); + SetEntPropEnt(client, Prop_Send, "m_healTarget", -1); + + if( owner != -1 ) + { + SetEntPropEnt(owner, Prop_Send, "m_healOwner", -1); + SetEntPropEnt(owner, Prop_Send, "m_healTarget", -1); + owner_save = owner; + } + + if( target != -1 ) + { + SetEntPropEnt(target, Prop_Send, "m_healOwner", -1); + SetEntPropEnt(target, Prop_Send, "m_healTarget", -1); + target_save = target; + } + + SetEntProp(client, Prop_Send, "m_iProgressBarDuration", 0); + + if( owner_save != -1 ) + { + SetEntProp(owner_save, Prop_Send, "m_iProgressBarDuration", 0); + } + + if( target_save != -1 ) + { + SetEntProp(target_save, Prop_Send, "m_iProgressBarDuration", 0); + } + } +} + +/** + * @brief Returns if a Survivor is incapacitated + * + * @param client Client ID of the player to check + * + * @return Returns true if incapacitated, false otherwise + */ +#pragma deprecated Use L4D_IsPlayerIncapacitated instead +stock bool L4D_IsPlayerIncapped(int client) +{ + return GetEntProp(client, Prop_Send, "m_isIncapacitated", 1) != 0; +} + + + + + +// ================================================== +// GET CLIENT STOCKS +// ================================================== + +/** + * @brief Returns a random client in-game + * + * @return Client index or 0 if none + */ +stock int GetAnyRandomClient() +{ + int client; + ArrayList aClients = new ArrayList(); + + for( int i = 1; i <= MaxClients; i++ ) + { + if( IsClientInGame(i) ) + { + aClients.Push(i); + } + } + + if( aClients.Length > 0 ) + { + SetRandomSeed(GetGameTickCount()); + client = aClients.Get(GetRandomInt(0, aClients.Length - 1)); + } + + delete aClients; + + return client; +} + +/** + * @brief Returns a random Survivor + * + * @param alive -1 = Any. 0 = Only dead players. 1 = Only alive players + * @param bots -1 = Any. 0 - Only real players. 1 = Only fake players + * + * @return Client index or 0 if none + */ +stock int GetRandomSurvivor(int alive = -1, int bots = -1) +{ + return GetRandomClient(2, alive, bots); +} + +/** + * @brief Returns a random Special Infected + * + * @param alive -1 = Any. 0 = Only dead players. 1 = Only alive players + * @param bots -1 = Any. 0 - Only real players. 1 = Only fake players + * + * @return Client index or 0 if none + */ +stock int GetRandomInfected(int alive = -1, int bots = -1) +{ + return GetRandomClient(3, alive, bots); +} + +/** + * @brief Returns a random client in game + * + * @param team -1 = Any. 1=Spectators, 2=Survivors, 3=Special Infected, 5=Survivors and Special Infected (team > 1) + * @param alive -1 = Any. 0 = Only dead players. 1 = Only alive players + * @param bots -1 = Any. 0 - Only real players. 1 = Only fake players + * + * @return Client index or 0 if none + */ +stock int GetRandomClient(int team = -1, int alive = -1, int bots = -1) +{ + ArrayList aClients = new ArrayList(); + + for( int i = 1; i <= MaxClients; i++ ) + { + if( IsClientInGame(i) && (team == -1 || (team == 5 && GetClientTeam(i) > 1) || GetClientTeam(i) == team) && (alive == -1 || IsPlayerAlive(i) == view_as(alive)) && (bots == -1 || IsFakeClient(i) == view_as(bots)) ) + { + aClients.Push(i); + } + } + + int client; + + if( aClients.Length > 0 ) + { + SetRandomSeed(GetGameTickCount()); + client = aClients.Get(GetRandomInt(0, aClients.Length - 1)); + } + + delete aClients; + + return client; +} \ No newline at end of file diff --git a/scripting/include/left4dhooks_stocks.inc b/scripting/include/left4dhooks_stocks.inc new file mode 100644 index 0000000..374c4f7 --- /dev/null +++ b/scripting/include/left4dhooks_stocks.inc @@ -0,0 +1,1880 @@ +/** + * ============================================================================= + * Left 4 Dead Stocks Library (C)2011-2012 Buster "Mr. Zero" Nielsen + * Syntax Update and merge into "Left 4 DHooks Direct" (C) 2023 "SilverShot" + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License, version 3.0, as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," + * the "Source Engine," the "SourcePawn JIT," and any Game MODs that run on + * software by the Valve Corporation. You must obey the GNU General Public + * License in all respects for all other code used. Additionally, + * AlliedModders LLC grants this exception to all derivative works. + * AlliedModders LLC defines further exceptions, found in LICENSE.txt + * (as of this writing, version JULY-31-2007), or + * . + */ + +#if defined _l4d_stocks_included + #endinput +#endif +#define _l4d_stocks_included + +#tryinclude +#tryinclude +#tryinclude + + + + + +// ==================================================================================================== +// VARIOUS STOCKS: "l4d_stocks.inc" by "Mr. Zero" +// ==================================================================================================== + +#include + +/* Spawn state bit flags */ +#define L4D_SPAWNFLAG_CANSPAWN (0 << 0) +#define L4D_SPAWNFLAG_DISABLED (1 << 0) +#define L4D_SPAWNFLAG_WAITFORSURVIVORS (1 << 1) +#define L4D_SPAWNFLAG_WAITFORFINALE (1 << 2) +#define L4D_SPAWNFLAG_WAITFORTANKTODIE (1 << 3) +#define L4D_SPAWNFLAG_SURVIVORESCAPED (1 << 4) +#define L4D_SPAWNFLAG_DIRECTORTIMEOUT (1 << 5) +#define L4D_SPAWNFLAG_WAITFORNEXTWAVE (1 << 6) +#define L4D_SPAWNFLAG_CANBESEEN (1 << 7) +#define L4D_SPAWNFLAG_TOOCLOSE (1 << 8) +#define L4D_SPAWNFLAG_RESTRICTEDAREA (1 << 9) +#define L4D_SPAWNFLAG_BLOCKED (1 << 10) + +/* Weapon upgrade bit flags */ +#define L4D2_WEPUPGFLAG_NONE (0 << 0) +#define L4D2_WEPUPGFLAG_INCENDIARY (1 << 0) +#define L4D2_WEPUPGFLAG_EXPLOSIVE (1 << 1) +#define L4D2_WEPUPGFLAG_LASER (1 << 2) + +/* Instructor Hint bit flags */ +#define L4D2_IHFLAG_NONE (0 << 0) +#define L4D2_IHFLAG_PULSE_SLOW (1 << 0) +#define L4D2_IHFLAG_PULSE_FAST (1 << 1) +#define L4D2_IHFLAG_PULSE_URGENT (1 << 2) +#define L4D2_IHFLAG_ALPHA_SLOW (1 << 3) +#define L4D2_IHFLAG_ALPHA_FAST (1 << 4) +#define L4D2_IHFLAG_ALPHA_URGENT (1 << 5) +#define L4D2_IHFLAG_SHAKE_NARROW (1 << 6) +#define L4D2_IHFLAG_SHAKE_WIDE (1 << 7) +#define L4D2_IHFLAG_STATIC (1 << 8) + +/* Survivor intensity -- Equal or less */ +#define L4D_SURVIVORINTENSITY_MILD 0.25 +#define L4D_SURVIVORINTENSITY_MODERATE 0.50 +#define L4D_SURVIVORINTENSITY_HIGH 0.75 +#define L4D_SURVIVORINTENSITY_EXTREME 1.00 + +enum L4DTeam +{ + L4DTeam_Unassigned = 0, + L4DTeam_Spectator = 1, + L4DTeam_Survivor = 2, + L4DTeam_Infected = 3 +} + +enum L4DWeaponSlot +{ + L4DWeaponSlot_Primary = 0, + L4DWeaponSlot_Secondary = 1, + L4DWeaponSlot_Grenade = 2, + L4DWeaponSlot_FirstAid = 3, + L4DWeaponSlot_Pills = 4 +} + +enum L4D2GlowType +{ + L4D2Glow_None = 0, + L4D2Glow_OnUse = 1, + L4D2Glow_OnLookAt = 2, + L4D2Glow_Constant = 3 +} + +enum L4D1ZombieClassType +{ + L4D1ZombieClass_Smoker = 1, + L4D1ZombieClass_Boomer = 2, + L4D1ZombieClass_Hunter = 3, + L4D1ZombieClass_Witch = 4, + L4D1ZombieClass_Tank = 5, + L4D1ZombieClass_NotInfected = 6 +} + +enum L4D2ZombieClassType +{ + L4D2ZombieClass_Smoker = 1, + L4D2ZombieClass_Boomer = 2, + L4D2ZombieClass_Hunter = 3, + L4D2ZombieClass_Spitter = 4, + L4D2ZombieClass_Jockey = 5, + L4D2ZombieClass_Charger = 6, + L4D2ZombieClass_Witch = 7, + L4D2ZombieClass_Tank = 8, + L4D2ZombieClass_NotInfected = 9 +} + +enum L4D2UseAction +{ + L4D2UseAction_None = 0, // No use action active + L4D2UseAction_Healing = 1, // Includes healing yourself or a teammate. + L4D2UseAction_AmmoPack = 2, // When deploying the ammo pack that was never added into the game + L4D2UseAction_Defibing = 4, // When defib'ing a dead body. + L4D2UseAction_GettingDefibed = 5, // When comming back to life from a dead body. + L4D2UseAction_DeployIncendiary = 6, // When deploying Incendiary ammo + L4D2UseAction_DeployExplosive = 7, // When deploying Explosive ammo + L4D2UseAction_PouringGas = 8, // Pouring gas into a generator + L4D2UseAction_Cola = 9, // For Dead Center map 2 cola event, when handing over the cola to whitalker. + L4D2UseAction_Button = 10, // Such as buttons, timed buttons, generators, etc. + L4D2UseAction_UsePointScript = 11 // When using a "point_script_use_target" entity + /* List is not fully done, these are just the ones I have found so far */ +} + +enum L4DResourceType +{ + L4DResource_Ping, + L4DResource_Score, + L4DResource_TankTickets, + L4DResource_Deaths, + L4DResource_MaxHealth, + L4DResource_WantsToPlay, + L4DResource_TankTickets2 +} + +stock const char L4D1ZombieClassname[6][] = +{ + "smoker", + "boomer", + "hunter", + "witch", + "tank", + "error_bad_L4D1ZombieClassType" +}; + +stock const char L4D2ZombieClassname[9][] = +{ + "smoker", + "boomer", + "hunter", + "spitter", + "jockey", + "charger", + "witch", + "tank", + "error_bad_L4D2ZombieClassType" +}; + +static const char L4DResourceName[L4DResourceType][] = +{ + "m_iPing", + "m_iScore", + "m_iTankTickets", + "m_iDeaths", + "m_maxHealth", + "m_wantsToPlay", + "m_tankTickets" +}; + +/** + * Returns the clients team using L4DTeam. + * + * @param client Player's index. + * @return Current L4DTeam of player. + * @error Invalid client index. + */ +stock L4DTeam L4D_GetClientTeam(int client) +{ + int team = GetClientTeam(client); + return view_as(team); +} + +/** + * Returns zombie player L4D1 zombie class. + * + * @param client Player's index. + * @return Current L4D1ZombieClassType of player. + * @error Invalid client index. + */ +// L4D1 only. +stock L4D1ZombieClassType L4D1_GetPlayerZombieClass(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_zombieClass")); +} + +/** + * Set zombie player L4D1 zombie class. + * + * @param client Player's index. + * @param class L4D1ZombieClassType class symbol. + * @noreturn + * @error Invalid client index. + */ +// L4D1 only. +stock void L4D1_SetPlayerZombieClass(int client, L4D1ZombieClassType class) +{ + SetEntProp(client, Prop_Send, "m_zombieClass", class); +} + +/** + * Returns zombie player L4D2 zombie class. + * + * @param client Player's index. + * @return Current L4D2ZombieClassType of player. + * @error Invalid client index. + */ +// L4D2 only. +stock any L4D2_GetPlayerZombieClass(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_zombieClass")); +} + +/** + * Set zombie player L4D2 zombie class. + * + * @param client Player's index. + * @param class L4D2ZombieClassType class symbol. + * @noreturn + * @error Invalid client index. + */ +// L4D2 only. +stock void L4D2_SetPlayerZombieClass(int client, L4D2ZombieClassType class) +{ + SetEntProp(client, Prop_Send, "m_zombieClass", class); +} + +/** + * Returns ghost state of zombie player. + * + * @param client Player index. + * @return True if player is ghost, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerGhost(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isGhost", 1)); +} + +/** + * Sets ghost state of zombie player. + * + * @param client Player index. + * @param isGhost Sets ghost status. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerGhostState(int client, bool isGhost) +{ + SetEntProp(client, Prop_Send, "m_isGhost", isGhost, 1); +} + +/** + * Returns ghost spawn state of zombie player. + * + * @param client Player index. + * @return Player's spawn state bits. + * @error Invalid client index. + */ +stock int L4D_GetPlayerGhostSpawnState(int client) +{ + return GetEntProp(client, Prop_Send, "m_ghostSpawnState"); +} + +/** + * Set zombie player's ghost spawn state bits. + * + * Note: The game updates spawn state bits every frame. + * + * @param client Player index. + * @param bits Ghost spawn state bits. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerGhostSpawnState(int client, int bits) +{ + SetEntProp(client, Prop_Send, "m_ghostSpawnState", bits); +} + +/** + * Returns whether zombie player is culling. + * + * @param client Player index. + * @return True if player is culling, false otherwise. + */ +stock bool L4D_IsPlayerCulling(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isCulling", 1)); +} + +/** + * Set culling state of zombie player. + * + * @param client Player index. + * @param isCulling Whether player is culling. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerCullingState(int client, bool isCulling) +{ + SetEntProp(client, Prop_Send, "m_isCulling", isCulling, 1); +} + +/** + * Returns whether player is incapacitated. + * + * Note: A tank player will return true when in dying animation. + * + * @param client Player index. + * @return True if incapacitated, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerIncapacitated(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isIncapacitated", 1)); +} + +/** + * Set player's incapacitated state. + * + * @param client Player index. + * @param isIncapacitated Whether the player is incapacitated. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerIncapacitatedState(int client, bool isIncapacitated) +{ + SetEntProp(client, Prop_Send, "m_isIncapacitated", isIncapacitated, 1); +} + +/** + * Returns survivor player shove penalty. + * + * @param client Player index. + * @return Current shove penalty of player. + */ +stock int L4D_GetPlayerShovePenalty(int client) +{ + return GetEntProp(client, Prop_Send, "m_iShovePenalty"); +} + +/** + * Set survivor player shove penalty. + * + * @param client Player index. + * @param shovePenalty Shove penalty. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerShovePenalty(int client, int shovePenalty) +{ + SetEntProp(client, Prop_Send, "m_iShovePenalty", shovePenalty); +} + +/** + * Returns tank player's frustration. + * + * @param client Player index. + * @return How frustrated tank player is. + * @error Invalid client index. + */ +stock int L4D_GetTankFrustration(int client) +{ + return GetEntProp(client, Prop_Send, "m_frustration"); +} + +/** + * Set tank player's frustration. + * + * @param client Player index. + * @param frustration How frustrated tank player is. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetTankFrustration(int client, int frustration) +{ + SetEntProp(client, Prop_Send, "m_frustration", frustration); +} + +/** + * Returns whether survivor player is idle. + * + * @param Player index. + * @return True if idle, false otherwise. + */ +stock bool L4D_IsPlayerIdle(int client) +{ + return L4D_GetBotOfIdlePlayer(client) > -1; +} + +/** + * Returns survivor bot of idle survivor player. + * + * @param client Player index. + * @return Player index of the bot, -1 if not found. + */ +stock int L4D_GetBotOfIdlePlayer(int client) +{ + int idleClient; + int offset; + char netclass[64]; + + for (int bot = 1; bot <= MaxClients; bot++) + { + if (!IsClientInGame(bot) || + !IsFakeClient(bot) || + view_as(GetClientTeam(bot)) != L4DTeam_Survivor || + !IsPlayerAlive(bot) || + GetClientHealth(bot) < 1) + { + continue; + } + + GetEntityNetClass(bot, netclass, sizeof(netclass)); + offset = FindSendPropInfo(netclass, "m_humanSpectatorUserID"); + + if (offset < 1) + { + continue; + } + + idleClient = GetClientOfUserId(GetEntProp(bot, Prop_Send, "m_humanSpectatorUserID")); + + if (idleClient == client) + { + return bot; + } + } + + return -1; +} + +/** + * Returns idle survivor player of survivor bot. + * + * @param bot Player index of bot. + * @return Player index of idle client, -1 if not found. + * @error Invalid client index. + */ +stock int L4D_GetIdlePlayerOfBot(int bot) +{ + char netclass[64]; + GetEntityNetClass(bot, netclass, sizeof(netclass)); + int offset = FindSendPropInfo(netclass, "m_humanSpectatorUserID"); + + if (offset < 1) + { + return -1; + } + + return GetClientOfUserId(GetEntProp(bot, Prop_Send, "m_humanSpectatorUserID")); +} + +/** + * Returns resource entity. + * + * @return Entity index of resource entity, -1 if not found. + */ +stock int L4D_GetResourceEntity() +{ + return FindEntityByClassname(-1, "terror_player_manager"); +} + +/** + * Retrieves client data from the resource entity. + * + * @param client Player's index. + * @param type ResourceType constant + * @return Value or -1 on failure. + * @error Invalid client index, client not in game or failed to find resource entity. + */ +stock int L4D_GetPlayerResourceData(int client, L4DResourceType type) +{ + if (!IsClientConnected(client)) + { + return -1; + } + + int offset = FindSendPropInfo("CTerrorPlayerResource", L4DResourceName[type]); + + if (offset < 1) + { + return -1; + } + + int entity = L4D_GetResourceEntity(); + + if (entity == -1) + { + return -1; + } + + return GetEntData(entity, offset + (client * 4)); +} + +/** + * Sets client data in the resource entity. + * + * Note: The game overwrites these values every frame, so changing them will have very little effect. + * + * @param client Player's index. + * @param type ResourceType constant + * @param value Value to set. + * @return Value or -1 on failure. + * @error Invalid client index, client not in game or failed to find resource entity. + */ +stock bool L4D_SetPlayerResourceData(int client, L4DResourceType type, any value) +{ + if (!IsClientConnected(client)) + { + return false; + } + + int offset = FindSendPropInfo("CTerrorPlayerResource", L4DResourceName[type]); + + if (offset < 1) + { + return false; + } + + int entity = L4D_GetResourceEntity(); + + if (entity == -1) + { + return false; + } + + SetEntData(entity, offset + (client * 4), value); + + return true; +} + +/** + * Removes the weapon from a client's weapon slot + * + * @param client Player's index. + * @param slot Slot index. + * @noreturn + * @error Invalid client or lack of mod support. + */ +stock void L4D_RemoveWeaponSlot(int client, L4DWeaponSlot slot) +{ + int weaponIndex; + while ((weaponIndex = GetPlayerWeaponSlot(client, view_as(slot))) != -1) + { + RemovePlayerItem(client, weaponIndex); + RemoveEdict(weaponIndex); + } +} + +/** + * Removes all weapons from a client + * + * @param client Player's index. + * @noreturn + * @error Invalid client or lack of mod support. + */ +stock void L4D_RemoveAllWeapons(int client) +{ + for (int i = 0; i <= 4; i++) + { + L4D_RemoveWeaponSlot(client, view_as(i)); + } +} + +/** + * Returns whether the finale is active. + * + * Note: Finales can also be on other maps than just the finale map. A perfect + * example of this is the Swamp Fever map 1 crescendo event. This event is + * defined as a finale by Valve for some reason. + * + * @return True if finale is active, false otherwise. + */ +stock bool L4D_IsFinaleActive() +{ + int entity = L4D_GetResourceEntity(); + + if (entity == -1) + { + return false; + } + + return view_as(GetEntProp(entity, Prop_Send, "m_isFinale", 1)); +} + +/** + * Returns whether any survivor have left the safe area. + * + * @return True if any survivor have left safe area, false otherwise. + */ +stock bool L4D_HasAnySurvivorLeftSafeAreaStock() +{ + int entity = L4D_GetResourceEntity(); + + if (entity == -1) + { + return false; + } + + return view_as(GetEntProp(entity, Prop_Send, "m_hasAnySurvivorLeftSafeArea", 1)); +} + +/** + * Returns pending tank player. + * + * @return Player index of pending tank player, -1 if not found. + */ +stock int L4D_GetPendingTankPlayer() +{ + int entity = L4D_GetResourceEntity(); + + if (entity == -1) + { + return -1; + } + + return GetEntProp(entity, Prop_Send, "m_pendingTankPlayerIndex"); +} + +/** + * Set entity glow. This is consider safer and more robust over setting each glow property on their own because glow offset will be check first. + * + * @param entity Entity index. + * @parma type Glow type. + * @param range Glow max range, 0 for unlimited. + * @param minRange Glow min range. + * @param colorOverride Glow color, RGB. + * @param flashing Whether the glow will be flashing. + * @return True if glow was set, false if entity does not support glow. + */ +// L4D2 only. +stock bool L4D2_SetEntityGlow(int entity, L4D2GlowType type, int range, int minRange, colorOverride[3], bool flashing) +{ + if (!IsValidEntity(entity)) + { + return false; + } + + char netclass[64]; + GetEntityNetClass(entity, netclass, sizeof(netclass)); + + int offset = FindSendPropInfo(netclass, "m_iGlowType"); + + if (offset < 1) + { + return false; + } + + L4D2_SetEntityGlow_Type(entity, type); + L4D2_SetEntityGlow_Range(entity, range); + L4D2_SetEntityGlow_MinRange(entity, minRange); + L4D2_SetEntityGlow_Color(entity, colorOverride); + L4D2_SetEntityGlow_Flashing(entity, flashing); + return true; +} + +/** + * Set entity glow type. + * + * @param entity Entity index. + * @parma type Glow type. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_SetEntityGlow_Type(int entity, L4D2GlowType type) +{ + SetEntProp(entity, Prop_Send, "m_iGlowType", type); +} + +/** + * Set entity glow range. + * + * @param entity Entity index. + * @parma range Glow range. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_SetEntityGlow_Range(int entity, int range) +{ + SetEntProp(entity, Prop_Send, "m_nGlowRange", range); +} + +/** + * Set entity glow min range. + * + * @param entity Entity index. + * @parma minRange Glow min range. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_SetEntityGlow_MinRange(int entity, int minRange) +{ + SetEntProp(entity, Prop_Send, "m_nGlowRangeMin", minRange); +} + +/** + * Set entity glow color. + * + * @param entity Entity index. + * @parma colorOverride Glow color, RGB. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_SetEntityGlow_Color(int entity, int colorOverride[3]) +{ + SetEntProp(entity, Prop_Send, "m_glowColorOverride", colorOverride[0] + (colorOverride[1] * 256) + (colorOverride[2] * 65536)); +} + +/** + * Set entity glow flashing state. + * + * @param entity Entity index. + * @parma flashing Whether glow will be flashing. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_SetEntityGlow_Flashing(int entity, bool flashing) +{ + SetEntProp(entity, Prop_Send, "m_bFlashing", flashing); +} + +/** + * Returns entity glow type. + * + * @param entity Entity index. + * @return L4D2 glow type. + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock L4D2GlowType L4D2_GetEntityGlow_Type(int entity) +{ + return view_as(GetEntProp(entity, Prop_Send, "m_iGlowType")); +} + +/** + * Returns entity glow range. + * + * @param entity Entity index. + * @return Glow range. + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock int L4D2_GetEntityGlow_Range(int entity) +{ + return GetEntProp(entity, Prop_Send, "m_nGlowRange"); +} + +/** + * Returns entity glow min range. + * + * @param entity Entity index. + * @return Glow min range. + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock int L4D2_GetEntityGlow_MinRange(int entity) +{ + return GetEntProp(entity, Prop_Send, "m_nGlowRangeMin"); +} + +/** + * Returns entity glow flashing state. + * + * @param entity Entity index. + * @return Glow flashing state. + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock bool L4D2_GetEntityGlow_Flashing(int entity) +{ + return view_as(GetEntProp(entity, Prop_Send, "m_bFlashing")); +} + +/** + * Removes entity glow. + * + * @param entity Entity index. + * @return True if glow was removed, false if entity does not + * support glow. + */ +// L4D2 only. +stock bool L4D2_RemoveEntityGlow(int entity) +{ + return view_as(L4D2_SetEntityGlow(entity, L4D2Glow_None, 0, 0, { 0, 0, 0 }, false)); +} + +/** + * Removes entity glow override color. + * + * Note: This only removes the override color and reset it to the default glow + * color. + * + * @param entity Entity index. + * @noreturn + * @error Invalid entity index or entity does not support glow. + */ +// L4D2 only. +stock void L4D2_RemoveEntityGlow_Color(int entity) +{ + L4D2_SetEntityGlow_Color(entity, { 0, 0, 0 }); +} + +/** + * Whether survivor glow for player is enabled. + * + * @param client Client index. + * @return True if survivor glow is enabled, false otherwise. + * @error Invalid client index. + */ +// L4D2 only. +stock bool L4D2_IsPlayerSurvivorGlowEnable(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_bSurvivorGlowEnabled")); +} + +/** + * Set survivor glow state for player. + * + * @param client Client index. + * @param enabled Whether survivor glow is enabled. + * @noreturn + * @error Invalid client index. + */ +// L4D2 only. +stock void L4D2_SetPlayerSurvivorGlowState(int client, bool enabled) +{ + SetEntProp(client, Prop_Send, "m_bSurvivorGlowEnabled", enabled); +} + +/** + * Return player current revive count. + * + * @param client Client index. + * @return Survivor's current revive count. + * @error Invalid client index. + */ +stock int L4D_GetPlayerReviveCount(int client) +{ + return GetEntProp(client, Prop_Send, "m_currentReviveCount"); +} + +/** + * Set player revive count. + * + * @param client Client index. + * @param count Revive count. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerReviveCount(int client, int count) +{ + SetEntProp(client, Prop_Send, "m_currentReviveCount", count); +} + +/** + * Return player intensity. + * + * Note: Its percentage. 0.0 - Player is calm, 1.0 - Player is stressed. + * + * @param client Client index. + * @return Intensity. + * @error Invalid client index. + */ +stock float L4D_GetPlayerIntensity(int client) +{ + /* This format is used to keep consistency with the Director which also + * uses 0.0 for calm and 1.0 for stressed */ + return float(GetEntProp(client, Prop_Send, "m_clientIntensity")) / 100.0; +} + +/** + * Returns average survivor intensity. + * + * Note: Its percentage. 0.0 - All survivors is calm, 1.0 - All survivors is stressed. + * + * @return Average intensity level for survivors. + */ +stock float L4D_GetAvgSurvivorIntensity() +{ + int intensityTotal = 0; + int intensityMaxTotal = 0; + + for (int client = 1; client <= MaxClients; client++) + { + if (!IsClientInGame(client) || + view_as(GetClientTeam(client)) != L4DTeam_Survivor || + !IsPlayerAlive(client) || + GetClientHealth(client) < 1) + { + continue; + } + + intensityMaxTotal += 100; + intensityTotal += GetEntProp(client, Prop_Send, "m_clientIntensity"); + } + + /* This format is used to keep consistency with the Director which also uses 0.0 for calm and 1.0 for stressed */ + return float(intensityTotal) / float(intensityMaxTotal); +} + +/** + * Set player intensity. + * + * Note: Its percentage. 0.0 - Player is calm, 1.0 - Player is stressed. + * + * @param client Client index. + * @param intensity Intensity. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerIntensity(int client, float intensity) +{ + SetEntProp(client, Prop_Send, "m_clientIntensity", RoundToNearest(intensity * 100.0)); +} + +/** + * Returns whether player is calm. + * + * Note: Player is calm means that the player have not taken damage or + * fired their weapon for a while. Survivor bots always return false. + * + * @param client Client index. + * @return True if player is calm, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerCalm(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isCalm")); +} + +/** + * Set player is calm state. + * + * Note: Player is calm means that the player have not taken damage or fired their weapon for a while. + * + * @param client Client index. + * @param isCalm Whether player is calm. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerCalmState(int client, bool isCalm) +{ + SetEntProp(client, Prop_Send, "m_isCalm", isCalm); +} + +/** + * Returns whether player has visible threats. + * + * Note: This function should work for all players. Survivors looking upon + * specials, witch or tank will be marked as has visible threats. However + * looking at commons will not be seen as has visible threats. The common has + * to be awaken from its slumber before beings seen as a threat. + * + * @parma client Client index. + * @return True if player has visible threats, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_HasVisibleThreats(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_hasVisibleThreats")); +} + +/** + * Returns whether player is on third strike. + * + * @param client Client index. + * @return True if on third strike, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerOnThirdStrike(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_bIsOnThirdStrike")); +} + +/** + * Set player third strike state. + * + * @param client Client index. + * @param onThirdStrike Whether survivor is on third strike. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerThirdStrikeState(int client, bool onThirdStrike) +{ + SetEntProp(client, Prop_Send, "m_bIsOnThirdStrike", onThirdStrike); +} + +/** + * Returns whether player is going to die. + * + * Note: This is not the same as is player on third strike. While on third + * strike defines whether player should die next time they get incapacitated, + * this defines whether the survivor should limp when they hit 1hp and make + * the character vocalize their "I dont think I'm gonna make it" lines. + * + * @param client Client index. + * @return True if player is going to die, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerGoingToDie(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_isGoingToDie")); +} + +/** + * Set player is going to die state. + * + * @param client Client index. + * @param isGoingToDie Whether player is going to die. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerIsGoingToDie(int client, bool isGoingToDie) +{ + SetEntProp(client, Prop_Send, "m_isGoingToDie", isGoingToDie); +} + +/** + * Returns whether weapon is upgrade compatible. + * + * @param weapon Weapon entity index. + * @return True if compatible with upgrades, false otherwise. + * @error Invalid entity index. + */ +stock bool L4D2_IsWeaponUpgradeCompatible(int weapon) +{ + if( HasEntProp(weapon, Prop_Send, "m_upgradeBitVec") ) + return true; + + return false; +} + +/** + * Returns upgraded ammo count for weapon. + * + * @param weapon Weapon entity index. + * @return Upgraded ammo count. + * @error Invalid entity index. + */ +// L4D2 only. +stock int L4D2_GetWeaponUpgradeAmmoCount(int weapon) +{ + if( HasEntProp(weapon, Prop_Send, "m_nUpgradedPrimaryAmmoLoaded") ) + return GetEntProp(weapon, Prop_Send, "m_nUpgradedPrimaryAmmoLoaded"); + + return 0; +} + +/** + * Set upgraded ammo count in weapon. + * + * @param weapon Weapon entity index. + * @param count Upgraded ammo count. + * @noreturn + * @error Invalid entity index. + */ +// L4D2 only. +stock void L4D2_SetWeaponUpgradeAmmoCount(int weapon, int count) +{ + if( HasEntProp(weapon, Prop_Send, "m_nUpgradedPrimaryAmmoLoaded") ) + SetEntProp(weapon, Prop_Send, "m_nUpgradedPrimaryAmmoLoaded", count); +} + +/** + * Returns weapon upgrades of weapon. + * + * @param weapon Weapon entity index. + * @return Weapon upgrade bits. + * @error Invalid entity index. + */ +// L4D2 only. +stock int L4D2_GetWeaponUpgrades(int weapon) +{ + if( HasEntProp(weapon, Prop_Send, "m_upgradeBitVec") ) + return GetEntProp(weapon, Prop_Send, "m_upgradeBitVec"); + + return 0; +} + +/** + * Set weapon upgrades for weapon. + * + * @param weapon Weapon entity index. + * @param upgrades Weapon upgrade bits. + * @noreturn + * @error Invalid entity index. + */ +// L4D2 only. +stock void L4D2_SetWeaponUpgrades(int weapon, int upgrades) +{ + if( HasEntProp(weapon, Prop_Send, "m_upgradeBitVec") ) + { + SetEntProp(weapon, Prop_Send, "m_upgradeBitVec", upgrades); + } +} + +/** + * Returns infected attacker of survivor victim. + * + * Note: Infected attacker means the infected player that is currently + * pinning down the survivor. Such as hunter, smoker, charger and jockey. + * + * @param client Survivor client index. + * @return Infected attacker index, -1 if not found. + * @error Invalid client index. + */ +// L4D2 only. +stock int L4D2_GetInfectedAttacker(int client) +{ + int attacker; + + /* Charger */ + attacker = GetEntPropEnt(client, Prop_Send, "m_pummelAttacker"); + if (attacker > 0) + { + return attacker; + } + + attacker = GetEntPropEnt(client, Prop_Send, "m_carryAttacker"); + if (attacker > 0) + { + return attacker; + } + + /* Hunter */ + attacker = GetEntPropEnt(client, Prop_Send, "m_pounceAttacker"); + if (attacker > 0) + { + return attacker; + } + + /* Smoker */ + attacker = GetEntPropEnt(client, Prop_Send, "m_tongueOwner"); + if (attacker > 0) + { + return attacker; + } + + /* Jockey */ + attacker = GetEntPropEnt(client, Prop_Send, "m_jockeyAttacker"); + if (attacker > 0) + { + return attacker; + } + + return -1; +} + +/** + * Returns survivor victim of infected attacker. + * + * Note: Survivor victim means the survivor player that is currently pinned + * down by an attacker. Such as hunter, smoker, charger and jockey. + * + * @param client Infected client index. + * @return Survivor victim index, -1 if not found. + * @error Invalid client index. + */ +// L4D2 only. +stock int L4D2_GetSurvivorVictim(int client) +{ + int victim; + + /* Charger */ + victim = GetEntPropEnt(client, Prop_Send, "m_pummelVictim"); + if (victim > 0) + { + return victim; + } + + victim = GetEntPropEnt(client, Prop_Send, "m_carryVictim"); + if (victim > 0) + { + return victim; + } + + /* Hunter */ + victim = GetEntPropEnt(client, Prop_Send, "m_pounceVictim"); + if (victim > 0) + { + return victim; + } + + /* Smoker */ + victim = GetEntPropEnt(client, Prop_Send, "m_tongueVictim"); + if (victim > 0) + { + return victim; + } + + /* Jockey */ + victim = GetEntPropEnt(client, Prop_Send, "m_jockeyVictim"); + if (victim > 0) + { + return victim; + } + + return -1; +} + +/** + * Returns whether survivor client was present at survival start. + * + * @param client Client index. + * @return True if survivor was present at survival start, false otherwise. + * @error Invalid client index. + */ +// L4D2 only. +stock bool L4D2_WasPresentAtSurvivalStart(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_bWasPresentAtSurvivalStart")); +} + +/** + * Sets whether player was present at survival start. + * + * @param client Client index. + * @param wasPresent Whether survivor was present at survival start. + * @noreturn + * @error Invalid client index. + */ +// L4D2 only. +stock void L4D2_SetPresentAtSurvivalStart(int client, bool wasPresent) +{ + SetEntProp(client, Prop_Send, "m_bWasPresentAtSurvivalStart", wasPresent); +} + +/** + * Returns whether player is using a mounted weapon. + * + * @param client Client index. + * @return True if using a mounted weapon, false otherwise. + * @error Invalid client index. + */ +stock bool L4D_IsPlayerUsingMountedWeapon(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_usingMountedWeapon")); +} + +/** + * Returns player temporarily health. + * + * Note: This will not work with mutations or campaigns that alters the decay + * rate through vscript'ing. If you want to be sure that it works no matter + * the mutation, you will have to detour the OnGetScriptValueFloat function. + * Doing so you are able to capture the altered decay rate and calculate the + * temp health the same way as this function does. + * + * @param client Client index. + * @return Player's temporarily health, -1 if unable to get. + * @error Invalid client index or unable to find pain_pills_decay_rate cvar. + */ +stock int L4D_GetPlayerTempHealth(int client) +{ + static ConVar painPillsDecayCvar; + if (painPillsDecayCvar == null) + { + painPillsDecayCvar = FindConVar("pain_pills_decay_rate"); + if (painPillsDecayCvar == null) + { + return -1; + } + } + + int tempHealth = RoundToCeil(GetEntPropFloat(client, Prop_Send, "m_healthBuffer") - ((GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime")) * painPillsDecayCvar.FloatValue)) - 1; + return tempHealth < 0 ? 0 : tempHealth; +} + +/** + * Set players temporarily health. + * + * @param client Client index. + * @param tempHealth Temporarily health. + * @noreturn + * @error Invalid client index. + */ +stock void L4D_SetPlayerTempHealth(int client, int tempHealth) +{ + SetEntPropFloat(client, Prop_Send, "m_healthBuffer", float(tempHealth)); + SetEntPropFloat(client, Prop_Send, "m_healthBufferTime", GetGameTime()); +} + +/** + * Returns player use action. + * + * @param client Client index. + * @return Use action. + * @error Invalid client index. + */ +// L4D2 only. +stock L4D2UseAction L4D2_GetPlayerUseAction(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_iCurrentUseAction")); +} + +/** + * Returns player use action target. + * + * @param client Client index. + * @return Entity index. + * @error Invalid client index. + */ +// L4D2 only. +stock int L4D2_GetPlayerUseActionTarget(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_useActionTarget"); +} + +/** + * Returns player use action owner. + * + * @param client Client index. + * @return Entity index. + * @error Invalid client index. + */ +// L4D2 only. +stock int L4D2_GetPlayerUseActionOwner(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_useActionOwner"); +} + +/** + * Creates an instructor hint. + * + * Note: Both infected and survivor players will see hint. No more than one at + * a time can be shown. The "newest" hint will override the old no matter the + * timeout and range. This instructor hint will not be shown if the given + * player is dead. + * + * @param name Instructor hint name. + * @param target Entity index of target. + * @param caption Caption of hint. + * @param color Color of the caption. RGB format. + * @param iconOnScreen Icon when hint is on screen. + * @param iconOffScreen Icon when hint is off screen. + * @param binding Key binding to show. + * @param iconOffset Height offset for icon from target entity's origin. + * @param range Display range of hint. 0 for unlimited range. + * @param timeout Timeout out for hint. 0 will persist until stopped with L4D2_EndInstructorHint. + * @param allowNoDrawTarget Whether hint will work with targets that have nodraw set. + * @param noOffScreen Whether when hint is off screen it will show an arrow pointing to target. + * @param forceCaption Whether the hint and icon will show even when occluded a wall. + * @param flags Instructor hint bit flags. See L4D2_IHFLAG_* defines. + * @return True if send, false otherwise. + */ +// L4D2 only. +stock bool L4D2_CreateInstructorHint(const char[] name, + int target = 0, + const char[] caption, + int color[3] = {255, 255, 255}, + const char[] iconOnScreen = "icon_tip", + const char[] iconOffScreen = "icon_tip", + const char[] binding = "", + float iconOffset = 0.0, + float range = 0.0, + int timeout = 0, + bool allowNoDrawTarget = true, + bool noOffScreen = false, + bool forceCaption = false, + int flags = L4D2_IHFLAG_STATIC) +{ + Event event = CreateEvent("instructor_server_hint_create", true); + if (event == null) + { + return false; + } + + char finalizedColor[16]; + Format(finalizedColor, 16, "%d,%d,%d", color[0], color[1], color[2]); + + event.SetString("hint_name", name); + event.SetInt("hint_target", target); + event.SetString("hint_caption", caption); + event.SetString("hint_color", finalizedColor); + event.SetString("hint_icon_onscreen", iconOnScreen); + event.SetString("hint_icon_offscreen", iconOffScreen); + event.SetString("hint_binding", binding); + event.SetFloat("hint_icon_offset", iconOffset); + event.SetFloat("hint_range", range); + event.SetInt("hint_timeout", timeout); + event.SetBool("hint_allow_nodraw_target", allowNoDrawTarget); + event.SetBool("hint_nooffscreen", noOffScreen); + event.SetBool("hint_forcecaption", forceCaption); + event.SetInt("hint_flags", flags); + event.Fire(); + return true; +} + +/** + * Stops all instructor hints with name. + * + * @param name Name of instructor hint to stop. + * @return True if send, false otherwise. + */ +// L4D2 only. +stock bool L4D2_StopInstructorHint(const char[] name) +{ + Event event = CreateEvent("instructor_server_hint_stop", true); + if (event == null) + { + return false; + } + + event.SetString("hint_name", name); + event.Fire(); + return true; +} + +/** + * Returns whether shotgun needs to be pumped. + * + * @parma weapon Weapon entity index. + * @return True if shotgun needs to be pumped, false otherwise. + */ +// L4D1 only. +stock int L4D1_GetShotgunNeedPump(int weapon) +{ + return HasEntProp(weapon, Prop_Send, "m_needPump") && GetEntProp(weapon, Prop_Send, "m_needPump"); +} + +/** + * Sets whether shotgun needs to be pumped. + * + * @parma weapon Weapon entity index. + * @parma needPump Whether shotgun needs to be pumped. + * @noreturn + */ +// L4D1 only. +stock void L4D1_SetShotgunNeedPump(int weapon, bool needPump) +{ + if( HasEntProp(weapon, Prop_Send, "m_needPump") ) + { + SetEntProp(weapon, Prop_Send, "m_needPump", view_as(needPump)); + } +} + +/** + * Sets custom ability cooldown of client. + * + * Note: Used for the Infected class abilities. + * + * @param client Client index. + * @param time How long before client can use their custom ability. + * @return True if set, false if no ability found. + */ +// L4D2 only. +stock bool L4D2_SetCustomAbilityCooldown(int client, float time) +{ + int ability = GetEntPropEnt(client, Prop_Send, "m_customAbility"); + if (ability > 0 && IsValidEdict(ability)) + { + SetEntPropFloat(ability, Prop_Send, "m_duration", time); + SetEntPropFloat(ability, Prop_Send, "m_timestamp", GetGameTime() + time); + return true; + } + return false; +} + + + + + +// ==================================================================================================== +// WEAPON STOCKS: "l4d_weapon_stocks.inc" by "Mr. Zero" +// ==================================================================================================== + +/* Credits to ProdigySim for the weapon details, models and original script */ + +#if defined _l4d_weapon_stocks_included + #endinput +#endif +#define _l4d_weapon_stocks_included + +#include +#include +#include + +enum L4D2WeaponId +{ + L4D2WeaponId_None, // 0 + L4D2WeaponId_Pistol, // 1 + L4D2WeaponId_Smg, // 2 + L4D2WeaponId_Pumpshotgun, // 3 + L4D2WeaponId_Autoshotgun, // 4 + L4D2WeaponId_Rifle, // 5 + L4D2WeaponId_HuntingRifle, // 6 + L4D2WeaponId_SmgSilenced, // 7 + L4D2WeaponId_ShotgunChrome, // 8 + L4D2WeaponId_RifleDesert, // 9 + L4D2WeaponId_SniperMilitary, // 10 + L4D2WeaponId_ShotgunSpas, // 11 + L4D2WeaponId_FirstAidKit, // 12 + L4D2WeaponId_Molotov, // 13 + L4D2WeaponId_PipeBomb, // 14 + L4D2WeaponId_PainPills, // 15 + L4D2WeaponId_Gascan, // 16 + L4D2WeaponId_PropaneTank, // 17 + L4D2WeaponId_OxygenTank, // 18 + L4D2WeaponId_Melee, // 19 + L4D2WeaponId_Chainsaw, // 20 + L4D2WeaponId_GrenadeLauncher, // 21 + L4D2WeaponId_AmmoPack, // 22 + L4D2WeaponId_Adrenaline, // 23 + L4D2WeaponId_Defibrillator, // 24 + L4D2WeaponId_Vomitjar, // 25 + L4D2WeaponId_RifleAK47, // 26 + L4D2WeaponId_GnomeChompski, // 27 + L4D2WeaponId_ColaBottles, // 28 + L4D2WeaponId_FireworksBox, // 29 + L4D2WeaponId_IncendiaryAmmo, // 30 + L4D2WeaponId_FragAmmo, // 31 + L4D2WeaponId_PistolMagnum, // 32 + L4D2WeaponId_SmgMP5, // 33 + L4D2WeaponId_RifleSG552, // 34 + L4D2WeaponId_SniperAWP, // 35 + L4D2WeaponId_SniperScout, // 36 + L4D2WeaponId_RifleM60, // 37 + L4D2WeaponId_TankClaw, // 38 + L4D2WeaponId_HunterClaw, // 39 + L4D2WeaponId_ChargerClaw, // 40 + L4D2WeaponId_BoomerClaw, // 41 + L4D2WeaponId_SmokerClaw, // 42 + L4D2WeaponId_SpitterClaw, // 43 + L4D2WeaponId_JockeyClaw, // 44 + L4D2WeaponId_Machinegun, // 45 + L4D2WeaponId_FatalVomit, // 46 + L4D2WeaponId_ExplodingSplat, // 47 + L4D2WeaponId_LungePounce, // 48 + L4D2WeaponId_Lounge, // 49 + L4D2WeaponId_FullPull, // 50 + L4D2WeaponId_Choke, // 51 + L4D2WeaponId_ThrowingRock, // 52 + L4D2WeaponId_TurboPhysics, // 53 + L4D2WeaponId_Ammo, // 54 + L4D2WeaponId_UpgradeItem, // 55 + L4D2WeaponId_MAX +}; + +static const char L4D2WeaponName[L4D2WeaponId][] = +{ + "weapon_none", // 0 + "weapon_pistol", // 1 + "weapon_smg", // 2 + "weapon_pumpshotgun", // 3 + "weapon_autoshotgun", // 4 + "weapon_rifle", // 5 + "weapon_hunting_rifle", // 6 + "weapon_smg_silenced", // 7 + "weapon_shotgun_chrome", // 8 + "weapon_rifle_desert", // 9 + "weapon_sniper_military", // 10 + "weapon_shotgun_spas", // 11 + "weapon_first_aid_kit", // 12 + "weapon_molotov", // 13 + "weapon_pipe_bomb", // 14 + "weapon_pain_pills", // 15 + "weapon_gascan", // 16 + "weapon_propanetank", // 17 + "weapon_oxygentank", // 18 + "weapon_melee", // 19 + "weapon_chainsaw", // 20 + "weapon_grenade_launcher", // 21 + "weapon_ammo_pack", // 22 + "weapon_adrenaline", // 23 + "weapon_defibrillator", // 24 + "weapon_vomitjar", // 25 + "weapon_rifle_ak47", // 26 + "weapon_gnome", // 27 + "weapon_cola_bottles", // 28 + "weapon_fireworkcrate", // 29 + "weapon_upgradepack_incendiary", // 30 + "weapon_upgradepack_explosive", // 31 + "weapon_pistol_magnum", // 32 + "weapon_smg_mp5", // 33 + "weapon_rifle_sg552", // 34 + "weapon_sniper_awp", // 35 + "weapon_sniper_scout", // 36 + "weapon_rifle_m60", // 37 + "weapon_tank_claw", // 38 + "weapon_hunter_claw", // 39 + "weapon_charger_claw", // 40 + "weapon_boomer_claw", // 41 + "weapon_smoker_claw", // 42 + "weapon_spitter_claw", // 43 + "weapon_jockey_claw", // 44 + "weapon_machinegun", // 45 + "vomit", // 46 + "splat", // 47 + "pounce", // 48 + "lounge", // 49 + "pull", // 50 + "choke", // 51 + "rock", // 52 + "physics", // 53 + "weapon_ammo", // 54 + "upgrade_item", // 55 + "" +}; + +static const char L4D2WeaponWorldModel[L4D2WeaponId][] = +{ + "", + "/w_models/weapons/w_pistol_b.mdl", + "/w_models/weapons/w_smg_uzi.mdl", + "/w_models/weapons/w_shotgun.mdl", + "/w_models/weapons/w_autoshot_m4super.mdl", + "/w_models/weapons/w_rifle_m16a2.mdl", + "/w_models/weapons/w_sniper_mini14.mdl", + "/w_models/weapons/w_smg_a.mdl", + "/w_models/weapons/w_pumpshotgun_a.mdl", + "/w_models/weapons/w_desert_rifle.mdl", // "/w_models/weapons/w_rifle_b.mdl" + "/w_models/weapons/w_sniper_military.mdl", + "/w_models/weapons/w_shotgun_spas.mdl", + "/w_models/weapons/w_eq_medkit.mdl", + "/w_models/weapons/w_eq_molotov.mdl", + "/w_models/weapons/w_eq_pipebomb.mdl", + "/w_models/weapons/w_eq_painpills.mdl", + "/props_junk/gascan001a.mdl", + "/props_junk/propanecanister001.mdl", + "/props_equipment/oxygentank01.mdl", + "", // "/weapons/w_knife_t.mdl", + // "/weapons/melee/w_bat.mdl", + // "/weapons/melee/w_chainsaw.mdl + // "/weapons/melee/w_cricket_bat.mdl", + // "/weapons/melee/w_crowbar.mdl", + // "/weapons/melee/w_didgeridoo.mdl", + // "/weapons/melee/w_electric_guitar.mdl", + // "/weapons/melee/w_fireaxe.mdl", + // "/weapons/melee/w_frying_pan.mdl", + // "/weapons/melee/w_golfclub.mdl", + // "/weapons/melee/w_katana.mdl", + // "/weapons/melee/w_machete.mdl", + // "/weapons/melee/w_riotshield.mdl", + // "/weapons/melee/w_tonfa.mdl" + "/weapons/melee/w_chainsaw.mdl", + "/w_models/weapons/w_grenade_launcher.mdl", + "", + "/w_models/weapons/w_eq_adrenaline.mdl", + "/w_models/weapons/w_eq_defibrillator.mdl", + "/w_models/weapons/w_eq_bile_flask.mdl", + "/w_models/weapons/w_rifle_ak47.mdl", + "/props_junk/gnome.mdl", + "/w_models/weapons/w_cola.mdl", + "/props_junk/explosive_box001.mdl", + "/w_models/weapons/w_eq_incendiary_ammopack.mdl", + "/w_models/weapons/w_eq_explosive_ammopack.mdl", + "/w_models/weapons/w_desert_eagle.mdl", + "/w_models/weapons/w_smg_mp5.mdl", + "/w_models/weapons/w_rifle_sg552.mdl", + "/w_models/weapons/w_sniper_awp.mdl", + "/w_models/weapons/w_sniper_scout.mdl", + "/w_models/weapons/w_m60.mdl", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" +}; + +StringMap g_hWeaponNameTrie; + +/** + * Returns whether weapon id is valid. + * + * @param weaponId Weapon id to check for validity. + * @return True if weapon id is valid, false otherwise. + */ +// L4D2 only. +stock bool L4D2_IsValidWeaponId(L4D2WeaponId weaponId) +{ + return weaponId >= L4D2WeaponId_None && weaponId < L4D2WeaponId_MAX; +} + +/** + * Returns whether weapon name is a valid weapon. + * + * @param weaponName Weapon name to check for validity. + * @return True if weapon name is valid, false otherwise. + */ +// L4D2 only. +stock bool L4D2_IsValidWeaponName(const char[] weaponName) +{ + return L4D2_GetWeaponIdByWeaponName(weaponName) != L4D2WeaponId_None; +} + +/** + * Checks to see if a given weapon id has a known WeaponModel in this file's model array. + * + * Note: The melee weapon have multiple valid models. This function will + * return false for melee weapon. + * + * @param weaponId Weapon id to check for a known weapon model for. + * @return True if a valid weapon model exists for weapon id, false otherwise. + */ +// L4D2 only. +stock bool L4D2_HasValidWeaponWorldModel(L4D2WeaponId weaponId) +{ + return L4D2WeaponWorldModel[weaponId][0] != '\0'; +} + +/** + * Returns weapon world model by weapon id. + * + * @note Does not work with melee weapons. + * + * @param weaponId Weapon id. + * @param dest Destination string buffer to copy to. + * @param destlen Destination buffer length (includes null terminator). + * @return Number of cells written. + */ +// L4D2 only. +stock int L4D2_GetWeaponModelByWeaponId(L4D2WeaponId weaponId, char[] dest, int destlen) +{ + if (!L4D2_IsValidWeaponId(weaponId)) + { + return 0; + } + + return strcopy(dest, destlen, L4D2WeaponWorldModel[weaponId]); +} + +/** + * Returns weapon id by weapon world model. + * + * @note Does not work with melee weapons. + * + * @param model Weapon world model. + * @return Weapon Id. + */ +// L4D2 only. +stock L4D2WeaponId L4D2_GetWeaponIdByWeaponModel(const char[] model) +{ + for (int i = 0; i < sizeof(L4D2WeaponWorldModel); i++) + { + if (strcmp(model, L4D2WeaponWorldModel[i], false) == 0) + { + return view_as(i); + } + } + + return L4D2WeaponId_None; +} + +/** + * Returns weapon id by weapon name. + * + * @param weaponName Weapon name to get id from. + * @return The corresponding weapon id if found, else L4D2WeaponId_None. + */ +// L4D2 only. +stock L4D2WeaponId L4D2_GetWeaponIdByWeaponName(const char[] weaponName) +{ + L4D2_InitWeaponNameTrie(); + L4D2WeaponId weaponId; + return g_hWeaponNameTrie.GetValue(weaponName, weaponId) ? weaponId : L4D2WeaponId_None; +} + +/** + * Returns weapon name by weapon id. + * + * @param weaponName Weapon id to get name from. + * @param dest Destination string buffer to copy to. + * @param destlen Destination buffer length (includes null terminator). + * @return Number of cells written. + */ +// L4D2 only. +stock int L4D2_GetWeaponNameByWeaponId(L4D2WeaponId weaponId, char[] dest, int destlen) +{ + if (!L4D2_IsValidWeaponId(weaponId)) + { + return 0; + } + + return strcopy(dest, destlen, L4D2WeaponName[weaponId]); +} + +/** + * Returns weapon id of entity. + * + * @param weapon Entity index of weapon. + * @return Weapon id if found, L4D2WeaponId_None otherwise. + * @error Invalid entity index. + */ +// L4D2 only. +stock L4D2WeaponId L4D2_GetWeaponId(int weapon) +{ + char classname[64]; + if (!GetEdictClassname(weapon, classname, sizeof(classname))) + { + return L4D2WeaponId_None; + } + + if (strcmp(classname, "weapon_spawn") == 0) + { + return view_as(GetEntProp(weapon, Prop_Send, "m_weaponID")); + } + + int len = strlen(classname); + if (len - 6 > 0 && strcmp(classname[len - 6], "_spawn") == 0) + { + classname[len - 6] = '\0'; + } + + return L4D2_GetWeaponIdByWeaponName(classname); +} + +/** + * Initialize the L4D2 weapon names trie. Not necessary to be executed, done by the functions that require the trie. + * + * @noreturn + */ +// L4D2 only. +stock void L4D2_InitWeaponNameTrie() +{ + if (g_hWeaponNameTrie != null) + { + return; + } + + g_hWeaponNameTrie = new StringMap(); + for (int i = 0; i < view_as(L4D2WeaponId_MAX); i++) + { + g_hWeaponNameTrie.SetValue(L4D2WeaponName[i], i); + } +} \ No newline at end of file diff --git a/scripting/include/multicolors.inc b/scripting/include/multicolors.inc new file mode 100644 index 0000000..e6612a7 --- /dev/null +++ b/scripting/include/multicolors.inc @@ -0,0 +1,460 @@ +#if defined _multicolors_included + #endinput +#endif +#define _multicolors_included + +#define MuCo_VERSION "2.1.2" + +#include +#include + +/* +* +* Credits: +* - Popoklopsi +* - Powerlord +* - exvel +* - Dr. McKay +* +* Based on stamm-colors +* - https://github.com/popoklopsi/Stamm/blob/master/include/stamm/stamm-colors.inc +* +*/ + + + +#define PREFIX_MAX_LENGTH 64 +#define PREFIX_SEPARATOR "{default} " + +/* Global var to check whether colors are fixed or not */ +static bool g_bCFixColors; + +static char g_sCPrefix[PREFIX_MAX_LENGTH]; + +/** + * Add a chat prefix before all chat msg + * + * @param sPrefix Prefix + */ +stock void CSetPrefix(const char[] sPrefix, any ...) { + if (!sPrefix[0]) { + return; + } + + SetGlobalTransTarget(LANG_SERVER); + VFormat(g_sCPrefix, sizeof(g_sCPrefix) - strlen(PREFIX_SEPARATOR), sPrefix, 2); + + // Add ending space + Format(g_sCPrefix, sizeof(g_sCPrefix), "%s%s", g_sCPrefix, PREFIX_SEPARATOR); +} + +/** + * Add a chat prefix before all chat msg + * + * @param sPrefix Prefix + */ +stock void CClearPrefix() { + g_sCPrefix[0] = '\0'; +} + +/** + * Writes a message to a client with the correct stock for the game. + * + * @param client Client index. + * @param message Message (formatting rules). + * + * @error If the client is not connected an error will be thrown. + */ +stock void CPrintToChat(int client, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_PrintToChat(client, "%s%s", g_sCPrefix, buffer); + } + else { + MC_PrintToChat(client, "%s%s", g_sCPrefix, buffer); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param message Message (formatting rules) + */ +stock void CPrintToChatAll(const char[] message, any ...) { + if (!g_bCFixColors) { + CFixColors(); + } + + char buffer[MAX_BUFFER_LENGTH]; + if (!IsSource2009()) { + for (int i = 1; i <= MaxClients; ++i) { + if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) { + SetGlobalTransTarget(i); + VFormat(buffer, sizeof(buffer), message, 2); + + C_PrintToChat(i, "%s", buffer); + } + + C_SkipList[i] = false; + } + } + else { + MC_CheckTrie(); + + char buffer2[MAX_BUFFER_LENGTH]; + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || MC_SkipList[i]) { + MC_SkipList[i] = false; + continue; + } + + SetGlobalTransTarget(i); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 2); + + MC_ReplaceColorCodes(buffer2); + MC_SendMessage(i, buffer2); + } + } +} + +/** + * Writes a message to all of a client's observers. + * + * @param target Client index. + * @param message Message (formatting rules). + */ +stock void CPrintToChatObservers(int target, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + for (int client = 1; client <= MaxClients; client++) { + if (IsClientInGame(client) && !IsPlayerAlive(client) && !IsFakeClient(client)) { + int observee = GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); + int ObserverMode = GetEntProp(client, Prop_Send, "m_iObserverMode"); + + if (observee == target && (ObserverMode == 4 || ObserverMode == 5)) { + CPrintToChat(client, buffer); + } + } + } +} + +/** + * Writes a message to a client with the correct stock for the game. + * + * @param client Client index. + * @param author Author index. + * @param message Message (formatting rules). + * + * @error If the client is not connected an error will be thrown. + */ +stock void CPrintToChatEx(int client, int author, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 4); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_PrintToChatEx(client, author, "%s%s", g_sCPrefix, buffer); + } + else { + MC_PrintToChatEx(client, author, "%s%s", g_sCPrefix, buffer); + } +} + +/** + * Writes a message to all clients with the correct stock for the game. + * + * @param author Author index. + * @param message Message (formatting rules). + */ +stock void CPrintToChatAllEx(int author, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_PrintToChatAllEx(author, "%s%s", g_sCPrefix, buffer); + } + else { + MC_PrintToChatAllEx(author, "%s%s", g_sCPrefix, buffer); + } +} + +/** + * Writes a message to all of a client's observers with the correct + * game stock. + * + * @param target Client index. + * @param message Message (formatting rules). + */ +stock void CPrintToChatObserversEx(int target, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + for (int client = 1; client <= MaxClients; client++) { + if (IsClientInGame(client) && !IsPlayerAlive(client) && !IsFakeClient(client)) { + int observee = GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); + int ObserverMode = GetEntProp(client, Prop_Send, "m_iObserverMode"); + + if (observee == target && (ObserverMode == 4 || ObserverMode == 5)) { + CPrintToChatEx(client, target, buffer); + } + } + } +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param message Message (formatting rules) + */ +stock void CReplyToCommand(int client, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_ReplyToCommand(client, "%s%s", g_sCPrefix, buffer); + } + else { + MC_ReplyToCommand(client, "%s%s", g_sCPrefix, buffer); + } +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param author Client to use for {teamcolor} + * @param message Message (formatting rules) + */ +stock void CReplyToCommandEx(int client, int author, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 4); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_ReplyToCommandEx(client, author, "%s%s", g_sCPrefix, buffer); + } + else { + MC_ReplyToCommandEx(client, author, "%s%s", g_sCPrefix, buffer); + } +} + +/** + * Remove all tags and print to server + * + * @param message Message (formatting rules) + */ +stock void CPrintToServer(const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + char prefixBuffer[PREFIX_MAX_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 2); + strcopy(prefixBuffer, sizeof(prefixBuffer), g_sCPrefix); + + if (!g_bCFixColors) { + CFixColors(); + } + + CRemoveTags(buffer, sizeof(buffer)); + CRemoveTags(prefixBuffer, sizeof(prefixBuffer)); + + PrintToServer("%s%s", prefixBuffer, buffer); +} + +/** + * Displays usage of an admin command to users depending on the + * setting of the sm_show_activity cvar. + * + * This version does not display a message to the originating client + * if used from chat triggers or menus. If manual replies are used + * for these cases, then this function will suffice. Otherwise, + * CShowActivity2() is slightly more useful. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * + * @error + */ +stock void CShowActivity(int author, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 3); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_ShowActivity(author, "%s", buffer); + } + else { + MC_ShowActivity(author, "%s", buffer); + } +} + +/** + * Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing). + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * + * @error + */ +stock void CShowActivityEx(int author, const char[] tag, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 4); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_ShowActivityEx(author, tag, "%s", buffer); + } + else { + MC_ShowActivityEx(author, tag, "%s", buffer); + } +} + +/** + * Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar. + * All users receive a message in their chat text, except for the originating client, + * who receives the message based on the current ReplySource. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * + * @error + */ + stock void CShowActivity2(int author, const char[] tag, const char[] message, any ...) { + char buffer[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(LANG_SERVER); + VFormat(buffer, sizeof(buffer), message, 4); + + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + C_ShowActivity2(author, tag, "%s", buffer); + } + else { + MC_ShowActivity2(author, tag, "%s", buffer); + } +} + +/** + * Replaces color tags in a string with color codes + * + * @param message String. + * @param maxlength Maximum length of the string buffer. + */ +stock void CFormatColor(char[] message, int maxlength, int author = -1) { + if (!g_bCFixColors) { + CFixColors(); + } + + if (!IsSource2009()) { + if (author == 0) { + author = -1; + } + + C_Format(message, maxlength, author); + } + else { + if (author == -1) { + author = 0; + } + + MC_ReplaceColorCodes(message, author, false, maxlength); + } +} + +/** + * Removes color tags from a message + * + * @param message Message to remove tags from + * @param maxlen Maximum buffer length + */ +stock void CRemoveTags(char[] message, int maxlen) { + if (!IsSource2009()) { + C_RemoveTags(message, maxlen); + } + else { + MC_RemoveTags(message, maxlen); + } +} + +/** + * Fixes missing Lightgreen color. + */ +stock void CFixColors() { + g_bCFixColors = true; + + // Replace lightgreen if not exists + if (!C_ColorAllowed(Color_Lightgreen)) { + if (C_ColorAllowed(Color_Lime)) { + C_ReplaceColor(Color_Lightgreen, Color_Lime); + } + else if (C_ColorAllowed(Color_Olive)) { + C_ReplaceColor(Color_Lightgreen, Color_Olive); + } + } +} + +stock bool IsSource2009() { + return (GetEngineVersion() == Engine_CSS + || GetEngineVersion() == Engine_HL2DM + || GetEngineVersion() == Engine_DODS + || GetEngineVersion() == Engine_TF2 + || GetEngineVersion() == Engine_SDK2013); +} diff --git a/scripting/include/multicolors/colors.inc b/scripting/include/multicolors/colors.inc new file mode 100644 index 0000000..5931c9a --- /dev/null +++ b/scripting/include/multicolors/colors.inc @@ -0,0 +1,898 @@ +/************************************************************************** + * * + * Colored Chat Functions * + * Author: exvel, Editor: Popoklopsi, Powerlord, Bara * + * Version: 2.0.0-MC * + * * + **************************************************************************/ + + +#if defined _colors_included + #endinput +#endif +#define _colors_included + +#define MAX_MESSAGE_LENGTH 250 +#define MAX_COLORS 18 + +#define SERVER_INDEX 0 +#define NO_INDEX -1 +#define NO_PLAYER -2 + +enum C_Colors { + Color_Default = 0, + Color_Darkred, + Color_Green, + Color_Lightgreen, + Color_Red, + Color_Blue, + Color_Olive, + Color_Lime, + Color_Lightred, + Color_Purple, + Color_Grey, + Color_Yellow, + Color_Orange, + Color_Bluegrey, + Color_Lightblue, + Color_Darkblue, + Color_Grey2, + Color_Orchid, + Color_Lightred2 +} + +/* C_Colors' properties */ +char C_Tag[][] = {"{default}", "{darkred}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}", "{lime}", "{lightred}", "{purple}", "{grey}", "{yellow}", "{orange}", "{bluegrey}", "{lightblue}", "{darkblue}", "{grey2}", "{orchid}", "{lightred2}"}; +char C_TagCode[][] = {"\x01", "\x02", "\x04", "\x03", "\x03", "\x03", "\x05", "\x06", "\x07", "\x03", "\x08", "\x09", "\x10", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F"}; +bool C_TagReqSayText2[] = {false, false, false, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false}; +bool C_EventIsHooked; +bool C_SkipList[MAXPLAYERS+1]; + +/* Game default profile */ +bool C_Profile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}; +int C_Profile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX}; +bool C_Profile_SayText2; + +static ConVar sm_show_activity; + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client is not connected an error will be thrown. + */ +stock void C_PrintToChat(int client, const char[] szMessage, any ...) { + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %d", client); + } + + if (!IsClientInGame(client)) { + ThrowError("Client %d is not in game", client); + } + + char szBuffer[MAX_MESSAGE_LENGTH]; + char szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3); + + int index = C_Format(szCMessage, sizeof(szCMessage)); + + if (index == NO_INDEX) { + PrintToChat(client, "%s", szCMessage); + } + else { + C_SayText2(client, index, szCMessage); + } +} + +/** + * Reples to a message in a command. A client index of 0 will use PrintToServer(). + * If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used. + * Supports color tags. + * + * @param client Client index, or 0 for server. + * @param szMessage Formatting rules. + * @param ... Variable number of format parameters. + * @return No return + * + * On error/Errors: If the client is not connected or invalid. + */ +stock void C_ReplyToCommand(int client, const char[] szMessage, any ...) { + char szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(szCMessage, sizeof(szCMessage), szMessage, 3); + + if (client == 0) { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToServer("%s", szCMessage); + } + else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToConsole(client, "%s", szCMessage); + } + else { + C_PrintToChat(client, "%s", szCMessage); + } +} + +/** + * Reples to a message in a command. A client index of 0 will use PrintToServer(). + * If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used. + * Supports color tags. + * + * @param client Client index, or 0 for server. + * @param author Author index whose color will be used for teamcolor tag. + * @param szMessage Formatting rules. + * @param ... Variable number of format parameters. + * @return No return + * + * On error/Errors: If the client is not connected or invalid. + */ +stock void C_ReplyToCommandEx(int client, int author, const char[] szMessage, any ...) { + char szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(szCMessage, sizeof(szCMessage), szMessage, 4); + + if (client == 0) { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToServer("%s", szCMessage); + } + else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToConsole(client, "%s", szCMessage); + } + else { + C_PrintToChatEx(client, author, "%s", szCMessage); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules) + * @return No return + */ +stock void C_PrintToChatAll(const char[] szMessage, any ...) { + char szBuffer[MAX_MESSAGE_LENGTH]; + + for (int i = 1; i <= MaxClients; ++i) { + if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 2); + + C_PrintToChat(i, "%s", szBuffer); + } + + C_SkipList[i] = false; + } +} + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags and teamcolor tag. + * + * @param client Client index. + * @param author Author index whose color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client or author are not connected an error will be thrown. + */ +stock void C_PrintToChatEx(int client, int author, const char[] szMessage, any ...) { + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %d", client); + } + + if (!IsClientInGame(client)) { + ThrowError("Client %d is not in game", client); + } + + if (author < 0 || author > MaxClients) { + ThrowError("Invalid client index %d", author); + } + + char szBuffer[MAX_MESSAGE_LENGTH]; + char szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4); + + int index = C_Format(szCMessage, sizeof(szCMessage), author); + + if (index == NO_INDEX) { + PrintToChat(client, "%s", szCMessage); + } + else { + C_SayText2(client, author, szCMessage); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags and teamcolor tag. + * + * @param author Author index whos color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the author is not connected an error will be thrown. + */ +stock void C_PrintToChatAllEx(int author, const char[] szMessage, any ...) { + if (author < 0 || author > MaxClients) { + ThrowError("Invalid client index %d", author); + } + + if (!IsClientInGame(author)) { + ThrowError("Client %d is not in game", author); + } + + char szBuffer[MAX_MESSAGE_LENGTH]; + + for (int i = 1; i <= MaxClients; ++i) { + if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 3); + + C_PrintToChatEx(i, author, "%s", szBuffer); + } + + C_SkipList[i] = false; + } +} + +/** + * Removes color tags from the string. + * + * @param szMessage String. + * @return No return + */ +stock void C_RemoveTags(char[] szMessage, int maxlength) { + for (int i = 0; i < MAX_COLORS; i++) { + ReplaceString(szMessage, maxlength, C_Tag[i], "", false); + } + + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); +} + +/** + * Checks whether a color is allowed or not + * + * @param tag Color Tag. + * @return True when color is supported, otherwise false + */ +stock bool C_ColorAllowed(C_Colors color) { + if (!C_EventIsHooked) { + C_SetupProfile(); + + C_EventIsHooked = true; + } + + return C_Profile_Colors[color]; +} + +/** + * Replace the color with another color + * Handle with care! + * + * @param color color to replace. + * @param newColor color to replace with. + * @noreturn + */ +stock void C_ReplaceColor(C_Colors color, C_Colors newColor) { + if (!C_EventIsHooked) { + C_SetupProfile(); + + C_EventIsHooked = true; + } + + C_Profile_Colors[color] = C_Profile_Colors[newColor]; + C_Profile_TeamIndex[color] = C_Profile_TeamIndex[newColor]; + + C_TagReqSayText2[color] = C_TagReqSayText2[newColor]; + Format(C_TagCode[color], sizeof(C_TagCode[]), C_TagCode[newColor]); +} + +/** + * This function should only be used right in front of + * C_PrintToChatAll or C_PrintToChatAllEx and it tells + * to those funcions to skip specified client when printing + * message to all clients. After message is printed client will + * no more be skipped. + * + * @param client Client index + * @return No return + */ +stock void C_SkipNextClient(int client) { + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %d", client); + } + + C_SkipList[client] = true; +} + +/** + * Replaces color tags in a string with color codes + * + * @param szMessage String. + * @param maxlength Maximum length of the string buffer. + * @return Client index that can be used for SayText2 author index + * + * On error/Errors: If there is more then one team color is used an error will be thrown. + */ +stock int C_Format(char[] szMessage, int maxlength, int author = NO_INDEX) { + /* Hook event for auto profile setup on map start */ + if (!C_EventIsHooked) { + C_SetupProfile(); + HookEvent("server_spawn", C_Event_MapStart, EventHookMode_PostNoCopy); + + C_EventIsHooked = true; + } + + int iRandomPlayer = NO_INDEX; + + // On CS:GO set invisible precolor + if (GetEngineVersion() == Engine_CSGO) { + Format(szMessage, maxlength, " %s", szMessage); + } + + /* If author was specified replace {teamcolor} tag */ + if (author != NO_INDEX) { + if (C_Profile_SayText2) { + ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false); + + iRandomPlayer = author; + } + /* If saytext2 is not supported by game replace {teamcolor} with green tag */ + else { + ReplaceString(szMessage, maxlength, "{teamcolor}", C_TagCode[Color_Green], false); + } + } + else { + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); + } + + /* For other color tags we need a loop */ + for (int i = 0; i < MAX_COLORS; i++) { + /* If tag not found - skip */ + if (StrContains(szMessage, C_Tag[i], false) == -1) { + continue; + } + + /* If tag is not supported by game replace it with green tag */ + else if (!C_Profile_Colors[i]) { + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + } + + /* If tag doesn't need saytext2 simply replace */ + else if (!C_TagReqSayText2[i]) { + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false); + } + + /* Tag needs saytext2 */ + else { + /* If saytext2 is not supported by game replace tag with green tag */ + if (!C_Profile_SayText2) { + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + } + + /* Game supports saytext2 */ + else { + /* If random player for tag wasn't specified replace tag and find player */ + if (iRandomPlayer == NO_INDEX) { + /* Searching for valid client for tag */ + iRandomPlayer = C_FindRandomPlayerByTeam(C_Profile_TeamIndex[i]); + + /* If player not found replace tag with green color tag */ + if (iRandomPlayer == NO_PLAYER) { + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + } + + /* If player was found simply replace */ + else { + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false); + } + + } + /* If found another team color tag throw error */ + else { + //ReplaceString(szMessage, maxlength, C_Tag[i], ""); + ThrowError("Using two team colors in one message is not allowed"); + } + } + } + } + + return iRandomPlayer; +} + +/** + * Finds a random player with specified team + * + * @param color_team Client team. + * @return Client index or NO_PLAYER if no player found + */ +stock int C_FindRandomPlayerByTeam(int color_team) { + if (color_team == SERVER_INDEX) { + return 0; + } + + int[] players = new int[MaxClients]; + int count; + + for (int i = 1; i <= MaxClients; ++i) { + if (IsClientInGame(i) && GetClientTeam(i) == color_team) { + players[count++] = i; + } + } + + if (count) { + return players[GetRandomInt(0, count-1)]; + } + + return NO_PLAYER; +} + +/** + * Sends a SayText2 usermessage to a client + * + * @param szMessage Client index + * @param maxlength Author index + * @param szMessage Message + * @return No return. + */ +stock void C_SayText2(int client, int author, const char[] szMessage) { + Handle hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { + Protobuf pb = UserMessageToProtobuf(hBuffer); + pb.SetInt("ent_idx", author); + pb.SetBool("chat", true); + pb.SetString("msg_name", szMessage); + pb.AddString("params", ""); + pb.AddString("params", ""); + pb.AddString("params", ""); + pb.AddString("params", ""); + } + else { + BfWrite bf = UserMessageToBfWrite(hBuffer); + bf.WriteByte(author); + bf.WriteByte(true); + bf.WriteString(szMessage); + } + + EndMessage(); +} + +/** + * Creates game color profile + * This function must be edited if you want to add more games support + * + * @return No return. + */ +stock void C_SetupProfile() { + EngineVersion engine = GetEngineVersion(); + + if (engine == Engine_CSS) { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_CSGO) { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_Colors[Color_Darkred] = true; + C_Profile_Colors[Color_Lime] = true; + C_Profile_Colors[Color_Lightred] = true; + C_Profile_Colors[Color_Purple] = true; + C_Profile_Colors[Color_Grey] = true; + C_Profile_Colors[Color_Yellow] = true; + C_Profile_Colors[Color_Orange] = true; + C_Profile_Colors[Color_Bluegrey] = true; + C_Profile_Colors[Color_Lightblue] = true; + C_Profile_Colors[Color_Darkblue] = true; + C_Profile_Colors[Color_Grey2] = true; + C_Profile_Colors[Color_Orchid] = true; + C_Profile_Colors[Color_Lightred2] = true; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_TF2) { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_Left4Dead || engine == Engine_Left4Dead2) { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 3; + C_Profile_TeamIndex[Color_Blue] = 2; + C_Profile_SayText2 = true; + } + else if (engine == Engine_HL2DM) { + /* hl2mp profile is based on mp_teamplay convar */ + if (GetConVarBool(FindConVar("mp_teamplay"))) { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Red] = 3; + C_Profile_TeamIndex[Color_Blue] = 2; + C_Profile_SayText2 = true; + } + else { + C_Profile_SayText2 = false; + C_Profile_Colors[Color_Olive] = true; + } + } + else if (engine == Engine_DODS) { + C_Profile_Colors[Color_Olive] = true; + C_Profile_SayText2 = false; + } + /* Profile for other games */ + else { + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { + C_Profile_SayText2 = false; + } + else { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + } +} + +public Action C_Event_MapStart(Event event, const char[] name, bool dontBroadcast) { + C_SetupProfile(); + + for (int i = 1; i <= MaxClients; ++i) { + C_SkipList[i] = false; + } + return Plugin_Continue; +} + +/** + * Displays usage of an admin command to users depending on the + * setting of the sm_show_activity cvar. + * + * This version does not display a message to the originating client + * if used from chat triggers or menus. If manual replies are used + * for these cases, then this function will suffice. Otherwise, + * C_ShowActivity2() is slightly more useful. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivity(int client, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char tag[] = "[SM] "; + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) { + ThrowError("Client index %d is invalid", client); + } + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 8) || ((value & 16) && is_root) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing). + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) { + ThrowError("Client index %d is invalid", client); + } + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 8) || ((value & 16) && is_root) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar. + * All users receive a message in their chat text, except for the originating client, + * who receives the message based on the current ReplySource. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivity2(int client, const char[] tag, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + // ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) { + ThrowError("Client index %d is invalid", client); + } + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + /* We don't display directly to the console because the chat text + * simply gets added to the console, so we don't want it to print + * twice. + */ + C_PrintToChatEx(client, client, "%s%s", tag, szBuffer); + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || i == client) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 8) || ((value & 16) && is_root)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} diff --git a/scripting/include/multicolors/morecolors.inc b/scripting/include/multicolors/morecolors.inc new file mode 100644 index 0000000..2020b60 --- /dev/null +++ b/scripting/include/multicolors/morecolors.inc @@ -0,0 +1,992 @@ +// MOAR COLORS +// By Dr. McKay +// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831 + +#if defined _more_colors_included + #endinput +#endif +#define _more_colors_included + +#pragma newdecls optional +#include + +#define MORE_COLORS_VERSION "2.0.0-MC" +#define MC_MAX_MESSAGE_LENGTH 256 +#define MAX_BUFFER_LENGTH (MC_MAX_MESSAGE_LENGTH * 4) + +#define MCOLOR_RED 0xFF4040 +#define MCOLOR_BLUE 0x99CCFF +#define MCOLOR_GRAY 0xCCCCCC +#define MCOLOR_GREEN 0x3EFF3E + +#define MC_GAME_DODS 0 + +bool MC_SkipList[MAXPLAYERS+1]; +StringMap MC_Trie; +int MC_TeamColors[][] = {{0xCCCCCC, 0x4D7942, 0xFF4040}}; // Multi-dimensional array for games that don't support SayText2. First index is the game index (as defined by the GAME_ defines), second index is team. 0 = spectator, 1 = team1, 2 = team2 + +static ConVar sm_show_activity; + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param message Message (formatting rules). + * + * On error/Errors: If the client is not connected an error will be thrown. + */ +stock void MC_PrintToChat(int client, const char[] message, any ...) { + MC_CheckTrie(); + + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + + if (!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + + char buffer[MAX_BUFFER_LENGTH]; + char buffer2[MAX_BUFFER_LENGTH]; + + SetGlobalTransTarget(client); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 3); + + MC_ReplaceColorCodes(buffer2); + MC_SendMessage(client, buffer2); +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param message Message (formatting rules). + */ +stock void MC_PrintToChatAll(const char[] message, any ...) { + MC_CheckTrie(); + + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || MC_SkipList[i]) { + MC_SkipList[i] = false; + continue; + } + + SetGlobalTransTarget(i); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 2); + + MC_ReplaceColorCodes(buffer2); + MC_SendMessage(i, buffer2); + } +} + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags and teamcolor tag. + * + * @param client Client index. + * @param author Author index whose color will be used for teamcolor tag. + * @param message Message (formatting rules). + * + * On error/Errors: If the client or author are not connected an error will be thrown + */ +stock void MC_PrintToChatEx(int client, int author, const char[] message, any ...) { + MC_CheckTrie(); + + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + + if (!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + + if (author <= 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + + if (!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 4); + MC_ReplaceColorCodes(buffer2, author); + MC_SendMessage(client, buffer2, author); +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags and teamcolor tag. + * + * @param author Author index whose color will be used for teamcolor tag. + * @param message Message (formatting rules). + * + * On error/Errors: If the author is not connected an error will be thrown. + */ +stock void MC_PrintToChatAllEx(int author, const char[] message, any ...) { + MC_CheckTrie(); + + if (author <= 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + + if (!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + + char buffer[MAX_BUFFER_LENGTH]; + char buffer2[MAX_BUFFER_LENGTH]; + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || MC_SkipList[i]) { + MC_SkipList[i] = false; + continue; + } + + SetGlobalTransTarget(i); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 3); + + MC_ReplaceColorCodes(buffer2, author); + MC_SendMessage(i, buffer2, author); + } +} + +/** + * Sends a SayText2 usermessage + * + * @param client Client to send usermessage to + * @param message Message to send + */ +stock void MC_SendMessage(int client, const char[] message, int author = 0) { + if (author == 0) { + author = client; + } + + char buffer[MC_MAX_MESSAGE_LENGTH]; + strcopy(buffer, sizeof(buffer), message); + + UserMsg index = GetUserMessageId("SayText2"); + if (index == INVALID_MESSAGE_ID) { + if (GetEngineVersion() == Engine_DODS) { + int team = GetClientTeam(author); + if (team == 0) { + ReplaceString(buffer, sizeof(buffer), "\x03", "\x04", false); // Unassigned gets green + } + else { + char temp[16]; + Format(temp, sizeof(temp), "\x07%06X", MC_TeamColors[MC_GAME_DODS][team - 1]); + ReplaceString(buffer, sizeof(buffer), "\x03", temp, false); + } + } + + PrintToChat(client, "%s", buffer); + return; + } + + Handle buf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS); + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { + Protobuf pb = UserMessageToProtobuf(buf); + pb.SetInt("ent_idx", author); + pb.SetBool("chat", true); + pb.SetString("msg_name", buffer); + pb.AddString("params", ""); + pb.AddString("params", ""); + pb.AddString("params", ""); + pb.AddString("params", ""); + } + else { + BfWrite bf = UserMessageToBfWrite(buf); + bf.WriteByte(author); // Message author + bf.WriteByte(true); // Chat message + bf.WriteString(buffer); // Message text + } + + EndMessage(); +} + +/** + * This function should only be used right in front of + * MC_PrintToChatAll or MC_PrintToChatAllEx. It causes those functions + * to skip the specified client when printing the message. + * After printing the message, the client will no longer be skipped. + * + * @param client Client index + */ +stock void MC_SkipNextClient(int client) { + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + + MC_SkipList[client] = true; +} + +/** + * Checks if the colors trie is initialized and initializes it if it's not (used internally) + * + * @return No return + */ +stock void MC_CheckTrie() { + if (MC_Trie == null) { + MC_Trie = MC_InitColorTrie(); + } +} + +/** + * Replaces color tags in a string with color codes (used internally by MC_PrintToChat, MC_PrintToChatAll, MC_PrintToChatEx, and MC_PrintToChatAllEx + * + * @param buffer String. + * @param author Optional client index to use for {teamcolor} tags, or 0 for none + * @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by MC_RemoveTags + * @param maxlen Optional value for max buffer length, used by MC_RemoveTags + * + * On error/Errors: If the client index passed for author is invalid or not in game. + */ +stock void MC_ReplaceColorCodes(char[] buffer, int author = 0, bool removeTags = false, int maxlen = MAX_BUFFER_LENGTH) { + MC_CheckTrie(); + if (!removeTags) { + ReplaceString(buffer, maxlen, "{default}", "\x01", false); + } + else { + ReplaceString(buffer, maxlen, "{default}", "", false); + ReplaceString(buffer, maxlen, "{teamcolor}", "", false); + } + + if (author != 0 && !removeTags) { + if (author < 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + + if (!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + + ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false); + } + + int cursor = 0; + int value; + char tag[32], buff[32]; + char[] output = new char[maxlen]; + + strcopy(output, maxlen, buffer); + // Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer + + Regex regex = new Regex("{[#a-zA-Z0-9]+}"); + for (int i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe. + if (regex.Match(buffer[cursor]) < 1) { + delete regex; + strcopy(buffer, maxlen, output); + return; + } + + regex.GetSubString(0, tag, sizeof(tag)); + MC_StrToLower(tag); + cursor = StrContains(buffer[cursor], tag, false) + cursor + 1; + strcopy(buff, sizeof(buff), tag); + ReplaceString(buff, sizeof(buff), "{", ""); + ReplaceString(buff, sizeof(buff), "}", ""); + + if (buff[0] == '#') { + if (strlen(buff) == 7) { + Format(buff, sizeof(buff), "\x07%s", buff[1]); + } + else if (strlen(buff) == 9) { + Format(buff, sizeof(buff), "\x08%s", buff[1]); + } + else { + continue; + } + + if (removeTags) { + ReplaceString(output, maxlen, tag, "", false); + } + else { + ReplaceString(output, maxlen, tag, buff, false); + } + } + else if (!MC_Trie.GetValue(buff, value)) { + continue; + } + + if (removeTags) { + ReplaceString(output, maxlen, tag, "", false); + } + else { + Format(buff, sizeof(buff), "\x07%06X", value); + ReplaceString(output, maxlen, tag, buff, false); + } + } + LogError("[MORE COLORS] Infinite loop broken."); +} + +/** + * Gets a part of a string + * + * @param input String to get the part from + * @param output Buffer to write to + * @param maxlen Max length of output buffer + * @param start Position to start at + * @param numChars Number of characters to return, or 0 for the end of the string + */ +stock void CSubString(const char[] input, char[] output, int maxlen, int start, int numChars = 0) { + int i = 0; + for (;;) { + if (i == maxlen - 1 || i >= numChars || input[start + i] == '\0') { + output[i] = '\0'; + return; + } + + output[i] = input[start + i]; + i++; + } +} + +/** + * Converts a string to lowercase + * + * @param buffer String to convert + */ +stock void MC_StrToLower(char[] buffer) { + int len = strlen(buffer); + for (int i = 0; i < len; i++) { + buffer[i] = CharToLower(buffer[i]); + } +} + +/** + * Adds a color to the colors trie + * + * @param name Color name, without braces + * @param color Hexadecimal representation of the color (0xRRGGBB) + * @return True if color was added successfully, false if a color already exists with that name + */ +stock bool MC_AddColor(const char[] name, int color) { + MC_CheckTrie(); + + int value; + + if (MC_Trie.GetValue(name, value)) { + return false; + } + + char newName[64]; + strcopy(newName, sizeof(newName), name); + + MC_StrToLower(newName); + MC_Trie.SetValue(newName, color); + return true; +} + +/** + * Removes color tags from a message + * + * @param message Message to remove tags from + * @param maxlen Maximum buffer length + */ +stock void MC_RemoveTags(char[] message, int maxlen) { + MC_ReplaceColorCodes(message, 0, true, maxlen); +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param message Message (formatting rules) + */ +stock void MC_ReplyToCommand(int client, const char[] message, any ...) { + char buffer[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 3); + + if (client == 0) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToServer("%s", buffer); + } + + if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToConsole(client, "%s", buffer); + } + else { + MC_PrintToChat(client, "%s", buffer); + } +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param author Client to use for {teamcolor} + * @param message Message (formatting rules) + */ +stock void MC_ReplyToCommandEx(int client, int author, const char[] message, any ...) { + char buffer[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 4); + + if (client == 0) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToServer("%s", buffer); + } + + if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToConsole(client, "%s", buffer); + } + else { + MC_PrintToChatEx(client, author, "%s", buffer); + } +} + +/** + * Displays usage of an admin command to users depending on the + * setting of the sm_show_activity cvar. + * + * This version does not display a message to the originating client + * if used from chat triggers or menus. If manual replies are used + * for these cases, then this function will suffice. Otherwise, + * MC_ShowActivity2() is slightly more useful. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivity(int client, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char tag[] = "[SM] "; + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = id.HasFlag(Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 8) || ((value & 16) && is_root) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Same as MC_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing). + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) { + ThrowError("Client index %d is invalid", client); + } + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = id.HasFlag(Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 8) || ((value & 16) && is_root) || (i == client)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar. + * All users receive a message in their chat text, except for the originating client, + * who receives the message based on the current ReplySource. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivity2(int client, const char[] tag, const char[] format, any ...) { + if (sm_show_activity == null) { + sm_show_activity = FindConVar("sm_show_activity"); + } + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = sm_show_activity.IntValue; + // ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + + if (client != 0) { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) { + ThrowError("Client index %d is invalid", client); + } + + GetClientName(client, name, sizeof(name)); + + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + sign = "PLAYER"; + } + + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + /* We don't display directly to the console because the chat text + * simply gets added to the console, so we don't want it to print + * twice. + */ + MC_PrintToChatEx(client, client, "%s%s", tag, szBuffer); + } + else { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) { + return 1; + } + + for (int i = 1; i <= MaxClients; ++i) { + if (!IsClientInGame(i) || IsFakeClient(i) || i == client) { + continue; + } + + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) { + char newsign[MAX_NAME_LENGTH]; + + if ((value & 2)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else { + /* Treat this as an admin user */ + bool is_root = id.HasFlag(Admin_Root, Access_Effective); + if ((value & 4) || (value & 8) || ((value & 16) && is_root)) { + char newsign[MAX_NAME_LENGTH]; + + + if ((value & 8) || ((value & 16) && is_root)) { + newsign = name; + } + else { + newsign = sign; + } + + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Determines whether a color name exists + * + * @param color The color name to check + * @return True if the color exists, false otherwise + */ +stock bool CColorExists(const char[] color) { + MC_CheckTrie(); + int temp; + return MC_Trie.GetValue(color, temp); +} + +/** + * Returns the hexadecimal representation of a client's team color (will NOT initialize the trie) + * + * @param client Client to get the team color for + * @return Client's team color in hexadecimal, or green if unknown + * On error/Errors: If the client index passed is invalid or not in game. + */ +stock int CGetTeamColor(int client) { + if (client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + + if (!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + + int value; + switch(GetClientTeam(client)) { + case 1: { + value = MCOLOR_GRAY; + } + case 2: { + value = MCOLOR_RED; + } + case 3: { + value = MCOLOR_BLUE; + } + default: { + value = MCOLOR_GREEN; + } + } + + return value; +} + +stock StringMap MC_InitColorTrie() { + StringMap hTrie = new StringMap(); + hTrie.SetValue("aliceblue", 0xF0F8FF); + hTrie.SetValue("allies", 0x4D7942); // same as Allies team in DoD:S + hTrie.SetValue("ancient", 0xEB4B4B); // same as Ancient item rarity in Dota 2 + hTrie.SetValue("antiquewhite", 0xFAEBD7); + hTrie.SetValue("aqua", 0x00FFFF); + hTrie.SetValue("aquamarine", 0x7FFFD4); + hTrie.SetValue("arcana", 0xADE55C); // same as Arcana item rarity in Dota 2 + hTrie.SetValue("axis", 0xFF4040); // same as Axis team in DoD:S + hTrie.SetValue("azure", 0x007FFF); + hTrie.SetValue("beige", 0xF5F5DC); + hTrie.SetValue("bisque", 0xFFE4C4); + hTrie.SetValue("black", 0x000000); + hTrie.SetValue("blanchedalmond", 0xFFEBCD); + hTrie.SetValue("blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color + hTrie.SetValue("blueviolet", 0x8A2BE2); + hTrie.SetValue("brown", 0xA52A2A); + hTrie.SetValue("burlywood", 0xDEB887); + hTrie.SetValue("cadetblue", 0x5F9EA0); + hTrie.SetValue("chartreuse", 0x7FFF00); + hTrie.SetValue("chocolate", 0xD2691E); + hTrie.SetValue("collectors", 0xAA0000); // same as Collector's item quality in TF2 + hTrie.SetValue("common", 0xB0C3D9); // same as Common item rarity in Dota 2 + hTrie.SetValue("community", 0x70B04A); // same as Community item quality in TF2 + hTrie.SetValue("coral", 0xFF7F50); + hTrie.SetValue("cornflowerblue", 0x6495ED); + hTrie.SetValue("cornsilk", 0xFFF8DC); + hTrie.SetValue("corrupted", 0xA32C2E); // same as Corrupted item quality in Dota 2 + hTrie.SetValue("crimson", 0xDC143C); + hTrie.SetValue("cyan", 0x00FFFF); + hTrie.SetValue("darkblue", 0x00008B); + hTrie.SetValue("darkcyan", 0x008B8B); + hTrie.SetValue("darkgoldenrod", 0xB8860B); + hTrie.SetValue("darkgray", 0xA9A9A9); + hTrie.SetValue("darkgrey", 0xA9A9A9); + hTrie.SetValue("darkgreen", 0x006400); + hTrie.SetValue("darkkhaki", 0xBDB76B); + hTrie.SetValue("darkmagenta", 0x8B008B); + hTrie.SetValue("darkolivegreen", 0x556B2F); + hTrie.SetValue("darkorange", 0xFF8C00); + hTrie.SetValue("darkorchid", 0x9932CC); + hTrie.SetValue("darkred", 0x8B0000); + hTrie.SetValue("darksalmon", 0xE9967A); + hTrie.SetValue("darkseagreen", 0x8FBC8F); + hTrie.SetValue("darkslateblue", 0x483D8B); + hTrie.SetValue("darkslategray", 0x2F4F4F); + hTrie.SetValue("darkslategrey", 0x2F4F4F); + hTrie.SetValue("darkturquoise", 0x00CED1); + hTrie.SetValue("darkviolet", 0x9400D3); + hTrie.SetValue("deeppink", 0xFF1493); + hTrie.SetValue("deepskyblue", 0x00BFFF); + hTrie.SetValue("dimgray", 0x696969); + hTrie.SetValue("dimgrey", 0x696969); + hTrie.SetValue("dodgerblue", 0x1E90FF); + hTrie.SetValue("exalted", 0xCCCCCD); // same as Exalted item quality in Dota 2 + hTrie.SetValue("firebrick", 0xB22222); + hTrie.SetValue("floralwhite", 0xFFFAF0); + hTrie.SetValue("forestgreen", 0x228B22); + hTrie.SetValue("frozen", 0x4983B3); // same as Frozen item quality in Dota 2 + hTrie.SetValue("fuchsia", 0xFF00FF); + hTrie.SetValue("fullblue", 0x0000FF); + hTrie.SetValue("fullred", 0xFF0000); + hTrie.SetValue("gainsboro", 0xDCDCDC); + hTrie.SetValue("genuine", 0x4D7455); // same as Genuine item quality in TF2 + hTrie.SetValue("ghostwhite", 0xF8F8FF); + hTrie.SetValue("gold", 0xFFD700); + hTrie.SetValue("goldenrod", 0xDAA520); + hTrie.SetValue("gray", 0xCCCCCC); // same as spectator team color + hTrie.SetValue("grey", 0xCCCCCC); + hTrie.SetValue("green", 0x3EFF3E); + hTrie.SetValue("greenyellow", 0xADFF2F); + hTrie.SetValue("haunted", 0x38F3AB); // same as Haunted item quality in TF2 + hTrie.SetValue("honeydew", 0xF0FFF0); + hTrie.SetValue("hotpink", 0xFF69B4); + hTrie.SetValue("immortal", 0xE4AE33); // same as Immortal item rarity in Dota 2 + hTrie.SetValue("indianred", 0xCD5C5C); + hTrie.SetValue("indigo", 0x4B0082); + hTrie.SetValue("ivory", 0xFFFFF0); + hTrie.SetValue("khaki", 0xF0E68C); + hTrie.SetValue("lavender", 0xE6E6FA); + hTrie.SetValue("lavenderblush", 0xFFF0F5); + hTrie.SetValue("lawngreen", 0x7CFC00); + hTrie.SetValue("legendary", 0xD32CE6); // same as Legendary item rarity in Dota 2 + hTrie.SetValue("lemonchiffon", 0xFFFACD); + hTrie.SetValue("lightblue", 0xADD8E6); + hTrie.SetValue("lightcoral", 0xF08080); + hTrie.SetValue("lightcyan", 0xE0FFFF); + hTrie.SetValue("lightgoldenrodyellow", 0xFAFAD2); + hTrie.SetValue("lightgray", 0xD3D3D3); + hTrie.SetValue("lightgrey", 0xD3D3D3); + hTrie.SetValue("lightgreen", 0x99FF99); + hTrie.SetValue("lightpink", 0xFFB6C1); + hTrie.SetValue("lightsalmon", 0xFFA07A); + hTrie.SetValue("lightseagreen", 0x20B2AA); + hTrie.SetValue("lightskyblue", 0x87CEFA); + hTrie.SetValue("lightslategray", 0x778899); + hTrie.SetValue("lightslategrey", 0x778899); + hTrie.SetValue("lightsteelblue", 0xB0C4DE); + hTrie.SetValue("lightyellow", 0xFFFFE0); + hTrie.SetValue("lime", 0x00FF00); + hTrie.SetValue("limegreen", 0x32CD32); + hTrie.SetValue("linen", 0xFAF0E6); + hTrie.SetValue("magenta", 0xFF00FF); + hTrie.SetValue("maroon", 0x800000); + hTrie.SetValue("mediumaquamarine", 0x66CDAA); + hTrie.SetValue("mediumblue", 0x0000CD); + hTrie.SetValue("mediumorchid", 0xBA55D3); + hTrie.SetValue("mediumpurple", 0x9370D8); + hTrie.SetValue("mediumseagreen", 0x3CB371); + hTrie.SetValue("mediumslateblue", 0x7B68EE); + hTrie.SetValue("mediumspringgreen", 0x00FA9A); + hTrie.SetValue("mediumturquoise", 0x48D1CC); + hTrie.SetValue("mediumvioletred", 0xC71585); + hTrie.SetValue("midnightblue", 0x191970); + hTrie.SetValue("mintcream", 0xF5FFFA); + hTrie.SetValue("mistyrose", 0xFFE4E1); + hTrie.SetValue("moccasin", 0xFFE4B5); + hTrie.SetValue("mythical", 0x8847FF); // same as Mythical item rarity in Dota 2 + hTrie.SetValue("navajowhite", 0xFFDEAD); + hTrie.SetValue("navy", 0x000080); + hTrie.SetValue("normal", 0xB2B2B2); // same as Normal item quality in TF2 + hTrie.SetValue("oldlace", 0xFDF5E6); + hTrie.SetValue("olive", 0x9EC34F); + hTrie.SetValue("olivedrab", 0x6B8E23); + hTrie.SetValue("orange", 0xFFA500); + hTrie.SetValue("orangered", 0xFF4500); + hTrie.SetValue("orchid", 0xDA70D6); + hTrie.SetValue("palegoldenrod", 0xEEE8AA); + hTrie.SetValue("palegreen", 0x98FB98); + hTrie.SetValue("paleturquoise", 0xAFEEEE); + hTrie.SetValue("palevioletred", 0xD87093); + hTrie.SetValue("papayawhip", 0xFFEFD5); + hTrie.SetValue("peachpuff", 0xFFDAB9); + hTrie.SetValue("peru", 0xCD853F); + hTrie.SetValue("pink", 0xFFC0CB); + hTrie.SetValue("plum", 0xDDA0DD); + hTrie.SetValue("powderblue", 0xB0E0E6); + hTrie.SetValue("purple", 0x800080); + hTrie.SetValue("rare", 0x4B69FF); // same as Rare item rarity in Dota 2 + hTrie.SetValue("red", 0xFF4040); // same as RED/Terrorist team color + hTrie.SetValue("rosybrown", 0xBC8F8F); + hTrie.SetValue("royalblue", 0x4169E1); + hTrie.SetValue("saddlebrown", 0x8B4513); + hTrie.SetValue("salmon", 0xFA8072); + hTrie.SetValue("sandybrown", 0xF4A460); + hTrie.SetValue("seagreen", 0x2E8B57); + hTrie.SetValue("seashell", 0xFFF5EE); + hTrie.SetValue("selfmade", 0x70B04A); // same as Self-Made item quality in TF2 + hTrie.SetValue("sienna", 0xA0522D); + hTrie.SetValue("silver", 0xC0C0C0); + hTrie.SetValue("skyblue", 0x87CEEB); + hTrie.SetValue("slateblue", 0x6A5ACD); + hTrie.SetValue("slategray", 0x708090); + hTrie.SetValue("slategrey", 0x708090); + hTrie.SetValue("snow", 0xFFFAFA); + hTrie.SetValue("springgreen", 0x00FF7F); + hTrie.SetValue("steelblue", 0x4682B4); + hTrie.SetValue("strange", 0xCF6A32); // same as Strange item quality in TF2 + hTrie.SetValue("tan", 0xD2B48C); + hTrie.SetValue("teal", 0x008080); + hTrie.SetValue("thistle", 0xD8BFD8); + hTrie.SetValue("tomato", 0xFF6347); + hTrie.SetValue("turquoise", 0x40E0D0); + hTrie.SetValue("uncommon", 0xB0C3D9); // same as Uncommon item rarity in Dota 2 + hTrie.SetValue("unique", 0xFFD700); // same as Unique item quality in TF2 + hTrie.SetValue("unusual", 0x8650AC); // same as Unusual item quality in TF2 + hTrie.SetValue("valve", 0xA50F79); // same as Valve item quality in TF2 + hTrie.SetValue("vintage", 0x476291); // same as Vintage item quality in TF2 + hTrie.SetValue("violet", 0xEE82EE); + hTrie.SetValue("wheat", 0xF5DEB3); + hTrie.SetValue("white", 0xFFFFFF); + hTrie.SetValue("whitesmoke", 0xF5F5F5); + hTrie.SetValue("yellow", 0xFFFF00); + hTrie.SetValue("yellowgreen", 0x9ACD32); + + return hTrie; +} diff --git a/scripting/include/netprops.inc b/scripting/include/netprops.inc new file mode 100644 index 0000000..175a454 --- /dev/null +++ b/scripting/include/netprops.inc @@ -0,0 +1,127 @@ +#if defined _netprops_included_ + #endinput +#endif +#define _netprops_included_ + +enum SendPropType { + DPT_Int=0, + DPT_Float, + DPT_Vector, + DPT_VectorXY, + DPT_String, + DPT_Array, // An array of the base types (can't be of datatables). + DPT_DataTable, + DPT_NUMSendPropTypes +}; + +/** + * Returns a handle to the SendTable for a specific netclass. + * + * @param netclass netclass name. + * @return Handle to a SendTable or INVALID_HANDLE on error. + */ +native Handle:GetSendTableByNetclass(const String:netclass[]); + +/** + * Returns the amount of netprops a SendTable holds. + * This does not count recursively! + * + * @param hSendTable Handle to a SendTable object. + * @return Returns the number of netprops in the table. + */ +native GetNumProps(Handle:hSendTable); + +/** + * Returns a handle to a NetProp object at the given index of a SendTable. + * + * @param hSendTable Handle to a SendTable object. + * @param iIndex Position of the Netprop in the table. + * @return Handle to a NetProp object or INVALID_HANDLE on error. + */ +native Handle:GetProp(Handle:hSendTable, iIndex); + +/** + * Retrieves the table name from a SendTable + * + * @param hSendTable Handle to a SendTable object. + * @param sName Buffer to store the name in. + * @param size Maximum length of the sName buffer. + * @return String length of the returned name. + */ +native GetTableName(Handle:hSendTable, String:sName[], size); + +/** + * Retrieves the name of a NetProp Object + * + * @param hProp Handle to a NetProp object. + * @param sName Buffer to store the name in. + * @param size Maximum length of the sName buffer. + * @return String length of the returned name. + */ +native GetPropName(Handle:hProp, String:sName[], size); + +/** + * Returns a handle to the SendTable of a NetProp with type DPT_DataTable. + * + * @param hProp Handle to a NetProp object. + * @return Handle to a SendTable or INVALID_HANDLE on error. + */ +native Handle:GetDataTable(Handle:hProp); + +/** + * Retrieves the SendPropType of a NetProp object. + * + * @param hProp Handle to a NetProp object. + * @return SendPropType value of the NetProp object. + */ +native SendPropType:GetType(Handle:hProp); + +/** + * Retrieves the SendPropType of a NetProp object as a human readable string. + * + * @param hProp Handle to a NetProp object. + * @param sType Buffer to store the type in. + * @param size Maximum length of the sType buffer. + * @return String length of the returned type. + */ +native GetTypeString(Handle:hProp, String:sType[], size); + +/** + * Retrieves the number of bits a NetProp object has. + * + * @param hProp Handle to a NetProp object. + * @return The number of bits of the netprops + */ +native GetBits(Handle:hProp); + +/** + * Retrieves the actual offset of a NetProp object. + * This function will correctly compute nested offsets. + * There is no need to calculate offsets yourself. It uses the same + * method as FindSendPropInfo(). + * + * @param hProp Handle to a NetProp object. + * @return The offset of the netprop + */ +native GetOffset(Handle:hProp); + + + +/** + * Do not edit below this line! + */ +public Extension:__ext_netprops = +{ + name = "Netprops", + file = "netprops.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; \ No newline at end of file diff --git a/scripting/include/player_notes.inc b/scripting/include/player_notes.inc new file mode 100644 index 0000000..7e513dd --- /dev/null +++ b/scripting/include/player_notes.inc @@ -0,0 +1,13 @@ +#if defined _player_notes_included_ + #endinput +#endif +#define _player_notes_included_ + +void AddNote(int noteCreator, int noteTarget, const char[] message) { + char steamidCreator[32], steamidTarget[32]; + GetClientAuthId(noteCreator, AuthId_Steam2, steamidCreator, sizeof(steamidCreator)); + GetClientAuthId(noteTarget, AuthId_Steam2, steamidTarget, sizeof(steamidTarget)); + AddPlayerNoteIdentity(steamidCreator, steamidTarget, message); +} + +native void AddPlayerNoteIdentity(const char noteCreator[32], const char noteTarget[32], const char[] message); \ No newline at end of file diff --git a/scripting/include/prophunt/phcmds.inc b/scripting/include/prophunt/phcmds.inc new file mode 100644 index 0000000..3fd5e32 --- /dev/null +++ b/scripting/include/prophunt/phcmds.inc @@ -0,0 +1,363 @@ +#define GAMEMODE_PROP_NAME "phprop" +#define GAMEMODE_BLOCKER_NAME "phblocker" + + + +public Action Command_PropHunt(int client, int args) { + if(!isEnabled) ReplyToCommand(client, "Warn: %s is not active", GAMEMODE_NAME); + if(args > 0) { + char subcmd[32]; + GetCmdArg(1, subcmd, sizeof(subcmd)); + if(StrEqual(subcmd, "r") || StrEqual(subcmd, "reload", false)) { + GetCurrentMap(g_currentMap, sizeof(g_currentMap)); + char arg[4]; + GetCmdArg(2, arg, sizeof(arg)); + ReloadPropDB(); + if(ReloadMapDB()) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: Map has no config file"); + } + Game.Cleanup(true); + if(arg[0] == 'f') { + InitGamemode(); + } + SetupEntities(Game.Blockers, Game.Props); + ReplyToCommand(client, "Reloaded map from config"); + } else { + ReplyToCommand(client, "Error occurred while reloading map file"); + } + } else if(StrEqual(subcmd, "set", false)) { + char set[16]; + if(args == 1) { + ReplyToCommand(client, "Current Map Set: \"%s\" (Specify with /gw set )", g_currentSet); + if(validSets.Length == 0) ReplyToCommand(client, "Available Sets: (no map config found)"); + else { + ReplyToCommand(client, "Available Sets: "); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + ReplyToCommand(client, "%d. %s", i + 1, set); + } + } + } else { + GetCmdArg(2, g_currentSet, sizeof(g_currentSet)); + for(int i = 0; i < validSets.Length; i++) { + validSets.GetString(i, set, sizeof(set)); + if(StrEqual(set, g_currentSet)) { + if(!LoadConfigForMap(g_currentMap)) { + ReplyToCommand(client, "Warn: No config entry for %s", g_currentMap); + } + Game.Cleanup(); + SetupEntities(Game.Blockers, Game.Props); + PrintToChatAll("[PropHunt] Map set has been changed to \"%s\"", g_currentSet); + return Plugin_Handled; + } + } + ReplyToCommand(client, "Warning: Set was not found, use /gw r to force load."); + } + } else if(StrEqual(subcmd, "toggle")) { + char type[32]; + GetCmdArg(2, type, sizeof(type)); + bool doAll = StrEqual(type, "all"); + bool isUnknown = true; + + if(doAll || StrEqual(type, "blockers", false)) { + if(Game.Blockers) { + EntFire(GAMEMODE_BLOCKER_NAME, "Disable"); + ReplyToCommand(client, "Disabled all custom gamemode blockers"); + } else { + EntFire(GAMEMODE_BLOCKER_NAME, "Enable"); + ReplyToCommand(client, "Enabled all custom gamemode blockers"); + } + Game.Blockers = !Game.Blockers; + isUnknown = false; + } + if(doAll || StrEqual(type, "props", false)) { + if(Game.Props) { + EntFire(GAMEMODE_PROP_NAME, "Disable"); + EntFire(GAMEMODE_PROP_NAME, "DisableCollision"); + ReplyToCommand(client, "Disabled all custom gamemode props"); + } else { + EntFire(GAMEMODE_PROP_NAME, "Enable"); + EntFire(GAMEMODE_PROP_NAME, "EnableCollision"); + ReplyToCommand(client, "Enabled all custom gamemode props"); + } + Game.Props = !Game.Props; + isUnknown = false; + } + if(isUnknown) ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', or 'all'"); + } else if(StrEqual(subcmd, "clear", false)) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "all")) { + Game.Cleanup(); + ReplyToCommand(client, "Cleaned up everything."); + } else if(StrEqual(arg, "props")) { + EntFire(GAMEMODE_PROP_NAME, "kill"); + ReplyToCommand(client, "Removed all custom gamemode props"); + } else if(StrEqual(arg, "blockers")) { + EntFire(GAMEMODE_BLOCKER_NAME, "kill"); + ReplyToCommand(client, "Removed all custom gamemode blockers"); + } else ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', or 'all'"); + } else if(StrEqual(subcmd, "settime")) { + int prev = Game.MapTime; + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int time = StringToInt(arg); + mapConfig.mapTime = time; + Game.MapTime = time; + ReplyToCommand(client, "Map's time is temporarily set to %d seconds (was %d)", time, prev); + } else if(StrEqual(subcmd, "settick")) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + int tick = -StringToInt(arg); + Game.Tick = tick; + ReplyToCommand(client, "Set tick time to %d", tick); + } else if(StrContains(subcmd, "map") >= 0) { + static char arg[16]; + GetCmdArg(2, arg, sizeof(arg)); + if(StrEqual(arg, "list")) { + ReplyToCommand(client, "See the console for available maps"); + char map[64]; + for(int i = 0; i < validMaps.Length; i++) { + validMaps.GetString(i, map, sizeof(map)); + PrintToConsole(client, "%d. %s", i + 1, map); + } + } else if(StrEqual(arg, "random")) { + bool foundMap; + char map[64]; + do { + int mapIndex = GetURandomInt() % validMaps.Length; + validMaps.GetString(mapIndex, map, sizeof(map)); + if(!StrEqual(g_currentMap, map, false)) { + foundMap = true; + } + } while(!foundMap); + PrintToChatAll("%s Switching map to %s", GAMEMODE_PREFIX, map); + ChangeMap(map); + } else if(StrEqual(arg, "next", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change on the next round: 'next '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + strcopy(nextRoundMap, sizeof(nextRoundMap), arg2); + PrintToChatAll("%s Switching map next round to %s", GAMEMODE_PREFIX, arg2); + ForceChangeLevel(arg, "SetMapSelect"); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else if(StrEqual(arg, "force", false)) { + if(args == 1) { + ReplyToCommand(client, "Specify the map to change to: 'force '"); + } else { + char arg2[64]; + GetCmdArg(3, arg2, sizeof(arg2)); + if(IsMapValid(arg2)) { + PrintToChatAll("[H&S] Switching map to %s", arg2); + ChangeMap(arg2); + } else { + ReplyToCommand(client, "Map is not valid"); + } + } + } else { + ReplyToCommand(client, "Syntax: 'map /next >"); + } + return Plugin_Handled; + } else if(StrEqual(subcmd, "pos", false)) { + float pos[3]; + GetClientAbsOrigin(client, pos); + ReplyToCommand(client, "\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientEyeAngles(client, pos); + ReplyToCommand(client, "\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + } else if(StrEqual(subcmd, "prop", false)) { + float pos[3]; + GetClientAbsOrigin(client, pos); + ReplyToCommand(client, "\"MYPROP\""); + ReplyToCommand(client, "{"); + ReplyToCommand(client, "\t\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + GetClientAbsAngles(client, pos); + ReplyToCommand(client, "\t\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]); + ReplyToCommand(client, "\t\"type\" \"prop_dynamic\""); + ReplyToCommand(client, "\t\"model\" \"props_junk/dumpster_2.mdl\""); + ReplyToCommand(client, "}"); + } else if(StrEqual(subcmd, "setspawn", false)) { + GetClientAbsOrigin(client, mapConfig.spawnpoint); + ReplyToCommand(client, "Set map's temporarily spawnpoint to your location."); + } else if(StrEqual(subcmd, "stuck")) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + } else if(StrEqual(subcmd, "peekfix")) { + if(!PeekCam.Exists()) { + PeekCam.Target = client; + } + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + PeekCam.SetViewing(client, true); + PeekCam.SetViewing(client, false); + } + } + PeekCam.Destroy(); + ReplyToCommand(client, "Killing active camera"); + } else if(StrEqual(subcmd, "seeker")) { + if(args == 2) { + char arg1[32]; + GetCmdArg(2, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_list[0] <= 0){ + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + Game.SetSeeker(target_list[0], true); + ReplyToCommand(client, "Made %N a seeker", target_list[0]); + } else { + ReplyToCommand(client, "Specify a player to make a seeker"); + } + } else if(StrEqual(subcmd, "prop")) { + if(args == 2) { + char arg1[32]; + GetCmdArg(2, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_list[0] <= 0){ + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + Game.SetSeeker(target_list[0], false); + ReplyToCommand(client, "Made %N a prop", target_list[0]); + } else { + ReplyToCommand(client, "Specify a player to make a prop"); + } + } else if(StrEqual(subcmd, "debug")) { + ReplyToCommand(client, "- Game Info -"); + ReplyToCommand(client, "State: %d | Tick: %d", view_as(Game.State), Game.Tick); + + ReplyToCommand(client, "- Map Info -"); + ReplyToCommand(client, "Map: %s (set %s)", g_currentMap, g_currentSet); + if(mapConfig.hasSpawnpoint) + ReplyToCommand(client, "Has Spawnpoint: yes (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + else + ReplyToCommand(client, "Has Spawnpoint: no (possibly map spawn %f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + ReplyToCommand(client, "Map Time: %d", mapConfig.mapTime); + } else { + ReplyToCommand(client, "Unknown option. Leave blank for help"); + } + return Plugin_Handled; + } + ReplyToCommand(client, " === [ %s Commands ] ===", GAMEMODE_NAME); + if(GetUserAdmin(client) != INVALID_ADMIN_ID) { + ReplyToCommand(client, "- Dev Commands -"); + ReplyToCommand(client, "r/reload [force]: Reloads map config from file"); + ReplyToCommand(client, "toggle : Toggles all specified entities"); + ReplyToCommand(client, "clear : Clear all specified"); + ReplyToCommand(client, "settime [seconds]: Sets the time override for the map"); + ReplyToCommand(client, "settick [tick]: Sets the current tick timer value"); + ReplyToCommand(client, "- Admin Commands -"); + ReplyToCommand(client, "set [new set]: Change the prop set or view current"); + ReplyToCommand(client, "setspawn: Sets the temporary spawnpoint for the map"); + ReplyToCommand(client, "peekfix - Clear peek camera from all players"); + ReplyToCommand(client, "seeker [new seeker]: Get the active seeker, or set a new one."); + ReplyToCommand(client, "- User Commands -"); + } + ReplyToCommand(client, "stuck: Teleports you to spawn to unstuck yourself"); + return Plugin_Handled; +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) { + if(isEnabled) { + if(!StrEqual(command, "say")) { //Is team message + if(Game.IsSeeker(client)) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && Game.IsSeeker(i)) { + PrintToChat(i, "[Seekers] %N: %s", client, sArgs); + } + } + } else { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && !Game.IsSeeker(i)) { + PrintToChat(i, "[Hiders] %N: %s", client, sArgs); + } + } + } + return Plugin_Handled; + } + } + return Plugin_Continue; +} + + +public Action Command_Join(int client, int args) { + if(!isEnabled) return Plugin_Continue; + static float tpLoc[3]; + FindSpawnPosition(tpLoc); + if(args == 1) { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + 0, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(GetClientTeam(target) != 2) { + ChangeClientTeam(target, 2); + L4D_RespawnPlayer(target); + TeleportEntity(target, tpLoc, NULL_VECTOR, NULL_VECTOR); + isPendingPlay[client] = false; + CheatCommand(target, "give", "knife"); + } + } + ReplyToCommand(client, "Joined %s", target_name); + } else { + if(Game.IsSeeker(client)) { + ReplyToCommand(client, "You are already in-game as a seeker."); + return Plugin_Handled; + } + isPendingPlay[client] = false; + ChangeClientTeam(client, 2); + L4D_RespawnPlayer(client); + TeleportEntity(client, tpLoc, NULL_VECTOR, NULL_VECTOR); + Game.SetupPlayer(client); + if(!ArePlayersJoining()) { + InitGamemode(); + } + } + return Plugin_Handled; +} diff --git a/scripting/include/prophunt/phcore.inc b/scripting/include/prophunt/phcore.inc new file mode 100644 index 0000000..3302f47 --- /dev/null +++ b/scripting/include/prophunt/phcore.inc @@ -0,0 +1,202 @@ +#define FOLDER_PERMS ( FPERM_U_READ | FPERM_U_WRITE | FPERM_U_EXEC | FPERM_G_EXEC | FPERM_G_WRITE | FPERM_G_READ | FPERM_O_EXEC ) + +#include +#include +#include +#include + + +static KeyValues mapsKv; +StringMap mapConfigs; + +bool ReloadMapDB() { + if(mapsKv != null) { + delete mapsKv; + } + mapsKv = new KeyValues("prophunt"); + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/prophunt"); + CreateDirectory(sPath, FOLDER_PERMS); + Format(sPath, sizeof(sPath), "%s/maps.cfg", sPath); + + if(!FileExists(sPath) || !mapsKv.ImportFromFile(sPath)) { + delete mapsKv; + return false; + } + + validMaps.Clear(); + + char map[64]; + mapsKv.GotoFirstSubKey(true); + do { + mapsKv.GetSectionName(map, sizeof(map)); + validMaps.PushString(map); + } while(mapsKv.GotoNextKey(true)); + mapsKv.GoBack(); + + PrintToServer("[PropHunt] Loaded %d map configs", validMaps.Length); + return true; +} + +bool ReloadPropDB() { + if(propHealths != null) + delete propHealths; + propHealths = new StringMap(); + KeyValues propKv = new KeyValues("props"); + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), "data/prophunt"); + CreateDirectory(sPath, FOLDER_PERMS); + Format(sPath, sizeof(sPath), "%s/props.cfg", sPath); + + if(!FileExists(sPath) || !propKv.ImportFromFile(sPath)) { + delete propKv; + return false; + } + + char model[64]; + propKv.GotoFirstSubKey(false); + do { + propKv.GetSectionName(model, sizeof(model)); + propHealths.SetValue(model, propKv.GetNum(NULL_STRING)); + } while(propKv.GotoNextKey(false)); + + PrintToServer("[PropHunt] Loaded %d models", propHealths.Size); + + delete propKv; + return true; +} + +static float DEFAULT_SCALE[3] = { 5.0, 5.0, 5.0 }; + +bool LoadConfigForMap(const char[] map) { + mapsKv.Rewind(); + if (mapsKv.JumpToKey(map)) { + MapConfig config; + config.entities = new ArrayList(sizeof(EntityConfig)); + config.inputs = new ArrayList(ByteCountToCells(64)); + validSets.Clear(); + + static char buffer[64]; + buffer[0] = '\0'; + if(StrEqual(g_currentSet, "default") && mapsKv.GetString("defaultset", buffer, sizeof(buffer)) && buffer[0] != '\0') { + strcopy(g_currentSet, sizeof(g_currentSet), buffer); + } + PrintToServer("[PropHunt] Loading config data for set %s on %s", g_currentSet, map); + + if(mapsKv.JumpToKey("props")) { + mapsKv.GotoFirstSubKey(); + do { + EntityConfig entCfg; + mapsKv.GetVector("origin", entCfg.origin, NULL_VECTOR); + mapsKv.GetVector("rotation", entCfg.rotation, NULL_VECTOR); + mapsKv.GetString("type", entCfg.type, sizeof(entCfg.type), "prop_dynamic"); + mapsKv.GetString("model", entCfg.model, sizeof(entCfg.model), ""); + if(entCfg.model[0] != '\0') + Format(entCfg.model, sizeof(entCfg.model), "models/%s", entCfg.model); + mapsKv.GetVector("scale", entCfg.scale, DEFAULT_SCALE); + mapsKv.GetVector("offset", entCfg.offset, NULL_VECTOR); + mapsKv.GetString("set", buffer, sizeof(buffer), "default"); + if(validSets.FindString(buffer) == -1) { + validSets.PushString(buffer); + } + if(StrEqual(buffer, "default") || StrEqual(g_currentSet, buffer, false)) { + + config.entities.PushArray(entCfg); + } else { + mapsKv.GetSectionName(buffer, sizeof(buffer)); + PrintToServer("Skipping %s", buffer); + } + } while (mapsKv.GotoNextKey()); + // JumpToKey and GotoFirstSubKey both traverse, i guess, go back + mapsKv.GoBack(); + mapsKv.GoBack(); + } + if(mapsKv.JumpToKey("inputs")) { + mapsKv.GotoFirstSubKey(false); + do { + mapsKv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + mapsKv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (mapsKv.GotoNextKey(false)); + mapsKv.GoBack(); + mapsKv.GoBack(); + } + int mapTime; + + config.hasSpawnpoint = false; + config.canClimb = true; + config.pressButtons = true; + if(!StrEqual(g_currentSet, "default") && mapsKv.JumpToKey("sets")) { + char set[16]; + mapsKv.GotoFirstSubKey(true); + do { + mapsKv.GetSectionName(set, sizeof(set)); + if(validSets.FindString(set) == -1) { + validSets.PushString(set); + } + if(StrEqual(g_currentSet, set, false)) { + mapsKv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[PropHunt] Using provided custom spawnpoint for set %s at %0.1f, %0.1f, %0.1f", g_currentSet, config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } + mapTime = mapsKv.GetNum("maptime", 0); + if(mapsKv.JumpToKey("inputs")) { + mapsKv.GotoFirstSubKey(false); + do { + mapsKv.GetSectionName(buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + + mapsKv.GetString(NULL_STRING, buffer, sizeof(buffer)); + config.inputs.PushString(buffer); + } while (mapsKv.GotoNextKey(false)); + mapsKv.GoBack(); + mapsKv.GoBack(); + } + break; + } + + } while(mapsKv.GotoNextKey(true)); + mapsKv.GoBack(); + mapsKv.GoBack(); + } + + if(!config.hasSpawnpoint) { + mapsKv.GetVector("spawnpoint", config.spawnpoint); + if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) { + PrintToServer("[PropHunt] Using provided custom spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else if (FindSpawnPosition(config.spawnpoint, false)) { + PrintToServer("[PropHunt] Using map spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]); + config.hasSpawnpoint = true; + } else { + PrintToServer("[PropHunt] Could not find any spawnpoints, using default spawn"); + config.hasSpawnpoint = false; + } + } + + // Use default maptime if exists + if(mapTime == 0) + mapTime = mapsKv.GetNum("maptime", 0); + if(mapTime > 0) { + config.mapTime = mapTime; + PrintToServer("[PropHunt] Map time overwritten to %d seconds", mapTime); + } + + mapConfigs.SetArray(map, config, sizeof(MapConfig)); + // Discard entInputs if unused + if(config.inputs.Length == 0) { + delete config.inputs; + } + mapConfig = config; + return true; + } else { + mapConfig.hasSpawnpoint = false; + PrintToServer("[PropHunt] %s has no config entry", map); + return false; + } +} \ No newline at end of file diff --git a/scripting/include/prophunt/phents.inc b/scripting/include/prophunt/phents.inc new file mode 100644 index 0000000..05b7b51 --- /dev/null +++ b/scripting/include/prophunt/phents.inc @@ -0,0 +1,99 @@ +#define ENT_PROP_NAME "gwprop" +#define ENT_BLOCKER_NAME "gwblocker" +#define ENT_PORTAL_NAME "gwportal" +#define ENT_ENV_NAME "gwenv" +#include + +stock void CheatCommand(int client, const char[] command, const char[] argument1) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", command, argument1); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} + + +stock void EntFire(const char[] name, const char[] input) { + static char targetname[64]; + static char cmd[32]; + #if defined DEBUG_LOG_MAPSTART + PrintToServer("EntFire: %s \"%s\"", name, input); + #endif + int len = SplitString(input, " ", cmd, sizeof(cmd)); + if(len > -1) SetVariantString(input[len]); + + int hammerId = name[0] == '!' ? StringToInt(name[1]) : 0; + for(int i = MaxClients + 1; i <= 4096; i++) { + if(IsValidEntity(i) && (IsValidEdict(i) || EntIndexToEntRef(i) != -1)) { + if(hammerId > 0) { + if(hammerId == Entity_GetHammerId(i)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } else { + GetEntPropString(i, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + + } else { + GetEntityClassname(i, targetname, sizeof(targetname)); + if(StrEqual(targetname, name, false)) { + if(len > -1) AcceptEntityInput(i, cmd); + else AcceptEntityInput(i, input); + } + } + } + } + } +} + + + +void SetupEntities(bool blockers = true, bool props = true) { + #if defined DEBUG_BLOCKERS + if(mapConfig.hasSpawnpoint) { + PrecacheModel("survivors/survivor_teenangst.mdl", true); + int dummy = CreateDummy("models/survivors/survivor_teenangst.mdl", "idle", mapConfig.spawnpoint, NULL_VECTOR); + SetEntProp(dummy, Prop_Data, "m_nSolidType", 0); + SetEntProp(dummy, Prop_Send, "m_CollisionGroup", 0); + SetEntProp(dummy, Prop_Send, "movetype", MOVETYPE_NONE); + } + EntFire("info_changelevel", "Kill"); + #endif + if(mapConfig.entities != null) { + PrintToServer("[PropHunt] Deploying %d custom entities (Set: %s) (blockers:%b props:%b)", mapConfig.entities.Length, g_currentSet, blockers, props); + for(int i = 0; i < mapConfig.entities.Length; i++) { + EntityConfig config; + mapConfig.entities.GetArray(i, config); + + if(config.model[0] != '\0') PrecacheModel(config.model); + + if(StrEqual(config.type, "env_physics_blocker")) { + if(blockers && CreateEnvBlockerScaled(config.type, config.origin, config.scale, isNavBlockersEnabled) == -1) { + Game.Warn("Failed to spawn blocker [type=%s] at (%.1f,%.1f, %.1f)", config.type, config.origin[0], config.origin[1], config.origin[2]); + } + } else if(StrEqual(config.type, "env_fire")) { + if(props && CreateFire(config.origin, config.scale[0], config.scale[1], config.scale[2]) == -1) { + Game.Warn("Failed to spawn env_fire at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]); + } + } else if(props) { + if(CreateProp(config.type, config.model, config.origin, config.rotation) == -1) { + Game.Warn("Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]); + } + } + } + + static char key[64]; + static char value[64]; + if(mapConfig.inputs != null) { + for(int i = 0; i < mapConfig.inputs.Length - 1; i += 2) { + mapConfig.inputs.GetString(i, key, sizeof(key)); + mapConfig.inputs.GetString(i + 1, value, sizeof(value)); + EntFire(key, value); + } + } + } +} diff --git a/scripting/include/prophunt/phgame.inc b/scripting/include/prophunt/phgame.inc new file mode 100644 index 0000000..4c2da18 --- /dev/null +++ b/scripting/include/prophunt/phgame.inc @@ -0,0 +1,385 @@ +static int mapChangeMsgTicks = 5; + +int GetColorInt(int r, int g, int b) { + int color = r; + color += 256 * g; + color += 65536 * b; + return color; +} + +Action Timer_ChangeMap(Handle h) { + PrintToChatAll("Changing map to %s in %d seconds", nextRoundMap, mapChangeMsgTicks); + if(mapChangeMsgTicks-- == 0) { + ForceChangeLevel(nextRoundMap, "GuessWhoMapSelect"); + nextRoundMap[0] = '\0'; + return Plugin_Stop; + } + return Plugin_Continue; +} + +void ChangeMap(const char map[64], int time = 5) { + strcopy(nextRoundMap, sizeof(nextRoundMap), map); + mapChangeMsgTicks = time; + CreateTimer(1.0, Timer_ChangeMap, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); +} + +bool FindSpawnPosition(float pos[3], bool includePlayers = true) { + if(includePlayers) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + GetClientAbsOrigin(i, pos); + return true; + } + } + } + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "info_player_start")) != INVALID_ENT_REFERENCE) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + return true; + } + return false; +} + +static char buffer[128]; + + +methodmap PropHuntGame < BaseGame { + + property int SeekersCount { + public get() { + int count = 0; + for(int i = 1; i <= MaxClients; i++) { + if(isSeeker[i]) count++; + } + return count; + } + } + property int PropsCount { + public get() { + int count = 0; + for(int i = 1; i <= MaxClients; i++) { + if(!isSeeker[i]) count++; + } + return count; + } + } + + public bool IsSeeker(int client) { + return isSeeker[client]; + } + + public bool SetSeeker(int client, bool value) { + isSeeker[client] = value; + hasBeenSeeker[client] = true; + DispatchKeyValue(client, "rendercolor", value ? WHITE : TRANSPARENT); + return true; + } + + public void ClearSeekers() { + for(int i = 1; i <= MaxClients; i++) { + isSeeker[i] = false; + } + } + + property int Tick { + public get() { + if(!isEnabled) return -1; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.Tick", buffer, sizeof(buffer)); + int value = -1; + if(StringToIntEx(buffer, value) > 0) { + return value; + } else { + return -1; + } + } + public set(int tick) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.Tick = %d", tick); + L4D2_ExecVScriptCode(buffer); + } + } + + property GameState State { + public get() { + if(!isEnabled) return State_Unknown; + L4D2_GetVScriptOutput("g_ModeScript.MutationState.State", buffer, sizeof(buffer)); + int stage = 0; + if(StringToIntEx(buffer, stage) > 0) { + return view_as(stage); + } else { + return State_Unknown; + } + } + public set(GameState state) { + if(isEnabled) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.State = %d", view_as(state)); + L4D2_ExecVScriptCode(buffer); + } + } + } + + property int MapTime { + public get() { + L4D2_GetVScriptOutput("g_ModeScript.MutationState.MaxTime", buffer, sizeof(buffer)); + return StringToInt(buffer); + } + public set(int seconds) { + Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.MaxTime = %d", seconds); + L4D2_ExecVScriptCode(buffer); + if(timesUpTimer != null) { + float remaining = float(seconds) - float(this.Tick); + delete timesUpTimer; + timesUpTimer = CreateTimer(remaining, Timer_TimesUp, _, TIMER_FLAG_NO_MAPCHANGE); + } + } + } + + public void Start() { + + } + + public void End(GameState state) { + this.State = state; + CreateTimer(5.0, Timer_ResetAll); + } + + public void Cleanup(bool noClearInv = false) { + DeleteCustomEnts(); + } + + public bool TeleportToSpawn(int client) { + if(mapConfig.hasSpawnpoint) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + return true; + } else { + float pos[3]; + if(FindSpawnPosition(pos)) { + return false; + } + TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR); + } + return false; + } + + public void TeleportAllToStart() { + if(mapConfig.hasSpawnpoint) { + PrintToServer("[GuessWho] Teleporting all players to provided spawnpoint (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + this.TeleportToSpawn(i); + } + } + } else { + PrintToServer("[GuessWho] Warn: No spawnpoint found (provided or map spawn)"); + } + } + + // Ignores seeker + property int PropsAlive { + public get() { + int amount = 0; + for(int i = 1; i <= MaxClients; i++) { + if(!isSeeker[i] && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) > 1 && IsPlayerAlive(i) && !IsFakeClient(i)) { + amount++; + } + } + return amount; + } + } + property int SeekersAlive { + public get() { + int amount = 0; + for(int i = 1; i <= MaxClients; i++) { + if(!isSeeker[i] && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) > 1 && IsPlayerAlive(i) && !IsFakeClient(i)) { + amount++; + } + } + return amount; + } + } + + public void SetupProp(int client, int prop) { + if(!IsValidEntity(prop)) { + ThrowError("Invalid prop (id %d)", prop); + return; + } + if(propData[client].prop > 0 && IsValidEntity(propData[client].prop)) { + AcceptEntityInput(propData[client].prop, "Kill"); + } + static char model[64]; + GetEntPropString(prop, Prop_Data, "m_ModelName", model, sizeof(model)); + PrintToConsole(client, "Setup prop model: %s", model); + + int health = 1; + if(!propHealths.GetValue(model[7], health)) { + PrintToServer("[PropHunt] Missing health for model: %s", model[7]); + } + float mins[3]; + GetEntPropVector(prop, Prop_Data, "m_vecMins", mins); + propData[client].verticalOffset = -mins[2]; + SetEntProp(client, Prop_Send, "m_iHealth", health); + propData[client].prop = prop; + DispatchKeyValue(client, "rendercolor", TRANSPARENT); + SDKHook(client, SDKHook_SetTransmit, OnPlayerTransmit); + } + + public void SetupRandomProp(int client) { + int propIndex = GetURandomInt() % MAX_VALID_MODELS; + int prop = CreatePropInternal(VALID_MODELS[propIndex]); + this.SetupProp(client, prop); + } + + public void SetupPropTeam(int client) { + DispatchKeyValue(client, "rendercolor", TRANSPARENT); + SDKHook(client, SDKHook_SetTransmit, OnPlayerTransmit); + this.SetupRandomProp(client); + } + + public void SetupSeekerTeam(int client) { + CheatCommand(client, "give", "smg"); + } + + public void SetupPlayer(int client) { + ClearInventory(client); + + ChangeClientTeam(client, 2); + SetEntProp(client, Prop_Send, "m_survivorCharacter", GetURandomInt() % 7); + SDKHook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + } + + public void UnsetupPlayer(int client) { + DispatchKeyValue(client, "rendercolor", WHITE); + SDKUnhook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + hasBeenSeeker[client] = false; + isSeeker[client] = false; + SDKUnhook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + SetPlayerBlind(client, 0); + SetEntPropFloat(client, Prop_Send, "m_flLaggedMovementValue", 1.0); + } +} + +stock bool ArePlayersJoining() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsClientInGame(i)) { + return true; + } + } + return false; +} + +stock void GetHorizontalPositionFromClient(int client, float units, float finalPosition[3]) { + float pos[3], ang[3]; + GetClientEyeAngles(client, ang); + GetClientAbsOrigin(client, pos); + + float theta = DegToRad(ang[1]); + pos[0] += units * Cosine(theta); + pos[1] += units * Sine(theta); + finalPosition = pos; +} + +stock void GetAnglesLookAt(int iClient, int iTarget, float fFinalPos[3]) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + + GetEntPropVector(iClient, Prop_Send, "m_vecOrigin", fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + // TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} +stock void AddInFrontOf(const float fVecOrigin[3], const float fVecAngle[3], float fUnits, float fOutPut[3]) +{ + float fVecView[3]; GetViewVector(fVecAngle, fVecView); + + fOutPut[0] = fVecView[0] * fUnits + fVecOrigin[0]; + fOutPut[1] = fVecView[1] * fUnits + fVecOrigin[1]; + fOutPut[2] = fVecView[2] * fUnits + fVecOrigin[2]; +} +stock void GetViewVector(const float fVecAngle[3], float fOutPut[3]) +{ + fOutPut[0] = Cosine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[1] = Sine(fVecAngle[1] / (180 / FLOAT_PI)); + fOutPut[2] = -Sine(fVecAngle[0] / (180 / FLOAT_PI)); +} + +stock void LookAtClient(int iClient, int iTarget) { + static float fTargetPos[3]; + static float fTargetAngles[3]; + static float fClientPos[3]; + static float fFinalPos[3]; + + GetClientEyePosition(iClient, fClientPos); + GetClientEyePosition(iTarget, fTargetPos); + GetClientEyeAngles(iTarget, fTargetAngles); + + float fVecFinal[3]; + AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} + +stock void LookAtPoint(int client, const float targetPos[3]) { + static float targetAngles[3]; + static float clientPos[3]; + static float fFinalPos[3]; + + GetClientEyePosition(client, clientPos); + GetClientEyeAngles(client, targetAngles); + + float fVecFinal[3]; + AddInFrontOf(targetPos, targetAngles, 7.0, fVecFinal); + MakeVectorFromPoints(clientPos, fVecFinal, fFinalPos); + + GetVectorAngles(fFinalPos, fFinalPos); + + TeleportEntity(client, NULL_VECTOR, fFinalPos, NULL_VECTOR); +} + + +void SetPlayerBlind(int target, int amount) { + int targets[1]; + targets[0] = target; + + int duration = 1536; + int holdtime = 1536; + int flags = (amount == 0) ? (0x0001 | 0x0010) : (0x0002 | 0x0008); + int color[4] = { 0, 0, 0, 0 }; + color[3] = amount; + + Handle message = StartMessageEx(g_FadeUserMsgId, targets, 1); + BfWrite bf = UserMessageToBfWrite(message); + bf.WriteShort(duration); + bf.WriteShort(holdtime); + bf.WriteShort(flags); + bf.WriteByte(color[0]); + bf.WriteByte(color[1]); + bf.WriteByte(color[2]); + bf.WriteByte(color[3]); + EndMessage(); +} + +#define HIDER_DISTANCE_MAX_SIZE 10 + + +#define MAX_AUTO_VOCALIZATIONS 9 +static char AUTO_VOCALIZATIONS[MAX_AUTO_VOCALIZATIONS][] = { + "PlayerLaugh", + "PlayerSpotPill", + "Playerlookout", + "EatPills", + "ReviveMeInterrupted", + "PlayerIncapacitated", + "PlayerNiceShot", + "ResponseSoftDispleasureSwear", + "PlayerAreaClear" +}; diff --git a/scripting/include/prophunt/phtimers.inc b/scripting/include/prophunt/phtimers.inc new file mode 100644 index 0000000..e489886 --- /dev/null +++ b/scripting/include/prophunt/phtimers.inc @@ -0,0 +1,48 @@ +Action Timer_WaitForPlayers(Handle h) { + if(!isEnabled) return Plugin_Stop; + if(!ArePlayersJoining()) { + Game.Debug("No players pending, ready to go"); + if(!firstCheckDone) { + // Wait one more iteration + firstCheckDone = true; + } else { + firstCheckDone = false; + InitGamemode(); + return Plugin_Stop; + } + } + Game.Debug("Waiting for players"); + return Plugin_Continue; +} + + +Action Timer_StartGame(Handle h) { + Game.State = State_Active; + Game.MapTime = DEFAULT_GAME_TIME; + Game.Tick = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(Game.IsSeeker(i)) { + Game.SetupSeekerTeam(i); + } + SetPlayerBlind(i, 0); + SetEntPropFloat(i, Prop_Send, "m_flLaggedMovementValue", 1.0); + } + } + Game.Broadcast("Get ready here they come"); + return Plugin_Continue; +} + +Action Timer_TimesUp(Handle h) { + Game.End(State_PropsWin); + return Plugin_Continue; +} + +Action Timer_ResetAll(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + ForcePlayerSuicide(i); + } + } + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/include/ripext.inc b/scripting/include/ripext.inc new file mode 100644 index 0000000..9fc02e3 --- /dev/null +++ b/scripting/include/ripext.inc @@ -0,0 +1,26 @@ +#if defined _ripext_included_ + #endinput +#endif +#define _ripext_included_ + +#include +#include + +/** + * Do not edit below this line! + */ +public Extension __ext_rip = +{ + name = "REST in Pawn", + file = "rip.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; diff --git a/scripting/include/ripext/http.inc b/scripting/include/ripext/http.inc new file mode 100644 index 0000000..3122f22 --- /dev/null +++ b/scripting/include/ripext/http.inc @@ -0,0 +1,359 @@ +enum HTTPStatus +{ + HTTPStatus_Invalid = 0, + + // 1xx Informational + HTTPStatus_Continue = 100, + HTTPStatus_SwitchingProtocols = 101, + + // 2xx Success + HTTPStatus_OK = 200, + HTTPStatus_Created = 201, + HTTPStatus_Accepted = 202, + HTTPStatus_NonAuthoritativeInformation = 203, + HTTPStatus_NoContent = 204, + HTTPStatus_ResetContent = 205, + HTTPStatus_PartialContent = 206, + + // 3xx Redirection + HTTPStatus_MultipleChoices = 300, + HTTPStatus_MovedPermanently = 301, + HTTPStatus_Found = 302, + HTTPStatus_SeeOther = 303, + HTTPStatus_NotModified = 304, + HTTPStatus_UseProxy = 305, + HTTPStatus_TemporaryRedirect = 307, + HTTPStatus_PermanentRedirect = 308, + + // 4xx Client Error + HTTPStatus_BadRequest = 400, + HTTPStatus_Unauthorized = 401, + HTTPStatus_PaymentRequired = 402, + HTTPStatus_Forbidden = 403, + HTTPStatus_NotFound = 404, + HTTPStatus_MethodNotAllowed = 405, + HTTPStatus_NotAcceptable = 406, + HTTPStatus_ProxyAuthenticationRequired = 407, + HTTPStatus_RequestTimeout = 408, + HTTPStatus_Conflict = 409, + HTTPStatus_Gone = 410, + HTTPStatus_LengthRequired = 411, + HTTPStatus_PreconditionFailed = 412, + HTTPStatus_RequestEntityTooLarge = 413, + HTTPStatus_RequestURITooLong = 414, + HTTPStatus_UnsupportedMediaType = 415, + HTTPStatus_RequestedRangeNotSatisfiable = 416, + HTTPStatus_ExpectationFailed = 417, + HTTPStatus_MisdirectedRequest = 421, + HTTPStatus_TooEarly = 425, + HTTPStatus_UpgradeRequired = 426, + HTTPStatus_PreconditionRequired = 428, + HTTPStatus_TooManyRequests = 429, + HTTPStatus_RequestHeaderFieldsTooLarge = 431, + HTTPStatus_UnavailableForLegalReasons = 451, + + // 5xx Server Error + HTTPStatus_InternalServerError = 500, + HTTPStatus_NotImplemented = 501, + HTTPStatus_BadGateway = 502, + HTTPStatus_ServiceUnavailable = 503, + HTTPStatus_GatewayTimeout = 504, + HTTPStatus_HTTPVersionNotSupported = 505, + HTTPStatus_VariantAlsoNegotiates = 506, + HTTPStatus_NotExtended = 510, + HTTPStatus_NetworkAuthenticationRequired = 511, +}; + +typeset HTTPRequestCallback +{ + function void (HTTPResponse response, any value); + function void (HTTPResponse response, any value, const char[] error); +}; + +typeset HTTPFileCallback +{ + function void (HTTPStatus status, any value); + function void (HTTPStatus status, any value, const char[] error); +}; + +methodmap HTTPRequest < Handle +{ + // Creates an HTTP request. + // + // The Handle is automatically freed when the request is performed. + // Otherwise, the Handle must be freed via delete or CloseHandle(). + // + // @param url URL to the REST API endpoint. + public native HTTPRequest(const char[] url); + + // Appends a parameter to the form data. + // + // The parameter name and value are encoded according to RFC 3986. + // + // @param name Parameter name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void AppendFormParam(const char[] name, const char[] format, any ...); + + // Appends a query parameter to the URL. + // + // The parameter name and value are encoded according to RFC 3986. + // + // @param name Parameter name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void AppendQueryParam(const char[] name, const char[] format, any ...); + + // Sets the credentials for HTTP Basic authentication. + // + // @param username Username to use. + // @param password Password to use. + public native void SetBasicAuth(const char[] username, const char[] password); + + // Sets an HTTP header. + // + // @param name Header name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void SetHeader(const char[] name, const char[] format, any ...); + + // Performs an HTTP GET request. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Get(HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP POST request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Post(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PUT request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Put(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PATCH request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Patch(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP DELETE request. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Delete(HTTPRequestCallback callback, any value = 0); + + // Downloads a file. + // + // This function closes the request Handle after completing. + // + // @param path File path to write to. + // @param callback A function to use as a callback when the download has finished. + // @param value Optional value to pass to the callback function. + public native void DownloadFile(const char[] path, HTTPFileCallback callback, any value = 0); + + // Uploads a file. + // + // This function performs an HTTP PUT request. The file contents are sent in the request body. + // This function closes the request Handle after completing. + // + // @param path File path to read from. + // @param callback A function to use as a callback when the upload has finished. + // @param value Optional value to pass to the callback function. + public native void UploadFile(const char[] path, HTTPFileCallback callback, any value = 0); + + // Performs an HTTP POST request with form data. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void PostForm(HTTPRequestCallback callback, any value = 0); + + // Connect timeout in seconds. Defaults to 10. + property int ConnectTimeout { + public native get(); + public native set(int connectTimeout); + } + + // Maximum number of redirects to follow. Defaults to 5. + property int MaxRedirects { + public native get(); + public native set(int maxRedirects); + } + + // Maximum download speed in bytes per second. Defaults to unlimited speed. + property int MaxRecvSpeed { + public native get(); + public native set(int maxSpeed); + } + + // Maximum upload speed in bytes per second. Defaults to unlimited speed. + property int MaxSendSpeed { + public native get(); + public native set(int maxSpeed); + } + + // Timeout in seconds. Defaults to 30. + property int Timeout { + public native get(); + public native set(int timeout); + } +} + +methodmap HTTPResponse +{ + // Retrieves an HTTP header from the response. + // + // @param name Header name. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if the header was not found. + public native bool GetHeader(const char[] name, char[] buffer, int maxlength); + + // Retrieves the JSON data of the response. + // + // @error Invalid JSON response. + property JSON Data { + public native get(); + } + + // Retrieves the HTTP status of the response. + property HTTPStatus Status { + public native get(); + } +}; + +// Deprecated. Use HTTPRequest instead. +methodmap HTTPClient < Handle +{ + // Creates an HTTP client. + // + // The HTTPClient must be freed via delete or CloseHandle(). + // + // @param baseURL Base URL to the REST API. + #pragma deprecated Use HTTPRequest instead. + public native HTTPClient(const char[] baseURL); + + // Sets an HTTP header to be used for all requests. + // + // @param name Header name. + // @param value String value to set. + #pragma deprecated Use HTTPRequest.SetHeader() instead. + public native void SetHeader(const char[] name, const char[] value); + + // Performs an HTTP GET request. + // + // @param endpoint API endpoint to request. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Get() instead. + public native void Get(const char[] endpoint, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP POST request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Post() instead. + public native void Post(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PUT request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Put() instead. + public native void Put(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PATCH request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Patch() instead. + public native void Patch(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP DELETE request. + // + // @param endpoint API endpoint to request. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Delete() instead. + public native void Delete(const char[] endpoint, HTTPRequestCallback callback, any value = 0); + + // Downloads a file. + // + // @param endpoint API endpoint to download from. + // @param path File path to write to. + // @param callback A function to use as a callback when the download has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.DownloadFile() instead. + public native void DownloadFile(const char[] endpoint, const char[] path, HTTPFileCallback callback, any value = 0); + + // Uploads a file. + // + // This function performs an HTTP PUT request. The file contents are sent in the request body. + // + // @param endpoint API endpoint to upload to. + // @param path File path to read from. + // @param callback A function to use as a callback when the upload has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.UploadFile() instead. + public native void UploadFile(const char[] endpoint, const char[] path, HTTPFileCallback callback, any value = 0); + + // Connect timeout in seconds. Defaults to 10. + #pragma deprecated Use HTTPRequest.ConnectTimeout instead. + property int ConnectTimeout { + public native get(); + public native set(int connectTimeout); + } + + // Follow HTTP 3xx redirects. Defaults to true. + #pragma deprecated Use HTTPRequest.MaxRedirects instead. + property bool FollowLocation { + public native get(); + public native set(bool followLocation); + } + + // Timeout in seconds. Defaults to 30. + #pragma deprecated Use HTTPRequest.Timeout instead. + property int Timeout { + public native get(); + public native set(int timeout); + } + + // Maximum upload speed in bytes per second. Defaults to unlimited speed. + #pragma deprecated Use HTTPRequest.MaxSendSpeed instead. + property int MaxSendSpeed { + public native get(); + public native set(int speed); + } + + // Maximum download speed in bytes per second. Defaults to unlimited speed. + #pragma deprecated Use HTTPRequest.MaxRecvSpeed instead. + property int MaxRecvSpeed { + public native get(); + public native set(int speed); + } +}; diff --git a/scripting/include/ripext/json.inc b/scripting/include/ripext/json.inc new file mode 100644 index 0000000..9d13ef9 --- /dev/null +++ b/scripting/include/ripext/json.inc @@ -0,0 +1,400 @@ +// Decoding flags +enum +{ + JSON_REJECT_DUPLICATES = 0x1, /**< Error if any JSON object contains duplicate keys */ + JSON_DISABLE_EOF_CHECK = 0x2, /**< Allow extra data after a valid JSON array or object */ + JSON_DECODE_ANY = 0x4, /**< Decode any value */ + JSON_DECODE_INT_AS_REAL = 0x8, /**< Interpret all numbers as floats */ + JSON_ALLOW_NUL = 0x10 /**< Allow \u0000 escape inside string values */ +}; + +// Encoding flags +enum +{ + JSON_COMPACT = 0x20, /**< Compact representation */ + JSON_ENSURE_ASCII = 0x40, /**< Escape all Unicode characters outside the ASCII range */ + JSON_SORT_KEYS = 0x80, /**< Sort object keys */ + JSON_ENCODE_ANY = 0x200, /**< Encode any value */ + JSON_ESCAPE_SLASH = 0x400, /**< Escape / with \/ */ + JSON_EMBED = 0x10000 /**< Omit opening and closing braces of the top-level object */ +}; + +// Maximum indentation +static const int JSON_MAX_INDENT = 0x1F; + +// Pretty-print the result, indenting with n spaces +stock int JSON_INDENT(int n) +{ + return n & JSON_MAX_INDENT; +} + +// Output floats with at most n digits of precision +stock int JSON_REAL_PRECISION(int n) +{ + return (n & 0x1F) << 11; +} + +// Generic type for encoding JSON. +methodmap JSON < Handle +{ + // Writes the JSON string representation to a file. + // + // @param file File to write to. + // @param flags Encoding flags. + // @return True on success, false on failure. + public native bool ToFile(const char[] file, int flags = 0); + + // Retrieves the JSON string representation. + // + // @param buffer String buffer to write to. + // @param maxlength Maximum length of the string buffer. + // @param flags Encoding flags. + // @return True on success, false on failure. + public native bool ToString(char[] buffer, int maxlength, int flags = 0); +}; + +methodmap JSONObject < JSON +{ + // Creates a JSON object. A JSON object maps strings (called "keys") to values. Keys in a + // JSON object are unique. That is, there is at most one entry in the map for a given key. + // + // The JSONObject must be freed via delete or CloseHandle(). + public native JSONObject(); + + // Loads a JSON object from a file. + // + // @param file File to read from. + // @param flags Decoding flags. + // @return Object handle, or null on failure. + // @error Invalid JSON. + public static native JSONObject FromFile(const char[] file, int flags = 0); + + // Loads a JSON object from a string. + // + // @param buffer String buffer to load into the JSON object. + // @param flags Decoding flags. + // @return Object handle, or null on failure. + // @error Invalid JSON. + public static native JSONObject FromString(const char[] buffer, int flags = 0); + + // Retrieves an array or object value from the object. + // + // The JSON must be freed via delete or CloseHandle(). + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native JSON Get(const char[] key); + + // Retrieves a boolean value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native bool GetBool(const char[] key); + + // Retrieves a float value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native float GetFloat(const char[] key); + + // Retrieves an integer value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native int GetInt(const char[] key); + + // Retrieves a 64-bit integer value from the object. + // + // @param key Key string. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if the key was not found. + public native bool GetInt64(const char[] key, char[] buffer, int maxlength); + + // Retrieves a string value from the object. + // + // @param key Key string. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success. False if the key was not found, or the value is not a string. + public native bool GetString(const char[] key, char[] buffer, int maxlength); + + // Returns whether or not a value in the object is null. + // + // @param key Key string. + // @return True if the value is null, false otherwise. + // @error Invalid key. + public native bool IsNull(const char[] key); + + // Returns whether or not a key exists in the object. + // + // @param key Key string. + // @return True if the key exists, false otherwise. + public native bool HasKey(const char[] key); + + // Sets an array or object value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool Set(const char[] key, JSON value); + + // Sets a boolean value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetBool(const char[] key, bool value); + + // Sets a float value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetFloat(const char[] key, float value); + + // Sets an integer value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetInt(const char[] key, int value); + + // Sets a 64-bit integer value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetInt64(const char[] key, const char[] value); + + // Sets a null value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @return True on success, false on failure. + public native bool SetNull(const char[] key); + + // Sets a string value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetString(const char[] key, const char[] value); + + // Removes an entry from the object. + // + // @param key Key string. + // @return True on success, false if the key was not found. + public native bool Remove(const char[] key); + + // Clears the object of all entries. + // @return True on success, false on failure. + public native bool Clear(); + + // Returns an iterator for the object's keys. See JSONObjectKeys. + public native JSONObjectKeys Keys(); + + // Retrieves the size of the object. + property int Size { + public native get(); + } +}; + +/** + * A JSONObjectKeys is created via JSONObject.Keys(). It allows the keys of an + * object to be iterated. The JSONObjectKeys must be freed with delete or + * CloseHandle(). + */ +methodmap JSONObjectKeys < Handle +{ + // Reads an object key, then advances to the next key if any. + // + // @param buffer String buffer to store key. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if there are no more keys. + public native bool ReadKey(char[] buffer, int maxlength); +}; + +methodmap JSONArray < JSON +{ + // Creates a JSON array. + // + // The JSONArray must be freed via delete or CloseHandle(). + public native JSONArray(); + + // Loads a JSON array from a file. + // + // @param file File to read from. + // @param flags Decoding flags. + // @return Array handle, or null on failure. + // @error Invalid JSON. + public static native JSONArray FromFile(const char[] file, int flags = 0); + + // Loads a JSON array from a string. + // + // @param buffer String buffer to load into the JSON array. + // @param flags Decoding flags. + // @return Array handle, or null on failure. + // @error Invalid JSON. + public static native JSONArray FromString(const char[] buffer, int flags = 0); + + // Retrieves an array or object value from the array. + // + // The JSON must be freed via delete or CloseHandle(). + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native JSON Get(int index); + + // Retrieves a boolean value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native bool GetBool(int index); + + // Retrieves a float value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native float GetFloat(int index); + + // Retrieves an integer value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native int GetInt(int index); + + // Retrieves an 64-bit integer value from the array. + // + // @param index Index in the array. + // @param buffer Buffer to copy to. + // @param maxlength Maximum size of the buffer. + // @error Invalid index. + public native void GetInt64(int index, char[] buffer, int maxlength); + + // Retrieves a string value from the array. + // + // @param index Index in the array. + // @param buffer Buffer to copy to. + // @param maxlength Maximum size of the buffer. + // @return True on success, false if the value is not a string. + // @error Invalid index. + public native bool GetString(int index, char[] buffer, int maxlength); + + // Returns whether or not a value in the array is null. + // + // @param index Index in the array. + // @return True if the value is null, false otherwise. + // @error Invalid index. + public native bool IsNull(int index); + + // Sets an array or object value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool Set(int index, JSON value); + + // Sets a boolean value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetBool(int index, bool value); + + // Sets a float value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetFloat(int index, float value); + + // Sets an integer value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetInt(int index, int value); + + // Sets a 64 bit integer value in the array. + // + // @param index Index in the array. + // @param value 64-bit integer value to set. + // @return True on success, false on failure. + public native bool SetInt64(int index, const char[] value); + + // Sets a null value in the array. + // + // @param index Index in the array. + // @return True on success, false on failure. + public native bool SetNull(int index); + + // Sets a string value in the array. + // + // @param index Index in the array. + // @param value String value to set. + // @return True on success, false on failure. + public native bool SetString(int index, const char[] value); + + // Pushes an array or object value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool Push(JSON value); + + // Pushes a boolean value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushBool(bool value); + + // Pushes a float value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushFloat(float value); + + // Pushes an integer value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushInt(int value); + + // Pushes a 64-bit integer value onto the end of the array, adding a new index. + // + // @param value 64-bit integer value to push. + // @return True on success, false on failure. + public native bool PushInt64(const char[] value); + + // Pushes a null value onto the end of the array, adding a new index. + // @return True on success, false on failure. + public native bool PushNull(); + + // Pushes a string value onto the end of the array, adding a new index. + // + // @param value String value to push. + // @return True on success, false on failure. + public native bool PushString(const char[] value); + + // Removes an entry from the array. + // + // @param index Index in the array to remove. + // @return True on success, false on invalid index. + public native bool Remove(int index); + + // Clears the array of all entries. + // @return True on success, false on failure. + public native bool Clear(); + + // Retrieves the size of the array. + property int Length { + public native get(); + } +}; diff --git a/scripting/include/sceneprocessor.inc b/scripting/include/sceneprocessor.inc new file mode 100644 index 0000000..cbdd2a7 --- /dev/null +++ b/scripting/include/sceneprocessor.inc @@ -0,0 +1,283 @@ +#if defined _sceneprocessor_included + #endinput +#endif +#define _sceneprocessor_included + +#define MAX_SCENEFILE_LENGTH PLATFORM_MAX_PATH // Maximum length of scene files +#define MAX_VOCALIZE_LENGTH 128 // Maximum length of vocalize strings + +#define SCENE_INITIATOR_WORLD 0 /* All scenes created by the map (such as landmarks, "Down this way", "Through here") + * and by the game (such as team mate actions, "Let me heal you up", "Help I'm falling") + * are marked as started by the world, or entity index 0. */ +#define SCENE_INITIATOR_PLUGIN -1 /* All scenes started by the Scene Processor are by default marked as started by plugin or + * entity index -1. This can be changed in the PerformScene function call. */ + +#define DEFAULT_SCENE_PREDELAY 0.0 /* By default all scenes occur the instant they are created */ +#define DEFAULT_SCENE_PITCH 1.0 /* By default all scenes have a pitch of 1.0, or as they are normally heard. 2.0 will make + * it sounds twice as fast but in a high pitched voice. 0.5 will be half the normal speed + * and with low pitched voice. */ + +enum SceneStages +{ + SceneStage_Unknown = 0, /* Scene has not been created nor processed. Either something went wrong, the + * scene is not valid, incorrectly formatted, or a round just started recently. */ + + SceneStage_Created = 1, /* When scene is created. Contains no information about the scene that is about to + * be played out. Guaranteed to occur. */ + + SceneStage_Spawned, /* When scene is spawned. Everything is filled in but the pre-delay! Change scene + * pitch and pre-delay here. */ + + SceneStage_SpawnedPost, /* Post scene spawned frame. Pre-delay is now filled out. Pre-delay can be changed + * here if the scene originally has a pre-delay greater than 0.0. */ + + SceneStage_Started, /* When scene is started. Time stamp is set. */ + + SceneStage_Cancelled, /* When scene is cancelled. Happens if the Survivor was interrupted by another scene + * or the scene was cancelled post starting. */ + + SceneStage_Completion, /* When scene is completed. Happens if the Survivor gets to fully perform the scene + * with no interruptions or cancellation. Entity index is no longer valid but + * information is retained. */ + + SceneStage_Killed /* When scene is killed. Entity index is no longer valid but information is retained + * until end of forward. Guaranteed to occur */ +}; + +/** + * Called on scene stage changed. + * + * @param scene Scene entity index. + * @param stage SceneStages value. + * @noreturn + */ +forward void OnSceneStageChanged(int scene, SceneStages stage); + +/** + * Called on vocalize command send. + * + * @remarks See SCENE_INITIATOR_WORLD and SCENE_INITIATOR_PLUGIN for + * non-client initiated vocalizes. + * + * @param client Index of player sending vocalize command. + * @param vocalize String of what player wish to vocalize, as typed. + * @param initiator Index of entity initiated vocalize command. + * @return Plugin_Stop to stop vocalize command. + * Plugin_Continue to allow vocalize command. + */ +forward Action OnVocalizeCommand(int client, const char[] vocalize, int initiator); + +/** + * Returns scene stage. + * + * @param scene Scene entity index. + * @return SceneStages value or 0 if scene is not valid. + */ +native SceneStages GetSceneStage(int scene); + +/** + * Returns whether scene is valid as a scene. + * + * @remarks The scene entity index may still be invalid. + * + * @param scene Scene entity index. + * @return True if a valid scene, false otherwise. + */ +stock bool IsValidScene(int scene) +{ + return GetSceneStage(scene) != SceneStage_Unknown; +} + +/** + * Returns scene start time stamp, in engine time. + * + * @param scene Scene entity index. + * @return Scene start engine time stamp. 0.0 if the scene has not started yet. + */ +native float GetSceneStartTimeStamp(int scene); + +/** + * Returns scene actor. + * + * @param scene Scene entity index. + * @return Actor of the scene. 0 if no one is playing it. + */ +native int GetActorFromScene(int scene); + +/** + * Returns actor's scene. + * + * @remarks Only returns scene if it is currently being played out. + * + * @param actor Client index of actor. + * @return Scene entity index. INVALID_ENT_REFERENCE if actor currently aren't playing. + */ +native int GetSceneFromActor(int actor); + +/** + * Returns whether actor is already playing a scene. + * + * @param actor Client index of actor. + * @return True if actor is busy, false otherwise. + */ +stock bool IsActorBusy(int actor) +{ + return GetSceneFromActor(actor) != INVALID_ENT_REFERENCE; +} + +/** + * Returns scene initiator. + * + * @remarks See SCENE_INITIATOR_WORLD and SCENE_INITIATOR_PLUGIN for automated + * scenes. + * + * @param scene Scene entity index. + * @return Initiator of the scene. + */ +native int GetSceneInitiator(int scene); + +/** + * Returns scene file. + * + * @param scene Scene entity index. + * @param dest Destination string buffer to copy to. + * @param len Destination buffer length (includes null terminator). + * @return Number of bytes written + */ +native int GetSceneFile(int scene, char[] dest, int len); + +/** + * Returns scene vocalize. + * + * @remarks Will only contain the vocalize string if the scene was started by + * the client them self. Otherwise empty. + * + * @param scene Scene entity index. + * @param dest Destination string buffer to copy to. + * @param len Destination buffer length (includes null terminator). + * @return Number of bytes written + */ +native int GetSceneVocalize(int scene, char[] dest, int len); + +/** + * Returns scene pre-delay. + * + * @remarks Sadly pre-delay is first fetched on SceneStage_SpawnedPost where + * altering the pre-delay with SetScenePreDelay might already be too late. + * + * @param scene Scene entity index. + * @return Scene pre-delay in seconds. + */ +native float GetScenePreDelay(int scene); + +/** + * Sets scene pre-delay. + * + * @remarks Pre-delay can be set on SceneStage_Spawned and sometimes (!) on + * SceneStage_SpawnedPost depending on whether the scene originally has a + * pre-delay. Once SceneStage_Started fires pre-delay is no longer obeyed. + * + * @param scene Scene entity index. + * @param preDelay Scene pre-delay in seconds. + * @noreturn + */ +native void SetScenePreDelay(int scene, float preDelay); + +/** + * Returns scene pitch. + * + * @param scene Scene entity index. + * @return Scene pitch. + */ +native float GetScenePitch(int scene); + +/** + * Sets scene pitch + * + * @remarks Scene pitch can be set on SceneStage_Spawned and + * SceneStage_SpawnedPost. Setting pitch post spawning results in weird + * settings such as some clients hearing 1.13 as double as fast instead of 2.0. + * + * @param scene Scene entity index. + * @param pitch Scene pitch. + * @noreturn + */ +native void SetScenePitch(int scene, float pitch); + +/** + * Cancels scene. + * + * @remarks Can be used at all scene stages. Scene is validated before sending + * the cancel input. + * + * @param scene Scene entity index. + * @noreturn + */ +native void CancelScene(int scene); + +/** + * Performs a scene. + * + * @remarks Scene file is used before vocalize string however vocalize string + * is still saved to scene entity index and can be retrieved for later usage. + * If vocalize string is used, it is delayed for a short while in order to + * work if used inside of OnSceneStageChanged. See PerformSceneEx to avoid + * this delay. + * + * @param client Client index. + * @param vocalize Vocalize string. + * @param file Scene file. + * @param preDelay Scene pre-delay. + * @param pitch Scene pitch. + * @param initiator Initiator of the scene. + * @noreturn + */ +native void PerformScene(int client, const char[] vocalize, const char[] file = "", float preDelay = DEFAULT_SCENE_PREDELAY, float pitch = DEFAULT_SCENE_PITCH, int initiator = SCENE_INITIATOR_PLUGIN); + +/** + * Performs a scene. + * + * @remarks Works the same way as PerformScene however there is no delay when + * using vocalize string. Not recommend to use inside OnSceneStageChanged if + * vocalizes needs to get through. + * + * @param client Client index. + * @param vocalize Vocalize string. + * @param file Scene file. + * @param preDelay Scene pre-delay. + * @param pitch Scene pitch. + * @param initiator Initiator of the scene. + * @noreturn + */ +native void PerformSceneEx(int client, const char[] vocalize, const char[] file = "", float preDelay = DEFAULT_SCENE_PREDELAY, float pitch = DEFAULT_SCENE_PITCH, int initiator = SCENE_INITIATOR_PLUGIN); + +public SharedPlugin __pl_sceneproces = +{ + name = "sceneprocessor", + file = "sceneprocessor.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_sceneproces_SetNTVOptional() +{ + MarkNativeAsOptional("GetSceneStage"); + MarkNativeAsOptional("GetSceneStartTimeStamp"); + MarkNativeAsOptional("GetActorFromScene"); + MarkNativeAsOptional("GetSceneFromActor"); + MarkNativeAsOptional("GetSceneInitiator"); + MarkNativeAsOptional("GetSceneFile"); + MarkNativeAsOptional("GetSceneVocalize"); + MarkNativeAsOptional("GetScenePreDelay"); + MarkNativeAsOptional("SetScenePreDelay"); + MarkNativeAsOptional("GetScenePitch"); + MarkNativeAsOptional("SetScenePitch"); + MarkNativeAsOptional("CancelScene"); + MarkNativeAsOptional("PerformScene"); + MarkNativeAsOptional("PerformSceneEx"); +} +#endif \ No newline at end of file diff --git a/scripting/include/smlib/arrays.inc b/scripting/include/smlib/arrays.inc new file mode 100644 index 0000000..87f1733 --- /dev/null +++ b/scripting/include/smlib/arrays.inc @@ -0,0 +1,157 @@ +#if defined _smlib_array_included + #endinput +#endif +#define _smlib_array_included + +#include + +/** + * Returns the index for the first occurance of the given value. + * If the value cannot be found, -1 will be returned. + * + * @param array Static Array. + * @param size Size of the Array. + * @param value Value to search for. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index, or -1 if the value couldn't be found. + */ +stock int Array_FindValue(const any[] array, int size, any value, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + + if (array[i] == value) { + return i; + } + } + + return -1; +} + +/** + * Searchs for the first occurance of a string in the array. + * If the value cannot be located, -1 will be returned. + * + * @param array Static Array. + * @param size Size of the Array. + * @param value String to search for. + * @param start Optional: Offset where to start(0 - (size-1)). + * @return Array index, or -1 if the value couldn't be found. + */ +stock int Array_FindString(const char[][] array, int size, const char[] str, bool caseSensitive=true, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + + if (StrEqual(array[i], str, caseSensitive)) { + return i; + } + } + + return -1; +} + +/** + * Returns the Index of the Lowest value in the array + * + * @param array Static Array. + * @param size Size of the Array. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index. + */ +stock int Array_FindLowestValue(const any[] array, int size, int start=0) +{ + if (start < 0) { + start = 0; + } + + any value = array[start]; + any tempValue; + int x = start; + + for (int i=start; i < size; i++) { + + tempValue = array[i]; + + if (tempValue < value) { + value = tempValue; + x = i; + } + + } + + return x; +} + +/** + * Returns the Index of the Highest value in the array + * + * @param array Static Array. + * @param size Size of the Array. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index. + */ +stock int Array_FindHighestValue(const any[] array, int size, int start=0) +{ + if (start < 0) { + start = 0; + } + + any value = array[start]; + any tempValue; + int x = start; + + for (int i=start; i < size; i++) { + + tempValue = array[i]; + + if (tempValue > value) { + value = tempValue; + x = i; + } + + } + + return x; +} + +/** + * Fills an array with a given value in a 1 dimensional static array. + * You can specify the amount of cells to be written. + * + * @param array Static Array. + * @param size Number of cells to write (eg. the array's size) + * @param value Fill value. + * @param start Optional: Offset where to start (0 - (size-1)). + */ +stock void Array_Fill(any[] array, int size, any value, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + array[i] = value; + } +} + +/** + * Copies a 1 dimensional static array. + * + * @param array Static Array to copy from. + * @param newArray New Array to copy to. + * @param size Size of the array (or number of cells to copy) + * @noreturn + */ +stock void Array_Copy(const any[] array, any[] newArray, int size) +{ + for (int i=0; i < size; i++) { + newArray[i] = array[i]; + } +} diff --git a/scripting/include/smlib/clients.inc b/scripting/include/smlib/clients.inc new file mode 100644 index 0000000..ca5cf4c --- /dev/null +++ b/scripting/include/smlib/clients.inc @@ -0,0 +1,3077 @@ +#if defined _smlib_client_included + #endinput +#endif +#define _smlib_client_included + +// Defined here beacause needed in teams.inc +#define CLIENTFILTER_ALL 0 // No filtering +#define CLIENTFILTER_BOTS ( 1 << 1 ) // Fake clients +#define CLIENTFILTER_NOBOTS ( 1 << 2 ) // No fake clients +#define CLIENTFILTER_AUTHORIZED ( 1 << 3 ) // SteamID validated +#define CLIENTFILTER_NOTAUTHORIZED ( 1 << 4 ) // SteamID not validated (yet) +#define CLIENTFILTER_ADMINS ( 1 << 5 ) // Generic Admins (or higher) +#define CLIENTFILTER_NOADMINS ( 1 << 6 ) // No generic admins +// All flags below require ingame checking (optimization) +#define CLIENTFILTER_INGAME ( 1 << 7 ) // Ingame +#define CLIENTFILTER_INGAMEAUTH ( 1 << 8 ) // Ingame & Authorized +#define CLIENTFILTER_NOTINGAME ( 1 << 9 ) // Not ingame (currently connecting) +#define CLIENTFILTER_ALIVE ( 1 << 10 ) // Alive +#define CLIENTFILTER_DEAD ( 1 << 11 ) // Dead +#define CLIENTFILTER_SPECTATORS ( 1 << 12 ) // Spectators +#define CLIENTFILTER_NOSPECTATORS ( 1 << 13 ) // No Spectators +#define CLIENTFILTER_OBSERVERS ( 1 << 14 ) // Observers +#define CLIENTFILTER_NOOBSERVERS ( 1 << 15 ) // No Observers +#define CLIENTFILTER_TEAMONE ( 1 << 16 ) // First Team (Terrorists, ...) +#define CLIENTFILTER_TEAMTWO ( 1 << 17 ) // Second Team (Counter-Terrorists, ...) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * Very useful macro to iterate all clients + * matching the specified flags. + * + * @param 1 Name of the client index variable (will be only valid in the loop). + * @param 2 CLIENTFILTER_ flags to check. + */ +#define LOOP_CLIENTS(%1,%2) for (int %1=Client_GetNext(%2); %1 >= 1 && %1 <= MaxClients; %1=Client_GetNext(%2, ++%1)) + +/** + * Macro for iterating trough all observers of a player. + * + * @param 1 Client Index for who to get the observers. + * @param 2 Name of the observer client index variable (will be only valid in the loop). + * @param 3 CLIENTFILTER_ flags to check. + */ +#define LOOP_OBSERVERS(%1,%2,%3) for (int %2=Client_GetNextObserver(%1, 1, %3); %2 >= 1 && %2 <= MaxClients; %2=Client_GetNextObserver(%1, ++%2, %3)) + +/** + * Very useful macro to iterate all weapons of a client. + * + * @param 1 Client Index + * @param 2 Name of the weapon index variable (will be only valid in the loop). + * @param 3 Name of the client's weapon index variable (will be only valid in the loop). + */ +#define LOOP_CLIENTWEAPONS(%1,%2,%3) for (int %3, %2=Client_GetNextWeapon(%1, %3); %2 != -1; %2=Client_GetNextWeapon(%1, %3)) + +// Hud Element hiding flags (possibly outdated) +#define HIDEHUD_WEAPONSELECTION ( 1<<0 ) // Hide ammo count & weapon selection +#define HIDEHUD_FLASHLIGHT ( 1<<1 ) +#define HIDEHUD_ALL ( 1<<2 ) +#define HIDEHUD_HEALTH ( 1<<3 ) // Hide health & armor / suit battery +#define HIDEHUD_PLAYERDEAD ( 1<<4 ) // Hide when local player's dead +#define HIDEHUD_NEEDSUIT ( 1<<5 ) // Hide when the local player doesn't have the HEV suit +#define HIDEHUD_MISCSTATUS ( 1<<6 ) // Hide miscellaneous status elements (trains, pickup history, death notices, etc) +#define HIDEHUD_CHAT ( 1<<7 ) // Hide all communication elements (saytext, voice icon, etc) +#define HIDEHUD_CROSSHAIR ( 1<<8 ) // Hide crosshairs +#define HIDEHUD_VEHICLE_CROSSHAIR ( 1<<9 ) // Hide vehicle crosshair +#define HIDEHUD_INVEHICLE ( 1<<10 ) +#define HIDEHUD_BONUS_PROGRESS ( 1<<11 ) // Hide bonus progress display (for bonus map challenges) + +/** +* Sets the Hide-Hud flags of a client +* +* @param client Client index. +* @param flags Flag to set, use one of the HIDEHUD_ hiding constants +*/ +stock void Client_SetHideHud(int client, int flags) +{ + SetEntProp(client, Prop_Send, "m_iHideHUD", flags); +} + +/** +* Checks if the specified index is a player and connected. +* +* @param entity An entity index. +* @param checkConnected Set to false to skip the IsClientConnected check +* @return Returns true if the specified entity index is a player connected, false otherwise. +*/ +stock bool Client_IsValid(int client, bool checkConnected=true) +{ + if (client > 4096) { + client = EntRefToEntIndex(client); + } + + if (client < 1 || client > MaxClients) { + return false; + } + + if (checkConnected && !IsClientConnected(client)) { + return false; + } + + return true; +} + +/** +* Checks if the specified index is a player and ingame. +* +* @param entity An entity index. +* @return Returns true if the specified index is a player and ingame, false otherwise. +*/ +stock bool Client_IsIngame(int client) +{ + if (!Client_IsValid(client, false)) { + return false; + } + + return IsClientInGame(client); +} + +/** +* Checks if the specified index is a player, ingame and authorized. +* +* @param entity An entity index. +* @return Returns true if the specified index is a player, ingame and authed, false otherwise. +*/ +stock bool Client_IsIngameAuthorized(int client) +{ + if (!Client_IsIngame(client)) { + return false; + } + + return IsClientAuthorized(client); +} + +#define MAX_STEAMAUTH_LENGTH 21 + +/** +* Finds a player by his SteamID +* +* @param auth SteamID to search for +* @return Client Index or -1 +*/ +stock int Client_FindBySteamId(const char[] auth) +{ + char clientAuth[MAX_STEAMAUTH_LENGTH]; + for (int client=1; client <= MaxClients; client++) { + if (!IsClientAuthorized(client)) { + continue; + } + + GetClientAuthId(client, AuthId_Steam2, clientAuth, sizeof(clientAuth)); + + if (StrEqual(auth, clientAuth)) { + return client; + } + } + + return -1; +} + +/** +* Finds a player by his name. +* Only returns the first matching player. +* +* @param name Name to search for. +* @param partOfName Whether to search for the part of a name or compare the full name. +* @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. +* @return Client Index or -1 +*/ +stock int Client_FindByName(const char[] name, bool partOfName=true, bool caseSensitive=false) +{ + char clientName[MAX_NAME_LENGTH]; + for (int client=1; client <= MaxClients; client++) { + if (!IsClientAuthorized(client)) { + continue; + } + + GetClientName(client, clientName, sizeof(clientName)); + + if (partOfName) { + if (StrContains(clientName, name, caseSensitive) != -1) { + return client; + } + } + else if (StrEqual(name, clientName, caseSensitive)) { + return client; + } + } + + return -1; +} + +// Spectator Movement modes +enum Obs_Mode +{ + OBS_MODE_NONE = 0, // not in spectator mode + OBS_MODE_DEATHCAM, // special mode for death cam animation + OBS_MODE_FREEZECAM, // zooms to a target, and freeze-frames on them + OBS_MODE_FIXED, // view from a fixed camera position + OBS_MODE_IN_EYE, // follow a player in first person view + OBS_MODE_CHASE, // follow a player in third person view + OBS_MODE_ROAMING, // free roaming + + NUM_OBSERVER_MODES +}; + +// Force Camera Restrictions with mp_forcecamera +enum Obs_Allow +{ + OBS_ALLOW_ALL = 0, // allow all modes, all targets + OBS_ALLOW_TEAM, // allow only own team & first person, no PIP + OBS_ALLOW_NONE, // don't allow any spectating after death (fixed & fade to black) + + OBS_ALLOW_NUM_MODES, +}; + +/** + * Gets the client's observer mode (Obs_Mode). + * + * @param client Client Index. + * @return The current observer mode (ObsMode). + */ +stock Obs_Mode Client_GetObserverMode(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_iObserverMode")); +} + + +/** + * Sets the client's observer mode. + * Use a value of the Obs_Mode enum. + * This is a rewrite of CBasePlayer::SetObserverMode(). + * + * @param client Client Index. + * @param mode New Observer mode value (Obs_Mode). + * @param updateMoveType Set to true (default) to allow this function updating the movetype, false otherwise. + */ +stock void Client_SetObserverMode(int client, Obs_Mode mode, bool updateMoveType=true) +{ + if (mode < OBS_MODE_NONE || mode >= NUM_OBSERVER_MODES) { + return; + } + + // check mp_forcecamera settings for dead players + if (mode > OBS_MODE_FIXED && GetClientTeam(client) > TEAM_SPECTATOR) + { + ConVar mp_forcecamera = FindConVar("mp_forcecamera"); + + if (mp_forcecamera != INVALID_HANDLE) { + switch (view_as(mp_forcecamera.IntValue)) + { + case OBS_ALLOW_TEAM: { + mode = OBS_MODE_IN_EYE; + } + case OBS_ALLOW_NONE: { + mode = OBS_MODE_FIXED; // don't allow anything + } + } + } + } + + Obs_Mode observerMode = Client_GetObserverMode(client); + if (observerMode > OBS_MODE_DEATHCAM) { + // remember mode if we were really spectating before + Client_SetObserverLastMode(client, observerMode); + } + + SetEntProp(client, Prop_Send, "m_iObserverMode", mode); + + switch (mode) { + case OBS_MODE_NONE, OBS_MODE_FIXED, OBS_MODE_DEATHCAM: { + Client_SetFOV(client, 0); // Reset FOV + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_NONE); + } + } + case OBS_MODE_CHASE, OBS_MODE_IN_EYE: { + // udpate FOV and viewmodels + Client_SetViewOffset(client, NULL_VECTOR); + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_OBSERVER); + } + } + case OBS_MODE_ROAMING: { + Client_SetFOV(client, 0); // Reset FOV + Client_SetViewOffset(client, NULL_VECTOR); + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_OBSERVER); + } + } + } +} + +/** + * Gets the client's last oberserver mode + * + * @param client Client Index. + * @return Last Observer mode + */ +stock Obs_Mode Client_GetObserverLastMode(int client) +{ + return view_as(GetEntProp(client, Prop_Data, "m_iObserverLastMode")); +} + +/** + * Sets the client's last oberserver mode + * + * @param client Client Index. + * @param mode Last Observer mode + */ +stock void Client_SetObserverLastMode(int client, Obs_Mode mode) +{ + SetEntProp(client, Prop_Data, "m_iObserverLastMode", mode); +} + +/** + * Gets the client's view offset. + * This is the position relative to the client itself. + * + * @param client Client Index. + * @param vec Vector Buffer. + */ +stock void Client_GetViewOffset(int client, float vec[3]) +{ + GetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); +} + +/** + * Sets the client's view offset. + * This is the position relative to the client itself. + * + * @param client Client Index. + * @param vec Vector buffer. + * @noreturn + */ +stock void Client_SetViewOffset(int client, float vec[3]) +{ + SetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); +} + +/** + * Gets the client's current observer target entity. + * + * @param client Client Index. + * @return Observed Entity Index. + */ +stock int Client_GetObserverTarget(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); +} + +/** + * Sets the client's current observer target entity. + * + * @param client Client Index. + * @param entity Observed Entity Index. + * @param resetFOV If to reset the client's field of view. + */ +stock void Client_SetObserverTarget(int client, int entity, bool resetFOV=true) +{ + SetEntPropEnt(client, Prop_Send, "m_hObserverTarget", entity); + + if (resetFOV) { + Client_SetFOV(client, 0); + } +} + +/** + * Gets the client's Field Of View. + * + * @param client Client Index. + * @return Field Of View + */ +stock int Client_GetFOV(int client) +{ + return GetEntProp(client, Prop_Send, "m_iFOV"); +} + +/** + * Sets the client's Field Of View. + * + * @param client Client Index. + * @param value Field Of View + */ +stock void Client_SetFOV(int client, int value) +{ + SetEntProp(client, Prop_Send, "m_iFOV", value); +} + +/** + * Checks if the client's View Model is drawn for the client. + * + * @param client Client Index. + * @return True if the viewmodel is drawn, false otherwise. + */ +stock bool Client_DrawViewModel(int client) +{ + return GetEntProp(client, Prop_Send, "m_bDrawViewmodel") != 0; +} + +/** + * Sets if to draw the client's view model for the client. + * + * @param client Client Index. + * @param drawViewModel Set to true if to draw, false otherwise. + */ +stock void Client_SetDrawViewModel(int client, bool drawViewModel) +{ + SetEntProp(client, Prop_Send, "m_bDrawViewmodel", drawViewModel); +} + +/** + * Puts the specified client into thirdperson or back to firstperson when false + * This doesn't work correctly in all games, it works in CS:S and DOD:S and some other games. + * Todo: Enhance this + * + * @param client Client Index. + * @param enable If set to true, the client will be put into thirdperson mode, + * if false the client will be put in firstperson mode. + */ +stock void Client_SetThirdPersonMode(int client, bool enable=true) +{ + if (enable) { + Client_SetObserverTarget(client, 0); + Client_SetObserverMode(client, OBS_MODE_DEATHCAM, false); + Client_SetDrawViewModel(client, false); + Client_SetFOV(client, 120); + } + else { + Client_SetObserverTarget(client, -1); + Client_SetObserverMode(client, OBS_MODE_NONE, false); + Client_SetDrawViewModel(client, true); + Client_SetFOV(client, 90); + } +} + +/** + * Checks if the client is in thirdperson mode + * + * @param client Cient Undex + * @return true if the client is currently in thirdperson mode, false otherwise + */ +stock bool Client_IsInThirdPersonMode(int client) +{ + // FIXME: Is this enough? + return Client_GetObserverMode(client) == OBS_MODE_DEATHCAM; +} + +#define FFADE_IN 0x0001 // Just here so we don't pass 0 into the function +#define FFADE_OUT 0x0002 // Fade out (not in) +#define FFADE_MODULATE 0x0004 // Modulate (don't blend) +#define FFADE_STAYOUT 0x0008 // ignores the duration, stays faded out until new ScreenFade message received +#define FFADE_PURGE 0x0010 // Purges all other fades, replacing them with this one + +/** + * Fades a client's screen to a specified color + * Your adviced to read the FFADE_ Comments + * + * @param client Player for which to fade the screen + * @param duration duration in seconds the effect stays + * @param mode fade mode, see FFADE_ defines + * @param holdtime holdtime in seconds + * @param r red amount + * @param g green amount + * @param b blue amount + * @param a transparency + * @return True on success, false otherwise + */ +stock bool Client_ScreenFade(int client, int duration, int mode, int holdtime=-1, int r=0, int g=0, int b=0, int a=255, bool reliable=true) +{ + Handle userMessage = StartMessageOne("Fade", client, (reliable?USERMSG_RELIABLE:0)); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && + GetUserMessageType() == UM_Protobuf) { + + int color[4]; + color[0] = r; + color[1] = g; + color[2] = b; + color[3] = a; + + PbSetInt(userMessage, "duration", duration); + PbSetInt(userMessage, "hold_time", holdtime); + PbSetInt(userMessage, "flags", mode); + PbSetColor(userMessage, "clr", color); + } + else { + BfWriteShort(userMessage, duration); // Fade duration + BfWriteShort(userMessage, holdtime); // Fade hold time + BfWriteShort(userMessage, mode); // What to do + BfWriteByte(userMessage, r); // Color R + BfWriteByte(userMessage, g); // Color G + BfWriteByte(userMessage, b); // Color B + BfWriteByte(userMessage, a); // Color Alpha + } + EndMessage(); + + return true; +} + +/** + * This function retrieves an array that holds all clones of a client by IP check. + * Size of CloneList has to be MaxClients at least, or MAX_PLAYERS + * + * @param client Client index. + * @param closelist An array that holds all clones of a client. + * @return Returns how many clones a client has. + */ +stock int Client_GetClones(int client, int[] cloneList) +{ + int x=0; + char ip_client[16], ip_player[16]; + + GetClientIP(client, ip_client, sizeof(client)); + + for (int player=1; player <= MaxClients; player++) { + + if (IsClientInGame(player)) { + GetClientIP(player, ip_player, sizeof(ip_player)); + + if (StrEqual(ip_client, ip_player, false)) { + cloneList[x++] = player; + } + } + } + + return x; +} + +/* + * This function returns true if the client is at a ladder.. + * + * @param client Client index. + * @return Returns true if the client is on a ladder other wise false. + */ +stock bool Client_IsOnLadder(int client) +{ + MoveType movetype = GetEntityMoveType(client); + + if (movetype == MOVETYPE_LADDER) { + return true; + } + else{ + return false; + } +} + +enum Water_Level +{ + WATER_LEVEL_NOT_IN_WATER = 0, + WATER_LEVEL_FEET_IN_WATER, + WATER_LEVEL_WAIST_IN_WATER, + WATER_LEVEL_HEAD_IN_WATER +}; + +/* + * This function returns how deep a client is in water. + * + * @param client Client index. + * @return Returns 0 if not in water. 1 if feets are in water. 2 if waist is in water. 3 if head is in water. + */ +stock Water_Level Client_GetWaterLevel(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_nWaterLevel")); +} + +/* + * Returns how much suit sprint power a client has left in percent. + * + * @param client Client index. + * @return returns the actual power left in percent. + */ +stock float Client_GetSuitSprintPower(int client) +{ + return GetEntPropFloat(client, Prop_Send, "m_flSuitPower"); +} + +/* + * Sets a client suit sprint power in percent. + * + * @param client Client index. + * @param power power (0.0 to 100.0) + */ +stock void Client_SetSuitSprintPower(int client, float power) +{ + SetEntPropFloat(client, Prop_Send, "m_flSuitPower", power); +} + +/* + * Returns the client count put in the server. + * + * @param inGameOnly If false connecting players are also counted. + * @param countBots If true bots will be counted too. + * @return Client count in the server. + */ +stock int Client_GetCount(bool countInGameOnly=true, bool countFakeClients=true) +{ + int numClients = 0; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientConnected(client)) { + continue; + } + + if (countInGameOnly && !IsClientInGame(client)) { + continue; + } + + if (!countFakeClients && IsFakeClient(client)) { + continue; + } + + numClients++; + } + + return numClients; +} + +/* + * Returns the ping of a client like it is displayed in the scoreboard. + * The weird calculation formula is taken from Valve's SDK + * hl2sdk\game\server\util.cpp: UTIL_GetPlayerConnectionInfo() + * The Scoreboard uses the goldSource corrected Ping, the net_graph doesn't + * For Fake Clients 0 is returned. + * + * @param client Client index + * @param goldSource If true, get the ping as displayed in the player's scoreboard, false returns the net_graph variant. + * @return Client's fake ping or 0 for fake clients + */ +stock int Client_GetFakePing(int client, bool goldSource=true) +{ + if (IsFakeClient(client)) { + return 0; + } + + int ping; + float latency = GetClientLatency(client, NetFlow_Outgoing); // in seconds + + // that should be the correct latency, we assume that cmdrate is higher + // then updaterate, what is the case for default settings + char cl_cmdrate[4]; + GetClientInfo(client, "cl_cmdrate", cl_cmdrate, sizeof(cl_cmdrate)); + + float tickRate = GetTickInterval(); + latency -= (0.5 / StringToInt(cl_cmdrate)) + TICKS_TO_TIME(1.0); // correct latency + + if (goldSource) { + // in GoldSrc we had a different, not fixed tickrate. so we have to adjust + // Source pings by half a tick to match the old GoldSrc pings. + latency -= tickRate * 0.5; + } + + ping = RoundFloat(latency * 1000.0); // as msecs + ping = Math_Clamp(ping, 5, 1000); // set bounds, dont show pings under 5 msecs + + return ping; +} + +/** + * Searches for the closest client in relation to the given client. + * + * @param client Client index + * @return The closest client or -1 + */ +stock int Client_GetClosestToClient(int client) +{ + return Edict_GetClosestToEdict(client, true); +} + +/** + * Gets the name of the last place (if set by the game) + * + * @param entity Entity index. + * @param buffer String buffer + * @param size Size of the String buffer + */ +stock void Client_GetLastPlaceName(int client, char[] buffer, int size) +{ + GetEntPropString(client, Prop_Send, "m_szLastPlaceName", buffer, size); +} + +/** + * Returns the client's Score. + * + * @param client Client's index. + * @return Score. + */ +stock int Client_GetScore(int client) +{ + return GetClientFrags(client); +} + +/** + * Sets the client's Score. + * + * @param client Client's index. + * @param value Score. + * @noreturn + */ +stock void Client_SetScore(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_iFrags", value); +} + +/** + * Returns the client's Death count + * + * @param client Client's index. + * @return Death count + */ +stock int Client_GetDeaths(int client) +{ + return GetEntProp(client, Prop_Data, "m_iDeaths"); +} + +/** + * Sets the client's Death count. + * + * @param client Client's index. + * @param value Death count + */ +stock void Client_SetDeaths(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_iDeaths", value); +} + +/** + * Returns the client's Armor + * + * @param client Client's index. + * @return Armor value + */ +stock int Client_GetArmor(int client) +{ + return GetEntProp(client, Prop_Data, "m_ArmorValue"); +} + +/** + * Sets the client's Armor. + * + * @param client Client's index. + * @param value Armor value + */ +stock void Client_SetArmor(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_ArmorValue", value); +} + +/** + * Returns the client's Suitpower + * + * @param client Client's index. + * @return Suitpower + */ +stock float Client_GetSuitPower(int client) +{ + return GetEntPropFloat(client, Prop_Data, "m_flSuitPower"); +} + +/** + * Sets the client's Suitpower + * + * @param client Client's index. + * @param value Suitpower + */ +stock void Client_SetSuitPower(int client, float value) +{ + SetEntPropFloat(client, Prop_Data, "m_flSuitPower", value); +} + +// suit usage bits +#define bits_SUIT_DEVICE_SPRINT 0x00000001 +#define bits_SUIT_DEVICE_FLASHLIGHT 0x00000002 +#define bits_SUIT_DEVICE_BREATHER 0x00000004 +#define MAX_SUIT_DEVICES 3 + +/** + * Returns the client's active devices (Max MAX_SUIT_DEVICES) + * The return is a bitwise value with bits_SUIT_DEVICE_SPRINT, + * bits_SUIT_DEVICE_FLASHLIGHT and/or bits_SUIT_DEVICE_BREATHER set. + * + * @param client Client's index. + * @return The active devices (bitwise value) + */ +stock int Client_GetActiveDevices(int client) +{ + return GetEntProp(client, Prop_Send, "m_bitsActiveDevices"); +} + +/** + * Returns the time when the client is allowed to spray + * a decal again. + * + * @param client Client's index. + * @return Next decal time + */ +stock float Client_GetNextDecalTime(int client) +{ + return GetEntPropFloat(client, Prop_Data, "m_flNextDecalTime"); +} + +/** + * Returns whether the client is allowed to spray a decal or not. + * + * @param client Client's index. + * @return True if he is allowed to spray a decal, false otherwise + */ +stock bool Client_CanSprayDecal(int client) +{ + return Client_GetNextDecalTime(client) <= GetGameTime(); +} + +/** + * Returns the vehicle the client is in, if the client + * isn't in a vehicle, -1 is returned. + * + * @param client Client's index. + * @return Vehicle index, -1 if the client isn't in a vehicle. + */ +stock int Client_GetVehicle(int client) +{ + int m_hVehicle = GetEntPropEnt(client, Prop_Send, "m_hVehicle"); + + return m_hVehicle; +} + +/** + * Returns whether the client is in a vehicle or not. + * + * @param client Client's index. + * @return True if he is in a vehicle, false otherwise + */ +stock bool Client_IsInVehicle(int client) +{ + return (Client_GetVehicle(client) != -1); +} + +/** + * Removes all decals for a client + * + * @param client Client's index. + */ +stock void Client_RemoveAllDecals(int client) +{ + ClientCommand(client, "r_cleardecals"); +} + +/** + * Let's the client exit the vehicle + * + * @param vehicle Client index. + * @return True on success, false otherwise. + */ +stock bool Client_ExitVehicle(int client) +{ + int vehicle = Client_GetVehicle(client); + + if (vehicle == -1) { + return false; + } + + return AcceptEntityInput(vehicle, "ExitVehicle"); +} + +/** + * Plays a soundfile as if the player is using voicecomm for a single client. + * The voiceindicator is shown on the right, as if the players is talking. + * Thanks to Peace-Maker for the function. + * + * @param client For whom to play the sound. + * @param emitter Player/Entity the voice stream comes from. + * @param soundfile Path to the soundfile relative to the sound folder. + * @param length Length in seconds how long the hud "voiceindicator" is shown. + * @param pitch The pitch of the audiofile. + * @return True on success, false on failure. + */ +stock bool Client_RawAudio(int client, int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) +{ + Handle message = StartMessageOne("RawAudio", client); + + if (message == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(message, "pitch", pitch); + PbSetInt(message, "entidx", emitter); + PbSetFloat(message, "duration", length ); + PbSetString(message, "voice_filename", soundfile); + } + else { + BfWriteByte(message, pitch); + BfWriteByte(message, emitter); + BfWriteFloat(message, length); + BfWriteString(message, soundfile); + } + EndMessage(); + + return true; +} + +/** + * Plays a soundfile as if the player is using voicecomm for all players. + * The voiceindicator is shown on the right, as if the players is talking. + * Thanks to Peace-Maker for the function. + * + * @param emitter Player/Entity the voice stream comes from. + * @param soundfile Path to the soundfile relative to the sound folder. + * @param length Length in seconds how long the hud "voiceindicator" is shown. + * @param pitch The pitch of the audiofile. + * @return True on success, false on failure. + */ +stock bool Client_RawAudioToAll(int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) +{ + Handle message = StartMessageAll("RawAudio"); + + if (message == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(message, "pitch", pitch); + PbSetInt(message, "entidx", emitter); + PbSetFloat(message, "duration", length); + PbSetString(message, "voice_filename", soundfile); + } + else { + BfWriteByte(message, pitch); + BfWriteByte(message, emitter); + BfWriteFloat(message, length); + BfWriteString(message, soundfile); + } + EndMessage(); + + return true; +} + +/** + * Sets an Impulse value for a client (eg: "impulse 100" for flashlight, value would be 100). + * See: http://developer.valvesoftware.com/wiki/Impulse + * + * @param client Client Index + * @param value The impulse command value. + * @return True on success, false on failure. + */ +stock void Client_Impulse(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_nImpulse", value); +} + +/** + * Gets the offset for a client's weapon list (m_hMyWeapons). + * The offset will saved globally for optimization. + * + * @param client Client Index. + * @return Weapon list offset or -1 on failure. + */ +stock int Client_GetWeaponsOffset(int client) +{ + static int offset = -1; + + if (offset == -1) { + offset = FindDataMapInfo(client, "m_hMyWeapons"); + } + + return offset; +} + +/** + * Gets the current/active weapon of a client + * + * @param client Client Index. + * @return Weapon Index or INVALID_ENT_REFERENCE if the client has no active weapon. + */ +stock int Client_GetActiveWeapon(int client) +{ + int weapon = GetEntPropEnt(client, Prop_Data, "m_hActiveWeapon"); + + if (!Entity_IsValid(weapon)) { + return INVALID_ENT_REFERENCE; + } + + return weapon; +} + +/** + * Gets the classname and entity index of the current/active weapon of a client. + * + * @param client Client Index. + * @param buffer String Buffer to store the weapon's classname. + * @param size Max size of String: buffer. + * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise + */ +stock int Client_GetActiveWeaponName(int client, char[] buffer, int size) +{ + int weapon = Client_GetActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + buffer[0] = '\0'; + return INVALID_ENT_REFERENCE; + } + + Entity_GetClassName(weapon, buffer, size); + + return weapon; +} + +/** + * Changes the active/current weapon of a player by Index. + * Note: No changing animation will be played ! + * + * @param client Client Index. + * @param weapon Index of a valid weapon. + */ +stock void Client_SetActiveWeapon(int client, int weapon) +{ + SetEntPropEnt(client, Prop_Data, "m_hActiveWeapon", weapon); + ChangeEdictState(client, FindDataMapInfo(client, "m_hActiveWeapon")); +} + +/** + * Changes the active weapon the client is holding. + * Note: No changing animation will be played ! + * + * @param client Client Index. + * @param className Weapon Classname. + * @return True on success, false on failure. + */ +stock bool Client_ChangeWeapon(int client, const char[] className) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + Client_SetActiveWeapon(client,weapon); + + return true; +} + +/** + * Changes the active weapon to the last. + * If the last active weapon can't be found, the default weapon is taken. + * If the default weapon can't be found, the first weapon in the list is taken. + * If the first weapon can't be found, INVALID_ENT_REFERENCEE is returned. + * + * @param client Client Index. + * @return Entity Index or, INVALID_ENT_REFERENCE. + */ +stock int Client_ChangeToLastWeapon(int client) +{ + int weapon = Client_GetLastActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Client_GetDefaultWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Client_GetFirstWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + } + } + + Client_SetActiveWeapon(client, weapon); + + return weapon; +} + +/** + * Gets the last active weapon of a client. + * + * @param client Client Index. + * @return Entity Index of the weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GetLastActiveWeapon(int client) +{ + int weapon = GetEntPropEnt(client, Prop_Data, "m_hLastWeapon"); + + if (!Entity_IsValid(weapon)) { + return INVALID_ENT_REFERENCE; + } + + return weapon; +} + +/** + * Gets the classname of the last active weapon of a client. + * + * @param client Client Index. + * @param buffer Buffer to store the weapon classname. + * @param size Max size of String: buffer. + * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise + */ +stock int Client_GetLastActiveWeaponName(int client, char[] buffer, int size) +{ + int weapon = Client_GetLastActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + buffer[0] = '\0'; + return INVALID_ENT_REFERENCE; + } + + Entity_GetClassName(weapon, buffer, size); + + return weapon; +} + +/** + * Sets the last active weapon of a client. + * + * @param client Client Index. + * @param weapon Entity Index of a weapon. + * @noreturn + */ +stock void Client_SetLastActiveWeapon(int client, int weapon) +{ + SetEntPropEnt(client, Prop_Data, "m_hLastWeapon", weapon); + ChangeEdictState(client, FindDataMapInfo(client, "m_hLastWeapon")); +} + +/** + * Equips (attaches) a weapon to a client. + * + * @param client Client Index. + * @param weapon Entity Index of the weapon. + * @param switchTo If true, the client will switch to that weapon (make it active). + */ +stock void Client_EquipWeapon(int client, int weapon, bool switchTo=false) +{ + EquipPlayerWeapon(client, weapon); + + if (switchTo) { + Client_SetActiveWeapon(client, weapon); + } +} + +/** + * Savly detaches a clients weapon, to remove it as example. + * The client will select his last weapon when detached. + * + * @param client Client Index. + * @param weapon Entity Index of the weapon, you'd like to detach. + * @return True on success, false otherwise. + */ +stock bool Client_DetachWeapon(int client, int weapon) +{ + if (!RemovePlayerItem(client, weapon)) { + return false; + } + + if (Client_GetActiveWeapon(client) == INVALID_ENT_REFERENCE) { + Client_ChangeToLastWeapon(client); + } + + return true; +} + +/** + * Gives a client a weapon. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param switchTo If set to true, the client will switch the active weapon to the new weapon. + * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GiveWeapon(int client, const char[] className, bool switchTo=true) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Weapon_CreateForOwner(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + } + + Client_EquipWeapon(client, weapon, switchTo); + + return weapon; +} + +/** + * Gives a client a weapon and ammo for that weapon. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param switchTo If set to true, the client will switch the active weapon to the new weapon. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GiveWeaponAndAmmo(int client, const char[] className, bool switchTo=true, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) +{ + int weapon = Client_GiveWeapon(client, className, switchTo); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + + if (secondaryClip != -1) { + Weapon_SetSecondaryClip(weapon, secondaryClip); + } + + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return weapon; +} + +/** + * Removes a weapon from a client. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param firstOnly If false it loops trough the whole weapon list and deletes all weapons that match the specified classname. + * @param clearAmmo If true, the ammo the client carries for that weapon will be set to 0 (primary and secondary). + * @return True on success, false otherwise. + */ +stock bool Client_RemoveWeapon(int client, const char[] className, bool firstOnly=true, bool clearAmmo=false) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (!Entity_ClassNameMatches(weapon, className)) { + continue; + } + + if (clearAmmo) { + Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); + } + + if (Client_GetActiveWeapon(client) == weapon) { + Client_ChangeToLastWeapon(client); + } + + if (RemovePlayerItem(client, weapon)) { + Entity_Kill(weapon); + } + + if (firstOnly) { + return true; + } + } + + return false; +} + +/** + * Removes all weapons of a client. + * You can specify a weapon it shouldn't remove and if to + * clear the player's ammo for a weapon when it gets removed. + * + * @param client Client Index. + * @param exclude If not empty, this weapon won't be removed from the client. + * @param clearAmmo If true, the ammo the player carries for all removed weapons are set to 0 (primary and secondary). + * @return Number of removed weapons. + */ +stock int Client_RemoveAllWeapons(int client, const char[] exclude="", bool clearAmmo=false) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + int numWeaponsRemoved = 0; + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (exclude[0] != '\0' && Entity_ClassNameMatches(weapon, exclude)) { + Client_SetActiveWeapon(client, weapon); + continue; + } + + if (clearAmmo) { + Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); + } + + if (RemovePlayerItem(client, weapon)) { + Entity_Kill(weapon); + } + + numWeaponsRemoved++; + } + + return numWeaponsRemoved; +} + +/** + * Checks if a client has a specific weapon. + * + * @param client Client Index. + * @param className Weapon Classname. + * @return True if client has the weapon, otherwise false. + */ +stock bool Client_HasWeapon(int client, const char[] className) +{ + int weapon = Client_GetWeapon(client, className); + + return (weapon != INVALID_ENT_REFERENCE); +} + +/** + * Gets the weapon of a client by the weapon's classname. + * + * @param client Client Index. + * @param className Classname of the weapon. + * @return Entity index on success or INVALID_ENT_REFERENCE. + */ +stock int Client_GetWeapon(int client, const char[] className) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + int weapon = INVALID_ENT_REFERENCE; + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (Entity_ClassNameMatches(weapon, className)) { + return weapon; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Gets the weapon of a client by slot number. + * Note: This is incompatible to games that have multiple + * weapons in one slot (eg.: hl2dm). + * + * @param client Client Index. + * @param slot Slot Index. + * @return Entity index on success or INVALID_ENT_REFERENCE. + */ +stock int Client_GetWeaponBySlot(int client, int slot) +{ + return GetPlayerWeaponSlot(client, slot); +} + +/** + * Gets the clients default weapon (Entity Index). + * + * @param client Client Index. + * @return Entity Index on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GetDefaultWeapon(int client) +{ + char weaponName[MAX_WEAPON_STRING]; + if (Client_GetDefaultWeaponName(client, weaponName, sizeof(weaponName))) { + return INVALID_ENT_REFERENCE; + } + + return Client_GetWeapon(client, weaponName); +} + +/** + * Gets the clients default weapon (classname). + * This function doesn't work in all games (maybe only works in hl2dm). + * It will return an empty string if cl_defaultweapon doesn't exist. + * + * @param client Client Index. + * @param buffer Buffer to store the default weapon's classname. + * @param size Max size of string: buffer. + * @return True on success, false otherwise. + */ +stock bool Client_GetDefaultWeaponName(int client, char[] buffer, int size) +{ + if (!GetClientInfo(client, "cl_defaultweapon", buffer, size)) { + buffer[0] = '\0'; + return false; + } + + return true; +} + +/** + * Gets the first weapon of the client's weapon list (m_hMyWeapons). + * Note: This has nothing to do with weapon slots. + * + * @param client Client Index. + * @return Entity Index of the weapon or INVALID_ENT_REFERENCE. + */ +stock int Client_GetFirstWeapon(int client) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + return weapon; + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Gets the number of weapons a client has. + * + * @param client Client Index. + * @return Number of weapons. + */ +stock int Client_GetWeaponCount(int client) +{ + int numWeapons = 0; + + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + numWeapons++; + } + + return numWeapons; +} + +/** + * Checks whether the client is currently reloading his active weapon. + * + * @param client Client Index. + * @return True if client is reloading, false otherwise. + */ +stock bool Client_IsReloading(int client) +{ + int weapon = Client_GetActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + return Weapon_IsReloading(weapon); +} + +/** + * Sets the primary and secondary clip value of a weapon. + * + * @param client Client Index. + * @param classname Classname of a weapon. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponClipAmmo(int client, const char[] className, int primaryClip=-1, int secondoaryClip=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + + if (secondoaryClip != -1) { + Weapon_SetSecondaryClip(weapon, primaryClip); + } + + return true; +} + +/** + * Gets the primary and secondary ammo the player carries for a specific weapon classname. + * + * @param client Client Index. + * @param classname Classname of a weapon. + * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_GetWeaponPlayerAmmo(int client, const char[] className, int &primaryAmmo=-1, int &secondaryAmmo=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + primaryAmmo = GetEntData(client, offset); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + secondaryAmmo = GetEntData(client, offset); + } + + return true; +} + +/** + * Gets the primary and secondary ammo the player carries for a specific weapon index. + * + * @param client Client Index. + * @param weapon Weapon Entity Index. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + */ +stock void Client_GetWeaponPlayerAmmoEx(int client, int weapon, int &primaryAmmo=-1, int &secondaryAmmo=-1) +{ + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + primaryAmmo = GetEntData(client, offset); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + secondaryAmmo = GetEntData(client, offset); + } +} + +/** + * Sets the primary and secondary ammo the player carries for a specific weapon classname. + * + * @param client Client Index. + * @param classname Weapon Classname String. + * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponPlayerAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return true; +} + +/** + * Sets the primary and secondary ammo the player carries for a specific weapon index. + * + * @param client Client Index. + * @param weapon Weapon Entity Index. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + */ +stock void Client_SetWeaponPlayerAmmoEx(int client, int weapon, int primaryAmmo=-1, int secondaryAmmo=-1) +{ + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + SetEntData(client, offset, primaryAmmo, 4, true); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + SetEntData(client, offset, secondaryAmmo, 4, true); + } +} + +/** + * Sets the value from primary and secondary ammo stock, of a client. + * + * @param client Client Index. + * @param className Classname of a weapon. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + if (secondaryClip != -1) { + Weapon_SetSecondaryClip(weapon, secondaryClip); + } + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return true; +} + +/** + * Gets the next weapon of a client, starting at start. + * + * @param client Client Index (must be a valid client ingame). + * @param index Reference to an index variable, will contain the index of the next weapon to check. + * @return Weapon Index or -1 if no more weapons are found. + */ +stock int Client_GetNextWeapon(int client, int &index = 0) +{ + int offset = Client_GetWeaponsOffset(client) + (index * 4); + + int weapon; + while (index < MAX_WEAPONS) { + index++; + + weapon = GetEntDataEnt2(client, offset); + + if (Weapon_IsValid(weapon)) { + return weapon; + } + + offset += 4; + } + + return -1; +} + +/** + * Prints white text to the bottom center of the screen + * for one client. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param client Client Index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if this usermessage doesn't exist. + */ +stock bool Client_PrintHintText(int client, const char[] format, any ...) +{ + Handle userMessage = StartMessageOne("HintText", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + char buffer[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetString(userMessage, "text", buffer); + } + else { + BfWriteByte(userMessage, 1); + BfWriteString(userMessage, buffer); + } + + EndMessage(); + + return true; +} + +/** + * Prints white text to the bottom center of the screen + * for all clients. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintHintTextToAll(const char[] format, any ...) +{ + char buffer[254]; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 2); + Client_PrintHintText(client, buffer); + } +} + +/** + * Prints white text to the right-center side of the screen + * for one client. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param client Client Index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if this usermessage doesn't exist. + */ +stock bool Client_PrintKeyHintText(int client, const char[] format, any ...) +{ + Handle userMessage = StartMessageOne("KeyHintText", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + char buffer[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbAddString(userMessage, "hints", buffer); + } + else { + BfWriteByte(userMessage, 1); + BfWriteString(userMessage, buffer); + } + + EndMessage(); + + return true; +} + +/** + * Prints white text to the right-center side of the screen + * for all clients. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + */ +stock void Client_PrintKeyHintTextToAll(const char[] format, any ...) +{ + char buffer[254]; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 2); + Client_PrintKeyHintText(client, buffer); + } +} + +/** + * Prints a reliable raw chat message to a client in the chat area. + * If the client == 0, the message will printed to server console. + * + * @param client Client Index. + * @param message String Message. + * @param subject Client Index/Subject (normally used for teamcolors) + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + */ +stock void Client_PrintToChatRaw(int client, const char[] message, int subject=0, bool isChat=false) +{ + if (client == 0) { + char buffer[253]; + Color_StripFromChatText(message, buffer, sizeof(buffer)); + PrintToServer(buffer); + return; + } + + static bool sayText2_supported = true; + static bool sayText2_checked = false; + + if (!sayText2_checked) { + + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { + sayText2_supported = false; + } + + sayText2_checked = true; + } + + Handle userMessage = INVALID_HANDLE; + + if (sayText2_supported) { + userMessage = StartMessageOne("SayText2", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "ent_idx", subject); + PbSetBool(userMessage, "chat", isChat); + PbSetString(userMessage, "msg_name", message); + + // psychonic: Furthermore, some usermessages with repeated field, + // such as the commonly-used SayText2, expected an undocumented + // specific number of values added, else the client will crash when receiving. + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + } + else { + BfWriteByte(userMessage , subject); + BfWriteByte(userMessage , isChat); + BfWriteString(userMessage , message); + } + } + else { + userMessage = StartMessageOne("SayText", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "ent_idx", subject); + PbSetString(userMessage, "text", message); + PbSetBool(userMessage, "chat", isChat); + } + else { + BfWriteByte(userMessage , subject); + BfWriteString(userMessage , message); + // For DoD:S nickname coloring + BfWriteByte(userMessage , -1); + } + } + + EndMessage(); +} + +/** + * Prints a reliable chat message to one client in the chat area. + * Allows up to 253 Characters (including \0) to be printed. + * Supports chat color tags (see: colors.inc). + * + * @param client Client Index. + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChat(int client, bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 4); + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + + Color_ChatClearSubject(); +} + +static int printToChat_excludeclient = -1; + +/** + * Exclude a client from the next call to a Client_PrintToChat function. + * + * @param client Client Index. + * @noreturn + */ +stock void Client_PrintToChatExclude(int client) +{ + printToChat_excludeclient = client; +} + +/** + * Prints a reliable chat message to all clients in the chat area. + * Allows up to 253 Characters (including \0) to be printed. + * Supports chat color tags (see: colors.inc). + * + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChatAll(bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + int + subject, + language, + lastLanguage = -1; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToChat_excludeclient) { + printToChat_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + lastLanguage = language; + } + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + } + + Color_ChatClearSubject(); +} + +/** + * Prints a reliable chat message to the specified clients in the chat area. + * Allows up to 253 Characters (including \0) to be print. + * Supports chat color tags (see: colors.inc). + * + * @param clients Client Array. + * @param numClients Number of clients in the client array. + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChatEx(int[] clients, int numClients, bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + int + client, + subject, + language, + lastLanguage = -1; + + for (int i=0; i < numClients; i++) { + + client = clients[i]; + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToChat_excludeclient) { + printToChat_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 5); + subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + lastLanguage = language; + } + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + } + + Color_ChatClearSubject(); +} + +enum ClientHudPrint { + ClientHudPrint_Notify = 1, + ClientHudPrint_Console, + ClientHudPrint_Talk, + Client_HudPrint_Center +}; + +/** + * Prints a relieable message to the client's console. + * Allows up to 254 Characters (including \0) to be print (253 for talk). + * Supports chat color tags (see: colors.inc, only available in Left 4 Dead (2) or higher). + * Chat colors are stripped automatically if not supported. + * + * @param clients Client Array. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToConsole(int client, const char[] format, any ...) +{ + char buffer[512]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + Client_Print(client, ClientHudPrint_Console, buffer); +} + +/** + * Prints a relieable message to the client's console. + * Allows up to 254 Characters (including \0) to be print. + * Supports chat color tags in chat & console (see: colors.inc). + * Chat colors are stripped automatically if not supported in the destination. + * + * @param clients Client Array. + * @param destination Destination place (use onf of the ClientHudPrint_) + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_Print(int client, ClientHudPrint destination, const char[] format, any ...) +{ + char buffer[512], buffer2[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 4); + + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + if (destination == ClientHudPrint_Talk) { + Client_PrintToChatRaw(client, buffer2, subject, false); + return; + } + + EngineVersion engineVersion = GetEngineVersion(); + if (client == 0 || + destination != ClientHudPrint_Console || + (destination == ClientHudPrint_Console + && engineVersion != Engine_Left4Dead && engineVersion != Engine_Left4Dead2)) + { + Color_StripFromChatText(buffer2, buffer2, sizeof(buffer2)); + + if (client == 0) { + PrintToServer(buffer2); + return; + } + } + + Handle userMessage = INVALID_HANDLE; + userMessage = StartMessageOne("TextMsg", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "msg_dst", view_as(destination)); + PbAddString(userMessage, "params", buffer2); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + } + else { + BfWriteByte(userMessage , view_as(destination)); + BfWriteString(userMessage , buffer2); + } + + EndMessage(); +} + +/** + * Replies to a message in a command. + * A client index of 0 will use PrintToServer(). + * If the command was from the console, Client_PrintToConsole() is used. + * If the command was from chat, Client_PrintToChat() is used. + * + * @param client Client Index. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_Reply(int client, const char[] format, any ...) +{ + char buffer[255]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + Client_PrintToConsole(client, buffer); + } + else { + Client_PrintToChat(client, false, buffer); + } +} + +#define SHAKE_START 0 // Starts the screen shake for all players within the radius. +#define SHAKE_STOP 1 // Stops the screen shake for all players within the radius. +#define SHAKE_AMPLITUDE 2 // Modifies the amplitude of an active screen shake for all players within the radius. +#define SHAKE_FREQUENCY 3 // Modifies the frequency of an active screen shake for all players within the radius. +#define SHAKE_START_RUMBLEONLY 4 // Starts a shake effect that only rumbles the controller, no screen effect. +#define SHAKE_START_NORUMBLE 5 // Starts a shake that does NOT rumble the controller. + +/** + * Shakes a client's screen with the specified amptitude, + * frequency & duration. + * + * @param client Client Index. + * @param command Shake Mode, use one of the SHAKE_ definitions. + * @param amplitude Shake magnitude/amplitude. + * @param frequency Shake noise frequency. + * @param duration Shake lasts this long. + * @return True on success, false otherwise. + */ +stock bool Client_Shake(int client, int command=SHAKE_START, float amplitude=50.0, float frequency=150.0, float duration=3.0) +{ + if (command == SHAKE_STOP) { + amplitude = 0.0; + } + else if (amplitude <= 0.0) { + return false; + } + + Handle userMessage = StartMessageOne("Shake", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "command", command); + PbSetFloat(userMessage, "local_amplitude", amplitude); + PbSetFloat(userMessage, "frequency", frequency); + PbSetFloat(userMessage, "duration", duration); + } + else { + BfWriteByte(userMessage, command); // Shake Command + BfWriteFloat(userMessage, amplitude); // shake magnitude/amplitude + BfWriteFloat(userMessage, frequency); // shake noise frequency + BfWriteFloat(userMessage, duration); // shake lasts this long + } + + EndMessage(); + + return true; +} + +/** + * Checks whether the client is a generic admin. + * + * @param Client Index. + * @return True if the client is a generic admin, false otheriwse. + */ +stock bool Client_IsAdmin(int client) +{ + AdminId adminId = GetUserAdmin(client); + + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + return GetAdminFlag(adminId, Admin_Generic); +} + +/** + * Checks whether a client has certain admin flags + * + * @param Client Index. + * @return True if the client has the admin flags, false otherwise. + */ +stock bool Client_HasAdminFlags(int client, int flags=ADMFLAG_GENERIC) +{ + AdminId adminId = GetUserAdmin(client); + + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + return GetAdminFlags(adminId, Access_Effective) & flags == flags; +} + +/** + * Returns whether a player is in a specific admin group. + * + * @param client Client Index. + * @param groupName Admin group name to check. + * @param caseSensitive True if the group check has to be case sensitive, false otherwise. + * @return True if the client is in the admin group, false otherwise. + */ +stock bool Client_IsInAdminGroup(int client, const char[] groupName, bool caseSensitive=true) +{ + AdminId adminId = GetUserAdmin(client); + + // Validate id. + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + // Get number of groups. + int count = GetAdminGroupCount(adminId); + + // Validate number of groups. + if (count == 0) { + return false; + } + + char groupname[64]; + + // Loop through each group. + for (int i = 0; i < count; i++) { + // Get group name. + GetAdminGroup(adminId, i, groupname, sizeof(groupname)); + + // Compare names. + if (StrEqual(groupName, groupname, caseSensitive)) { + return true; + } + } + + // No match. + return false; +} + +/** + * Checks if the client is currently looking at the wall in front + * of him with the given distance as max value. + * + * @param client Client Index. + * @param distance Max Distance as Float value. + * @return True if he is looking at a wall, false otherwise. + */ +stock bool Client_IsLookingAtWall(int client, float distance=40.0) { + + float posEye[3], posEyeAngles[3]; + bool isClientLookingAtWall = false; + + GetClientEyePosition(client, posEye); + GetClientEyeAngles(client, posEyeAngles); + + posEyeAngles[0] = 0.0; + + Handle trace = TR_TraceRayFilterEx(posEye, posEyeAngles, CONTENTS_SOLID, RayType_Infinite, _smlib_TraceEntityFilter); + + if (TR_DidHit(trace)) { + + if (TR_GetEntityIndex(trace) > 0) { + delete trace; + return false; + } + + float posEnd[3]; + + TR_GetEndPosition(posEnd, trace); + + if (GetVectorDistance(posEye, posEnd, true) <= (distance * distance)) { + isClientLookingAtWall = true; + } + } + + delete trace; + + return isClientLookingAtWall; +} + +public bool _smlib_TraceEntityFilter(int entity, int contentsMask) +{ + return entity == 0; +} + +/** + * Gets a client's class. + * Currently supported games are: TF2, Dark Messiah. + * Other games maybe work too, but are not tested. + * + * @param client Client Index. + * @return Class Index. + */ +stock int Client_GetClass(int client) +{ + if (GetEngineVersion() == Engine_DarkMessiah) { + return GetEntProp(client, Prop_Send, "m_iPlayerClass"); + } + + return GetEntProp(client, Prop_Send, "m_iClass"); +} + +/** + * Sets a client's class. + * Currently supported games are: TF2, Dark Messiah. + * Other games maybe work too, but are not tested. + * + * @param client Client Index. + * @param playerClass The class number to set the player to. Depends on game. + * @param persistant If true changes the players desired class so the change stays after death (probably TF2 only). + */ +stock void Client_SetClass(int client, int playerClass, bool persistant=false) +{ + if (GetEngineVersion() == Engine_DarkMessiah) { + SetEntProp(client, Prop_Send, "m_iPlayerClass", playerClass); + } else { + SetEntProp(client, Prop_Send, "m_iClass", playerClass); + + if (persistant) { + SetEntProp(client, Prop_Send, "m_iDesiredPlayerClass", playerClass); + } + } +} + +/** + * Returns what buttons are currently pressed by the client. + * + * @param client Client Index. + * @return Buttons as bitflag. + */ +stock int Client_GetButtons(int client) +{ + return GetClientButtons(client); +} + +/** + * Sets the client buttons. + * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_SetButtons(int client, int buttons) +{ + SetEntProp(client, Prop_Data, "m_nButtons", buttons); +} + +/** + * Adds buttons to the already pressed buttons. + * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_AddButtons(int client, int buttons) +{ + int newButtons = Client_GetButtons(client); + newButtons |= buttons; + Client_SetButtons(client, newButtons); +} + +/** + * Removes buttons from the already pressed buttons. + * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_RemoveButtons(int client, int buttons) +{ + int newButtons = Client_GetButtons(client); + newButtons &= ~buttons; + Client_SetButtons(client, newButtons); +} + +/** + * Clears all buttons. + * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + */ +stock void Client_ClearButtons(int client) +{ + Client_SetButtons(client,0); +} + +/** + * Returns if the given buttons are pressed by the client or not. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + * @return True if the buttons are pressed otherwise false. + */ +stock bool Client_HasButtons(int client, int buttons) +{ + return Client_GetButtons(client) & buttons == buttons; +} + +/** + * Returns only the buttons that have changed since the last call of this. + * Example usage: Within OnPlayerRunCmd use this function to call another function only once when a player pressed or released a button. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + * @return + */ +stock int Client_GetChangedButtons(int client) +{ + static int oldButtons[MAXPLAYERS+1] = {0,...}; + + int buttons = Client_GetButtons(client); + int changedButtons = buttons ^ oldButtons[client]; + + oldButtons[client] = buttons; + + return changedButtons; +} + +/** + * Sets the client's maxspeed to the given value (in units per second) + * + * @param Client Client Index + * @param maxspeed the maximum speed the client can move + */ +stock void Client_SetMaxSpeed(int client, float value) +{ + Entity_SetMaxSpeed(client, value); +} + +/** + * Shows a screen overlay tp a client. + * There can only be one overlay at a time. + * If you want to clear the overlay, pass + * an empty string to this function. + * + * @param Client Client Index. + * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. + * @noreturn + */ +stock void Client_SetScreenOverlay(int client, const char[] path) +{ + ClientCommand(client, "r_screenoverlay \"%s\"", path); +} + +/** + * Shows a screen overlay to all clients. + * There can only be one overlay at a time. + * If you want to clear the overlay, pass + * an empty string to this function. + * + * @param Client Client Index. + * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. + * @noreturn + */ +stock void Client_SetScreenOverlayForAll(const char[] path) +{ + LOOP_CLIENTS(client, CLIENTFILTER_INGAME | CLIENTFILTER_NOBOTS) { + Client_SetScreenOverlay(client, path); + } +} + +/** + * Mutes a client's voice + * + * @param Client Client Index. + * @noreturn + */ +stock void Client_Mute(int client) +{ + SetClientListeningFlags(client, VOICE_MUTED); +} + +/** + * UnMutes a client's voice + * Code copied from basecomm.sp + * + * @param Client Client Index. + */ +stock void Client_UnMute(int client) +{ + static ConVar cvDeadTalk = null; + + if (cvDeadTalk == INVALID_HANDLE) { + cvDeadTalk = FindConVar("sm_deadtalk"); + } + + if (cvDeadTalk == INVALID_HANDLE) { + SetClientListeningFlags(client, VOICE_NORMAL); + } + else { + if (cvDeadTalk.IntValue == 1 && !IsPlayerAlive(client)) { + SetClientListeningFlags(client, VOICE_LISTENALL); + } + else if (cvDeadTalk.IntValue == 2 && !IsPlayerAlive(client)) { + SetClientListeningFlags(client, VOICE_TEAM); + } + else { + SetClientListeningFlags(client, VOICE_NORMAL); + } + } +} + +/** + * Checks if a client's voice is muted + * + * @param Client Client Index. + * @return True if the client is muted, false otherwise. + */ +stock bool Client_IsMuted(int client) +{ + return GetClientListeningFlags(client) & VOICE_MUTED > 0; +} + +/** + * Checks if a client matches the specified flag filter. + * Use one of the CLIENTFILTER_ constants. + * Note that this already checks if the client is ingame or connected + * so you don't have to do that yourself. + * This function is optimized to make as less native calls as possible :) + * + * @param Client Client Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return True if the client if the client matches, false otherwise. + */ +stock bool Client_MatchesFilter(int client, int flags) +{ + bool isIngame = false; + + if (flags >= CLIENTFILTER_INGAME) { + isIngame = IsClientInGame(client); + + if (isIngame) { + if (flags & CLIENTFILTER_NOTINGAME) { + return false; + } + } + else { + return false; + } + } + else if (!IsClientConnected(client)) { + return false; + } + + if (!flags) { + return true; + } + + if (flags & CLIENTFILTER_INGAMEAUTH) { + flags |= CLIENTFILTER_INGAME | CLIENTFILTER_AUTHORIZED; + } + + if (flags & CLIENTFILTER_BOTS && !IsFakeClient(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOBOTS && IsFakeClient(client)) { + return false; + } + + if (flags & CLIENTFILTER_ADMINS && !Client_IsAdmin(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOADMINS && Client_IsAdmin(client)) { + return false; + } + + if (flags & CLIENTFILTER_AUTHORIZED && !IsClientAuthorized(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOTAUTHORIZED && IsClientAuthorized(client)) { + return false; + } + + if (isIngame) { + + if (flags & CLIENTFILTER_ALIVE && !IsPlayerAlive(client)) { + return false; + } + + if (flags & CLIENTFILTER_DEAD && IsPlayerAlive(client)) { + return false; + } + + if (flags & CLIENTFILTER_SPECTATORS && GetClientTeam(client) != TEAM_SPECTATOR) { + return false; + } + + if (flags & CLIENTFILTER_NOSPECTATORS && GetClientTeam(client) == TEAM_SPECTATOR) { + return false; + } + + if (flags & CLIENTFILTER_OBSERVERS && !IsClientObserver(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOOBSERVERS && IsClientObserver(client)) { + return false; + } + + if (flags & CLIENTFILTER_TEAMONE && GetClientTeam(client) != TEAM_ONE) { + return false; + } + + if (flags & CLIENTFILTER_TEAMTWO && GetClientTeam(client) != TEAM_TWO) { + return false; + } + } + + return true; +} + +/** + * Gets all clients matching the specified flags filter. + * + * @param client Client Array, size should be MaxClients or MAXPLAYERS + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return The number of clients stored in the array + */ +stock int Client_Get(int[] clients, int flags=CLIENTFILTER_ALL) +{ + int x=0; + for (int client = 1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + clients[x++] = client; + } + + return x; +} + +/** + * Gets a random client matching the specified flags filter. + * + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client Index or -1 if no client was found + */ +stock int Client_GetRandom(int flags=CLIENTFILTER_ALL) +{ + int[] clients = new int[MaxClients]; + int num = Client_Get(clients, flags); + + if (num == 0) { + return -1; + } + else if (num == 1) { + return clients[0]; + } + + int random = Math_GetRandomInt(0, num-1); + + return clients[random]; +} + +/** + * Gets a client matching certain flags starting at start. + * + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @param start Start Index. + * @return Client Index or -1 if no client was found + */ +stock int Client_GetNext(int flags, int start=1) +{ + for (int client=start; client <= MaxClients; client++) { + + if (Client_MatchesFilter(client, flags)) { + return client; + } + } + + return -1; +} + +/** + * Retrieves the time duration a client played on the current map. + * + * @param client Client Index. + * @return Time in seconds as Float + */ +stock float Client_GetMapTime(int client) +{ + float fClientTime = GetClientTime(client); + float fGameTime = GetGameTime(); + + return (fClientTime < fGameTime) ? fClientTime : fGameTime; +} + +/** + * Gets client money value (for games like Counter-Strike:Source). + * + * @param client Client Index. + * @return Money value from the client. + */ +stock int Client_GetMoney(int client) +{ + return GetEntProp(client, Prop_Send, "m_iAccount"); +} + +/** + * Sets client money value (for games like Counter-Strike:Source). + * + * @param client Client Index. + * @param value Money value to set. + */ +stock void Client_SetMoney(int client, int value) +{ + SetEntProp(client, Prop_Send, "m_iAccount", value); +} + +/** + * Gets a client's observers. + * + * @param client Client Index. + * @param observers Array with size of MaxClients or MAXPLAYERS. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Number of observers found. + */ +stock int Client_GetObservers(int client, int[] observers, int flags=CLIENTFILTER_ALL) +{ + int count = 0; + + LOOP_CLIENTS(player, CLIENTFILTER_OBSERVERS | flags) { + + if (Client_GetObserverTarget(player) == client) { + observers[count++] = player; + } + } + + return count; +} + +static float getPlayersInRadius_distances[MAXPLAYERS+1]; + +/** + * Gets all players near a player in a certain radius and + * orders the players by distance (optional). + * + * @param client Client Index. + * @param clients Array with size of MaxClients or MAXPLAYERS. + * @param radius radius Float (max distance) + * @param orderByDistance Set to true to order the clients by distance, false otherwise. + * @return Number of clients found. + */ +stock int Client_GetPlayersInRadius(int client, int[] clients, float radius, bool orderByDistance=true) +{ + float origin_client[3], distance; + int count=0; + + Entity_GetAbsOrigin(client, origin_client); + + LOOP_CLIENTS(player, CLIENTFILTER_INGAME) { + + if (player == client) { + continue; + } + + distance = Entity_GetDistanceOrigin(player, origin_client); + + if (distance <= radius) { + clients[count++] = player; + + if (orderByDistance) { + getPlayersInRadius_distances[player] = distance; + } + } + } + + if (orderByDistance) { + SortCustom1D(clients, count, __smlib_GetPlayersInRadius_Sort); + } + + return count; +} + +public int __smlib_GetPlayersInRadius_Sort(int player1, int player2, const int[] clients, Handle hndl) +{ + return FloatCompare(getPlayersInRadius_distances[player1], getPlayersInRadius_distances[player2]); +} + +/** + * Gets the next player observing client starting at start. + * + * @param client Client Index (Observer Target) + * @param start Start Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client Index or -1 if no client was found + */ +stock int Client_GetNextObserver(int client, int start=1, int flags=CLIENTFILTER_ALL) +{ + for (int player=start; player <= MaxClients; player++) { + + if (Client_MatchesFilter(player, CLIENTFILTER_OBSERVERS | flags)) { + + if (Client_GetObserverTarget(player) == client) { + return player; + } + } + } + + return -1; +} + +/** + * Searchs and returns the game's player_manager entity. + * This should be called on every map start. + * + * @return player_manager entity or INVALID_ENT_REFERENCE if not found. + */ +stock int Client_GetPlayerManager() +{ + static int player_manager = INVALID_ENT_REFERENCE; + + if (player_manager != INVALID_ENT_REFERENCE) { + + if (Entity_IsValid(player_manager)) { + return player_manager; + } + else { + player_manager = INVALID_ENT_REFERENCE; + } + } + + int maxEntities = GetMaxEntities(); + + for (int entity=MaxClients+1; entity < maxEntities; entity++) { + + if (!Entity_IsValid(entity)) { + continue; + } + + if (Entity_ClassNameMatches(entity, "player_manager", true)) { + player_manager = EntIndexToEntRef(entity); + + return player_manager; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Sets the client's ping as displayed in the scoreboards. + * Should be called OnGameFrame. + * + * @param client Client Index + * @param start New ping value. + * @return True on sucess, false otherwise. + */ +stock int Client_SetPing(int client, int value) +{ + int player_manager = Client_GetPlayerManager(); + + static int offset = -1; + + if (offset== -1) { + offset = GetEntSendPropOffs(player_manager, "m_iPing", true); + + if (offset == -1) { + return false; + } + } + + SetEntData(player_manager, offset + (client * 4), value, 4, true); + + return true; +} + +static int printToTop_excludeclient = -1; + +/** + * Exclude a client from the next call to a Client_PrintToTop function. + * + * @param client Client Index. + * @noreturn + */ +stock void Client_PrintToTopExclude(int client) +{ + printToTop_excludeclient = client; +} + +/** + * Prints colored text to the top left of the screen + * for one client. Does not work in all games. + * Line Breaks can't be done. + * + * @param client Client Index. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param text Text to print to. + * @return True on success, false if the key value for the dialog couldn't be created or closed. + */ +stock bool Client_PrintToTopRaw(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] text) +{ + //message line max 50 + //overline: 39*_ + //underline: 44*T + KeyValues keyValue = CreateKeyValues("Stuff", "title", text); + + if (keyValue == INVALID_HANDLE) { + return false; + } + + KvSetColor(keyValue, "color", r, g, b, a); + KvSetNum(keyValue, "level", 1); + KvSetNum(keyValue, "time", RoundToFloor(duration)); + + CreateDialog(client, keyValue, DialogType_Msg); + delete keyValue; + + return true; +} + +/** + * Prints colored text to the top left of the screen + * for one client. Does not work in all games. + * Line Breaks can't be done. + * + * @param client Client Index. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if the key value for the dialog couldn't be created or closed. + */ +stock bool Client_PrintToTop(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 8); + + return Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); +} + +/** + * Prints colored text to the top left of the screen + * to all clients. Does not work in all games. + * Line Breaks can't be done. + * + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToTopAll(int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + int + language, + lastLanguage = -1; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToTop_excludeclient) { + printToTop_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 7); + + lastLanguage = language; + } + + Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); + } +} + +/** + * Prints colored text to the top left of the screen + * to specified clients. Does not work in all games. + * Line Breaks can't be done. + * + * @param clients Client Array. + * @param numClients Number of clients in the clients array. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToTopEx(int[] clients, int numClients, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + int + client, + language, + lastLanguage = -1; + + for (int i=0; i < numClients; i++) { + + client = clients[i]; + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToTop_excludeclient) { + printToTop_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 9); + + lastLanguage = language; + } + + Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); + } +} + +/** + * Opens the scoreboard for a specific client + * + * @tested csgo + * @param client Client index + */ +stock void Client_ShowScoreboard(int client, int flags=USERMSG_RELIABLE | USERMSG_BLOCKHOOKS) +{ + Handle handle = StartMessageOne("VGUIMenu", client, flags); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && + GetUserMessageType() == UM_Protobuf) { + + PbSetString(handle, "name", "scores"); + PbSetBool(handle, "show", true); + } + else { + BfWriteString(handle, "scores"); + BfWriteByte(handle, 1); // Show + BfWriteByte(handle, 0); // subkeys count + } + + EndMessage(); +} diff --git a/scripting/include/smlib/colors.inc b/scripting/include/smlib/colors.inc new file mode 100644 index 0000000..9872227 --- /dev/null +++ b/scripting/include/smlib/colors.inc @@ -0,0 +1,575 @@ +#if defined _smlib_colors_included + #endinput +#endif +#define _smlib_colors_included + +#include +#include +#include + +#define CHATCOLOR_NOSUBJECT -2 +#define SMLIB_COLORS_GAMEDATAFILE "smlib_colors.games" + +enum ChatColorSubjectType +{ + ChatColorSubjectType_none = -3, + + // Subject/Team colors + ChatColorSubjectType_player = -2, + ChatColorSubjectType_undefined = -1, + ChatColorSubjectType_world = 0 + // Anything higher is a specific team +} + +enum struct ChatColorInfo +{ + int ChatColorInfo_Code; + int ChatColorInfo_Alternative; + bool ChatColorInfo_Supported; + ChatColorSubjectType ChatColorInfo_SubjectType; +} + +enum ChatColor +{ + ChatColor_Normal, + ChatColor_Orange, + ChatColor_Red, + ChatColor_RedBlue, + ChatColor_Blue, + ChatColor_BlueRed, + ChatColor_Team, + ChatColor_Lightgreen, + ChatColor_Gray, + ChatColor_Green, + ChatColor_Olivegreen, + ChatColor_Black, + ChatColor_MAXCOLORS +} + +static char chatColorTags[][] = { + "N", // Normal + "O", // Orange + "R", // Red + "RB", // Red, Blue + "B", // Blue + "BR", // Blue, Red + "T", // Team + "L", // Light green + "GRA", // Gray + "G", // Green + "OG", // Olive green + "BLA" // Black +}; + +static char chatColorNames[][] = { + "normal", // Normal + "orange", // Orange + "red", // Red + "redblue", // Red, Blue + "blue", // Blue + "bluered", // Blue, Red + "team", // Team + "lightgreen", // Light green + "gray", // Gray + "green", // Green + "olivegreen", // Olive green + "black" // Black +}; + +static ChatColorInfo chatColorInfo[ChatColor_MAXCOLORS]; + +static bool checkTeamPlay = false; +static ConVar mp_teamplay = null; +static bool isSayText2_supported = true; +static int chatSubject = CHATCOLOR_NOSUBJECT; + +/** + * Sets the subject (a client) for the chat color parser. + * Call this before Color_ParseChatText() or Client_PrintToChat(). + * + * @param client Client Index/Subject + */ +stock void Color_ChatSetSubject(int client) +{ + chatSubject = client; +} + +/** + * Gets the subject used for the chat color parser. + * + * @return Client Index/Subject, or CHATCOLOR_NOSUBJECT if none + */ +stock int Color_ChatGetSubject() +{ + return chatSubject; +} + +/** + * Clears the subject used for the chat color parser. + * Call this after Color_ParseChatText(). + */ +stock void Color_ChatClearSubject() +{ + chatSubject = CHATCOLOR_NOSUBJECT; +} + +/** + * Parses a chat string and converts all color tags to color codes. + * This is a very powerful function that works recursively over the color information + * table. The support colors are hardcoded, but can be overriden for each game by + * creating the file gamedata/smlib_colors.games.txt. + * + * @param str Chat String + * @param subject Output Buffer + * @param size Output Buffer size + * @return Returns a value for the subject + */ +stock int Color_ParseChatText(const char[] str, char[] buffer, int size) +{ + bool inBracket = false; + int x, x_buf, x_tag; + int subject = CHATCOLOR_NOSUBJECT; + + char sTag[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char colorCode[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char currentColor[10] = "\x01"; // Initialize with normal color + + size--; + + // Every chat message has to start with a + // color code, otherwise it will ignore all colors. + buffer[x_buf++] = '\x01'; + + while (str[x] != '\0') { + + if (size == x_buf) { + break; + } + + char character = str[x++]; + + if (inBracket) { + // We allow up to 9 characters in the tag (#RRGGBBAA) + if (character == '}' || x_tag > 9) { + inBracket = false; + sTag[x_tag] = '\0'; + x_tag = 0; + + if (character == '}') { + Color_TagToCode(sTag, subject, colorCode); + + if (colorCode[0] == '\0') { + // We got an unknown tag, ignore this + // and forward it to the buffer. + + // Terminate buffer with \0 so Format can handle it. + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s}", buffer, sTag); + + // We 'r done here + continue; + } + else if (!StrEqual(colorCode, currentColor)) { + // If we are already using this color, + // we don't need to set it again. + + // Write the color code to our buffer. + // x_buf will be increased by the number of cells written. + x_buf += strcopy(buffer[x_buf], size - x_buf, colorCode); + + // Remember the current color. + strcopy(currentColor, sizeof(currentColor), colorCode); + } + } + else { + // If the tag character limit exceeds 9, + // we have to do something. + + // Terminate buffer with \0 so Format can handle it. + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s%c", buffer, sTag, character); + } + } + else if (character == '{' && !x_tag) { + buffer[x_buf++] = '{'; + inBracket = false; + } + else { + sTag[x_tag++] = character; + } + } + else if (character == '{') { + inBracket = true; + } + else { + buffer[x_buf++] = character; + } + } + + // Write remaining text to the buffer, + // if we have been inside brackets. + if (inBracket) { + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s", buffer, sTag); + } + + buffer[x_buf] = '\0'; + + return subject; +} + +/** + * Converts a chat color tag to its code character. + * + * @param tag Color Tag String. + * @param subject Subject variable to pass + * @param result The result as character sequence (string). This will be \0 if the tag is unkown. + */ +stock void Color_TagToCode(const char[] tag, int &subject=-1, char result[10]) +{ + // Check if the tag starts with a '#'. + // We will handle it has RGB(A)-color code then. + if (tag[0] == '#') { + int length_tag = strlen(tag); + switch (length_tag - 1) { + // #RGB -> \07RRGGBB + case 3: { + FormatEx( + result, sizeof(result), "\x07%c%c%c%c%c%c", + tag[1], tag[1], tag[2], tag[2], tag[3], tag[3] + ); + } + // #RGBA -> \08RRGGBBAA + case 4: { + FormatEx( + result, sizeof(result), "\x08%c%c%c%c%c%c%c%c", + tag[1], tag[1], tag[2], tag[2], tag[3], tag[3], tag[4], tag[4] + ); + } + // #RRGGBB -> \07RRGGBB + case 6: { + FormatEx(result, sizeof(result), "\x07%s", tag[1]); + } + // #RRGGBBAA -> \08RRGGBBAA + case 8: { + FormatEx(result, sizeof(result), "\x08%s", tag[1]); + } + default: { + result[0] = '\0'; + } + } + + return; + } + else { + // Try to handle this string as color name + int n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag); + + // Check if this tag is invalid + if (n == -1) { + result[0] = '\0'; + return; + } + + // Check if the color is actually supported 'n stuff. + Color_GetChatColorInfo(n, subject); + + result[0] = chatColorInfo[n].ChatColorInfo_Code; + result[1] = '\0'; + } + + return; +} + +/** + * Strips all color control characters in a string. + * The Output buffer can be the same as the input buffer. + * Original code by Psychonic, thanks. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void Color_StripFromChatText(const char[] input, char[] output, int size) +{ + int x = 0; + for (int i=0; input[i] != '\0'; i++) { + + if (x+1 == size) { + break; + } + + char character = input[i]; + + if (character > 0x08) { + output[x++] = character; + } + } + + output[x] = '\0'; +} + +/** + * Checks the gamename and sets default values. + * For example if some colors are supported, or + * if a game uses another color code for a specific color. + * All those hardcoded default values can be overriden in + * smlib's color gamedata file. + */ +static stock void Color_ChatInitialize() +{ + static bool initialized = false; + + if (initialized) { + return; + } + + initialized = true; + + // Normal + chatColorInfo[ChatColor_Normal].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Normal].ChatColorInfo_Alternative = -1; /* None */ + chatColorInfo[ChatColor_Normal].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Normal].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Orange + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Alternative = 0; /* None */ + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Red + chatColorInfo[ChatColor_Red].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Red].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Red].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(2); + + // Red, Blue + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Alternative = 4; /* Blue */ + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(2); + + // Blue + chatColorInfo[ChatColor_Blue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Blue].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Blue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(3); + + // Blue, Red + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Alternative = 2; /* Red */ + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(3); + + // Team + chatColorInfo[ChatColor_Team].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Team].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Team].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Team].ChatColorInfo_SubjectType = ChatColorSubjectType_player; + + // Light green + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_SubjectType = ChatColorSubjectType_world; + + // Gray + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_undefined; + + // Green + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Alternative = 0; /* Normal*/ + chatColorInfo[ChatColor_Green].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Green].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Olive green + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Code = '\x05'; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Black + chatColorInfo[ChatColor_Black].ChatColorInfo_Code = '\x06'; + chatColorInfo[ChatColor_Black].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Black].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + char gameFolderName[PLATFORM_MAX_PATH]; + GetGameFolderName(gameFolderName, sizeof(gameFolderName)); + + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = false; + + if (strncmp(gameFolderName, "left4dead", 9, false) != 0 && + !StrEqual(gameFolderName, "cstrike", false) && + !StrEqual(gameFolderName, "tf", false)) + { + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = false; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = false; + } + + if (StrEqual(gameFolderName, "tf", false)) { + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + } + else if (strncmp(gameFolderName, "left4dead", 9, false) == 0) { + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); + + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x05'; + } + else if (StrEqual(gameFolderName, "hl2mp", false)) { + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + + checkTeamPlay = true; + } + else if (StrEqual(gameFolderName, "dod", false)) { + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = false; + } + + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { + isSayText2_supported = false; + } + + char path_gamedata[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, path_gamedata, sizeof(path_gamedata), "gamedata/%s.txt", SMLIB_COLORS_GAMEDATAFILE); + + if (FileExists(path_gamedata)) { + Handle gamedata = INVALID_HANDLE; + + if ((gamedata = LoadGameConfigFile(SMLIB_COLORS_GAMEDATAFILE)) != INVALID_HANDLE) { + + char keyName[32], buffer[6]; + + for (int i=0; i < sizeof(chatColorNames); i++) { + + Format(keyName, sizeof(keyName), "%s_code", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Code = StringToInt(buffer); + } + + Format(keyName, sizeof(keyName), "%s_alternative", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Alternative = buffer[0]; + } + + Format(keyName, sizeof(keyName), "%s_supported", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Supported = StrEqual(buffer, "true"); + } + + Format(keyName, sizeof(keyName), "%s_subjecttype", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_SubjectType = view_as(StringToInt(buffer)); + } + } + + if (GameConfGetKeyValue(gamedata, "checkteamplay", buffer, sizeof(buffer))) { + checkTeamPlay = StrEqual(buffer, "true"); + } + + CloseHandle(gamedata); + } + } + + mp_teamplay = FindConVar("mp_teamplay"); +} + +/** + * Checks if the passed color index is actually supported + * for the current game. If not, the index will be overwritten + * The color resolving works recursively until a valid color is found. + * + * @param index + * @param subject A client index or CHATCOLOR_NOSUBJECT + */ +static stock int Color_GetChatColorInfo(int &index, int &subject=CHATCOLOR_NOSUBJECT) +{ + Color_ChatInitialize(); + + if (index == -1) { + index = 0; + } + + while (!chatColorInfo[index].ChatColorInfo_Supported) { + + int alternative = chatColorInfo[index].ChatColorInfo_Alternative; + + if (alternative == -1) { + index = 0; + break; + } + + index = alternative; + } + + if (index == -1) { + index = 0; + } + + int newSubject = CHATCOLOR_NOSUBJECT; + ChatColorSubjectType type = chatColorInfo[index].ChatColorInfo_SubjectType; + + switch (type) { + case ChatColorSubjectType_none: { + } + case ChatColorSubjectType_player: { + newSubject = chatSubject; + } + case ChatColorSubjectType_undefined: { + newSubject = -1; + } + case ChatColorSubjectType_world: { + newSubject = 0; + } + default: { + + if (!checkTeamPlay || mp_teamplay.BoolValue) { + + if (subject > 0 && subject <= MaxClients) { + + if (GetClientTeam(subject) == view_as(type)) { + newSubject = subject; + } + } + else if (subject == CHATCOLOR_NOSUBJECT) { + int client = Team_GetAnyClient(view_as(type)); + + if (client != -1) { + newSubject = client; + } + } + } + } + } + + if (type > ChatColorSubjectType_none && + ((subject != CHATCOLOR_NOSUBJECT && subject != newSubject) || newSubject == CHATCOLOR_NOSUBJECT || !isSayText2_supported)) + { + index = chatColorInfo[index].ChatColorInfo_Alternative; + newSubject = Color_GetChatColorInfo(index, subject); + } + + // Only set the subject if there is no subject set already. + if (subject == CHATCOLOR_NOSUBJECT) { + subject = newSubject; + } + + return newSubject; +} diff --git a/scripting/include/smlib/concommands.inc b/scripting/include/smlib/concommands.inc new file mode 100644 index 0000000..2bd708f --- /dev/null +++ b/scripting/include/smlib/concommands.inc @@ -0,0 +1,45 @@ +#if defined _smlib_concommands_included + #endinput +#endif +#define _smlib_concommands_included + +#include +#include + +/** + * Checks if a ConCommand has one or more flags set. + * + * @param command ConCommand name. + * @param flags Flags to check. + * @return True if flags are set, false otherwise. + */ +stock bool ConCommand_HasFlags(const char[] command, int flags) +{ + return GetCommandFlags(command) & flags > 0; +} + +/** + * Adds one or more flags to a ConCommand. + * + * @param command ConCommand name. + * @param flags Flags to add. + */ +stock void ConCommand_AddFlags(const char[] command, int flags) +{ + int newFlags = GetCommandFlags(command); + newFlags |= flags; + SetCommandFlags(command, newFlags); +} + +/** + * Removes one ore more flags from a ConCommand. + * + * @param command ConCommand name. + * @param flags Flags to remove + */ +stock void ConCommand_RemoveFlags(const char[] command, int flags) +{ + int newFlags = GetCommandFlags(command); + newFlags &= ~flags; + SetCommandFlags(command, newFlags); +} diff --git a/scripting/include/smlib/convars.inc b/scripting/include/smlib/convars.inc new file mode 100644 index 0000000..b7f4b23 --- /dev/null +++ b/scripting/include/smlib/convars.inc @@ -0,0 +1,71 @@ +#if defined _smlib_convars_included + #endinput +#endif +#define _smlib_convars_included + +#include + +/** + * Checks if a ConVar has one or more flags set. + * + * @param convar ConVar Handle. + * @param flags Flags to check. + * @return True if flags are set, false otherwise. + */ +stock bool Convar_HasFlags(ConVar convar, int flags) +{ + return convar.Flags & flags > 0; +} + +/** + * Adds one or more flags to a ConVar. + * + * @param convar ConVar Handle. + * @param flags Flags to add. + */ +stock void Convar_AddFlags(ConVar convar, int flags) +{ + int newFlags = convar.Flags; + newFlags |= flags; + convar.Flags = newFlags; +} + +/** + * Removes one ore more flags from a ConVar. + * + * @param convar ConVar Handle. + * @param flags Flags to remove + * @noreturn + */ +stock void Convar_RemoveFlags(ConVar convar, int flags) +{ + int newFlags = convar.Flags; + newFlags &= ~flags; + convar.Flags = newFlags; +} + +/** + * Checks if a String is a valid ConVar or + * Console Command name. + * + * @param name String Name. + * @return True if the name specified is a valid ConVar or console command name, false otherwise. + */ +stock bool Convar_IsValidName(const char[] name) +{ + if (name[0] == '\0') { + return false; + } + + int n=0; + while (name[n] != '\0') { + + if (!IsValidConVarChar(name[n])) { + return false; + } + + n++; + } + + return true; +} diff --git a/scripting/include/smlib/crypt.inc b/scripting/include/smlib/crypt.inc new file mode 100644 index 0000000..21319aa --- /dev/null +++ b/scripting/include/smlib/crypt.inc @@ -0,0 +1,625 @@ +#if defined _smlib_crypt_included + #endinput +#endif +#define _smlib_crypt_included + +#include + +/********************************************************************************** + * + * Base64 Encoding/Decoding Functions + * All Credits to to SirLamer & ScriptCoderPro + * Taken from http://forums.alliedmods.net/showthread.php?t=101764 + * + ***********************************************************************************/ + +// The Base64 encoding table +static const char base64_sTable[] = + // 0000000000111111111122222222223333333333444444444455555555556666 + // 0123456789012345678901234567890123456789012345678901234567890123 + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// The Base64 decoding table +static const int base64_decodeTable[] = { +// 0 1 2 3 4 5 6 7 8 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - 29 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30 - 39 + 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, // 40 - 49 + 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, // 50 - 59 + 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, // 60 - 69 + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79 + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89 + 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, // 90 - 99 + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109 + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119 + 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, // 120 - 129 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130 - 139 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140 - 149 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150 - 159 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160 - 169 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 - 179 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180 - 189 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190 - 199 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200 - 209 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210 - 219 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220 - 229 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230 - 239 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240 - 249 + 0, 0, 0, 0, 0, 0 // 250 - 256 +}; + +/* + * For some reason the standard demands a string in 24-bit (3 character) intervals. + * This fill character is used to identify unused bytes at the end of the string. + */ +static const char base64_cFillChar = '='; + +// The conversion characters between the standard and URL-compliance Base64 protocols +static const char base64_mime_chars[] = "+/="; +static const char base64_url_chars[] = "-_."; + +/* + * Encodes a string or binary data into Base64 + * + * @param sString The input string or binary data to be encoded. + * @param sResult The storage buffer for the Base64-encoded result. + * @param len The maximum length of the storage buffer, in characters/bytes. + * @param sourcelen (optional): The number of characters or length in bytes to be read from the input source. + * This is not needed for a text string, but is important for binary data since there is no end-of-line character. + * @return The length of the written Base64 string, in bytes. + */ +stock int Crypt_Base64Encode(const char[] sString, char[] sResult, int len, int sourcelen=0) +{ + int nLength; // The string length to be read from the input + int resPos; // The string position in the result buffer + + // If the read length was specified, use it; otherwise, pull the string length from the input. + if (sourcelen > 0) { + nLength = sourcelen; + } + else { + nLength = strlen(sString); + } + + // Loop through and generate the Base64 encoded string + // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. + for (int nPos = 0; nPos < nLength; nPos++) { + int cCode; + + cCode = (sString[nPos] >> 2) & 0x3f; + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + + cCode = (sString[nPos] << 4) & 0x3f; + if (++nPos < nLength) { + cCode |= (sString[nPos] >> 4) & 0x0f; + } + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + + if ( nPos < nLength ) { + cCode = (sString[nPos] << 2) & 0x3f; + if (++nPos < nLength) { + cCode |= (sString[nPos] >> 6) & 0x03; + } + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + } + else { + nPos++; + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); + } + + if (nPos < nLength) { + cCode = sString[nPos] & 0x3f; + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + } + else { + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); + } + } + + return resPos; +} + + +/* + * Decodes a Base64 string. + * + * @param sString The input string in compliant Base64 format to be decoded. + * @param sResult The storage buffer for the decoded text strihg or binary data. + * @param len The maximum length of the storage buffer, in characters/bytes. + * @return The length of the decoded data, in bytes. + */ +stock int Crypt_Base64Decode(const char[] sString, char[] sResult, int len) +{ + int nLength = strlen(sString); // The string length to be read from the input + int resPos; // The string position in the result buffer + + // Loop through and generate the Base64 encoded string + // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. + for (int nPos = 0; nPos < nLength; nPos++) { + + int c, c1; + + c = base64_decodeTable[sString[nPos++]]; + c1 = base64_decodeTable[sString[nPos]]; + + c = (c << 2) | ((c1 >> 4) & 0x3); + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); + + if (++nPos < nLength) { + + c = sString[nPos]; + + if (c == base64_cFillChar) + break; + + c = base64_decodeTable[sString[nPos]]; + c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c1); + } + + if (++nPos < nLength) { + + c1 = sString[nPos]; + + if (c1 == base64_cFillChar) + break; + + c1 = base64_decodeTable[sString[nPos]]; + c = ((c << 6) & 0xc0) | c1; + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); + } + } + + return resPos; +} + + +/* + * Converts a standards-compliant Base64 string to the commonly accepted URL-compliant alternative. + * Note: The result will be the same length as the input string as long as the output buffer is large enough. + * + * @param sString The standards-compliant Base64 input string to converted. + * @param sResult The storage buffer for the URL-compliant result. + * @param len The maximum length of the storage buffer in characters/bytes. + * @return Number of cells written. + */ +stock int Crypt_Base64MimeToUrl(const char[] sString, char[] sResult, int len) +{ + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character + + nLength = strlen(sString); + + char[] sTemp = new char[nLength+1]; // Buffer string + + // Loop through string + for (int i = 0; i < nLength; i++) { + temp_char = sString[i]; + + for (int j = 0; j < chars_len; j++) { + + if(temp_char == base64_mime_chars[j]) { + temp_char = base64_url_chars[j]; + break; + } + } + + sTemp[i] = temp_char; + } + + sTemp[nLength] = '\0'; + + return strcopy(sResult, len, sTemp); +} + +/* + * Base64UrlToMime(String:sResult[], len, const String:sString[], sourcelen) + * Converts a URL-compliant Base64 string to the standards-compliant version. + * Note: The result will be the same length as the input string as long as the output buffer is large enough. + * + * @param sString The URL-compliant Base64 input string to converted. + * @param sResult The storage buffer for the standards-compliant result. + * @param len The maximum length of the storage buffer in characters/bytes. + * @return Number of cells written. + */ +stock int Crypt_Base64UrlToMime(const char[] sString, char[] sResult, int len) +{ + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character + + nLength = strlen(sString); + + char[] sTemp = new char[nLength+1]; // Buffer string + + // Loop through string + for (int i = 0; i < nLength; i++) { + temp_char = sString[i]; + for (int j = 0; j < chars_len; j++) { + if (temp_char == base64_url_chars[j]) { + temp_char = base64_mime_chars[j]; + break; + } + } + + sTemp[i] = temp_char; + } + + sTemp[nLength] = '\0'; + + return strcopy(sResult, len, sTemp); +} + +/********************************************************************************** + * + * MD5 Encoding Functions + * All Credits go to sslice + * RSA Data Security, Inc. MD5 Message Digest Algorithm + * Taken from http://forums.alliedmods.net/showthread.php?t=67683 + * + ***********************************************************************************/ + +/* + * Calculate the md5 hash of a string. + * + * @param str Input String + * @param output Output String Buffer + * @param maxlen Size of the Output String Buffer + */ +stock void Crypt_MD5(const char[] str, char[] output, int maxlen) +{ + int x[2]; + int buf[4]; + int input[64]; + int i, ii; + + int len = strlen(str); + + // MD5Init + x[0] = x[1] = 0; + buf[0] = 0x67452301; + buf[1] = 0xefcdab89; + buf[2] = 0x98badcfe; + buf[3] = 0x10325476; + + // MD5Update + int update[16]; + + update[14] = x[0]; + update[15] = x[1]; + + int mdi = (x[0] >>> 3) & 0x3F; + + if ((x[0] + (len << 3)) < x[0]) { + x[1] += 1; + } + + x[0] += len << 3; + x[1] += len >>> 29; + + int c = 0; + while (len--) { + input[mdi] = str[c]; + mdi += 1; + c += 1; + + if (mdi == 0x40) { + + for (i = 0, ii = 0; i < 16; ++i, ii += 4) + { + update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + // Transform + MD5Transform(buf, update); + + mdi = 0; + } + } + + // MD5Final + int padding[64] = { + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + int inx[16]; + inx[14] = x[0]; + inx[15] = x[1]; + + mdi = (x[0] >>> 3) & 0x3F; + + len = (mdi < 56) ? (56 - mdi) : (120 - mdi); + update[14] = x[0]; + update[15] = x[1]; + + mdi = (x[0] >>> 3) & 0x3F; + + if ((x[0] + (len << 3)) < x[0]) { + x[1] += 1; + } + + x[0] += len << 3; + x[1] += len >>> 29; + + c = 0; + while (len--) { + input[mdi] = padding[c]; + mdi += 1; + c += 1; + + if (mdi == 0x40) { + + for (i = 0, ii = 0; i < 16; ++i, ii += 4) { + update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + // Transform + MD5Transform(buf, update); + + mdi = 0; + } + } + + for (i = 0, ii = 0; i < 14; ++i, ii += 4) { + inx[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + MD5Transform(buf, inx); + + int digest[16]; + for (i = 0, ii = 0; i < 4; ++i, ii += 4) { + digest[ii] = (buf[i]) & 0xFF; + digest[ii + 1] = (buf[i] >>> 8) & 0xFF; + digest[ii + 2] = (buf[i] >>> 16) & 0xFF; + digest[ii + 3] = (buf[i] >>> 24) & 0xFF; + } + + FormatEx(output, maxlen, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], + digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); +} + +static stock void MD5Transform_FF(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += (((b) & (c)) | ((~b) & (d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_GG(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += (((b) & (d)) | ((c) & (~d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_HH(int &a, int &b, int &c, int &d, int x, int s, int ac) + { + a += ((b) ^ (c) ^ (d)) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_II(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += ((c) ^ ((b) | (~d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform(int[] buf, int[] input){ + int a = buf[0]; + int b = buf[1]; + int c = buf[2]; + int d = buf[3]; + + MD5Transform_FF(a, b, c, d, input[0], 7, 0xd76aa478); + MD5Transform_FF(d, a, b, c, input[1], 12, 0xe8c7b756); + MD5Transform_FF(c, d, a, b, input[2], 17, 0x242070db); + MD5Transform_FF(b, c, d, a, input[3], 22, 0xc1bdceee); + MD5Transform_FF(a, b, c, d, input[4], 7, 0xf57c0faf); + MD5Transform_FF(d, a, b, c, input[5], 12, 0x4787c62a); + MD5Transform_FF(c, d, a, b, input[6], 17, 0xa8304613); + MD5Transform_FF(b, c, d, a, input[7], 22, 0xfd469501); + MD5Transform_FF(a, b, c, d, input[8], 7, 0x698098d8); + MD5Transform_FF(d, a, b, c, input[9], 12, 0x8b44f7af); + MD5Transform_FF(c, d, a, b, input[10], 17, 0xffff5bb1); + MD5Transform_FF(b, c, d, a, input[11], 22, 0x895cd7be); + MD5Transform_FF(a, b, c, d, input[12], 7, 0x6b901122); + MD5Transform_FF(d, a, b, c, input[13], 12, 0xfd987193); + MD5Transform_FF(c, d, a, b, input[14], 17, 0xa679438e); + MD5Transform_FF(b, c, d, a, input[15], 22, 0x49b40821); + + MD5Transform_GG(a, b, c, d, input[1], 5, 0xf61e2562); + MD5Transform_GG(d, a, b, c, input[6], 9, 0xc040b340); + MD5Transform_GG(c, d, a, b, input[11], 14, 0x265e5a51); + MD5Transform_GG(b, c, d, a, input[0], 20, 0xe9b6c7aa); + MD5Transform_GG(a, b, c, d, input[5], 5, 0xd62f105d); + MD5Transform_GG(d, a, b, c, input[10], 9, 0x02441453); + MD5Transform_GG(c, d, a, b, input[15], 14, 0xd8a1e681); + MD5Transform_GG(b, c, d, a, input[4], 20, 0xe7d3fbc8); + MD5Transform_GG(a, b, c, d, input[9], 5, 0x21e1cde6); + MD5Transform_GG(d, a, b, c, input[14], 9, 0xc33707d6); + MD5Transform_GG(c, d, a, b, input[3], 14, 0xf4d50d87); + MD5Transform_GG(b, c, d, a, input[8], 20, 0x455a14ed); + MD5Transform_GG(a, b, c, d, input[13], 5, 0xa9e3e905); + MD5Transform_GG(d, a, b, c, input[2], 9, 0xfcefa3f8); + MD5Transform_GG(c, d, a, b, input[7], 14, 0x676f02d9); + MD5Transform_GG(b, c, d, a, input[12], 20, 0x8d2a4c8a); + + MD5Transform_HH(a, b, c, d, input[5], 4, 0xfffa3942); + MD5Transform_HH(d, a, b, c, input[8], 11, 0x8771f681); + MD5Transform_HH(c, d, a, b, input[11], 16, 0x6d9d6122); + MD5Transform_HH(b, c, d, a, input[14], 23, 0xfde5380c); + MD5Transform_HH(a, b, c, d, input[1], 4, 0xa4beea44); + MD5Transform_HH(d, a, b, c, input[4], 11, 0x4bdecfa9); + MD5Transform_HH(c, d, a, b, input[7], 16, 0xf6bb4b60); + MD5Transform_HH(b, c, d, a, input[10], 23, 0xbebfbc70); + MD5Transform_HH(a, b, c, d, input[13], 4, 0x289b7ec6); + MD5Transform_HH(d, a, b, c, input[0], 11, 0xeaa127fa); + MD5Transform_HH(c, d, a, b, input[3], 16, 0xd4ef3085); + MD5Transform_HH(b, c, d, a, input[6], 23, 0x04881d05); + MD5Transform_HH(a, b, c, d, input[9], 4, 0xd9d4d039); + MD5Transform_HH(d, a, b, c, input[12], 11, 0xe6db99e5); + MD5Transform_HH(c, d, a, b, input[15], 16, 0x1fa27cf8); + MD5Transform_HH(b, c, d, a, input[2], 23, 0xc4ac5665); + + MD5Transform_II(a, b, c, d, input[0], 6, 0xf4292244); + MD5Transform_II(d, a, b, c, input[7], 10, 0x432aff97); + MD5Transform_II(c, d, a, b, input[14], 15, 0xab9423a7); + MD5Transform_II(b, c, d, a, input[5], 21, 0xfc93a039); + MD5Transform_II(a, b, c, d, input[12], 6, 0x655b59c3); + MD5Transform_II(d, a, b, c, input[3], 10, 0x8f0ccc92); + MD5Transform_II(c, d, a, b, input[10], 15, 0xffeff47d); + MD5Transform_II(b, c, d, a, input[1], 21, 0x85845dd1); + MD5Transform_II(a, b, c, d, input[8], 6, 0x6fa87e4f); + MD5Transform_II(d, a, b, c, input[15], 10, 0xfe2ce6e0); + MD5Transform_II(c, d, a, b, input[6], 15, 0xa3014314); + MD5Transform_II(b, c, d, a, input[13], 21, 0x4e0811a1); + MD5Transform_II(a, b, c, d, input[4], 6, 0xf7537e82); + MD5Transform_II(d, a, b, c, input[11], 10, 0xbd3af235); + MD5Transform_II(c, d, a, b, input[2], 15, 0x2ad7d2bb); + MD5Transform_II(b, c, d, a, input[9], 21, 0xeb86d391); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +/********************************************************************************** + * + * RC4 Encoding Functions + * All Credits go to SirLamer and Raydan + * Taken from http://forums.alliedmods.net/showthread.php?t=101834 + * + ***********************************************************************************/ + +/* + * Encrypts a text string using RC4. + * Note: This function is NOT binary safe. + * Use Crypt_RC4EncodeBinary to encode binary data. + * + * @param input The source data to be encrypted. + * @param pwd The password/key used to encode and decode the data. + * @param output The encoded result. + * @param maxlen The maximum length of the output buffer. + */ +stock void Crypt_RC4Encode(const char[] input, const char[] pwd, char[] output, int maxlen) +{ + int pwd_len,str_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; + + pwd_len = strlen(pwd); + str_len = strlen(input); + + if (pwd_len > 0 && str_len > 0) { + + for (i=0; i < 256; i++) { + key[i] = pwd[i%pwd_len]; + box[i]=i; + } + + i=0; j=0; + + for (; i < 256; i++) { + j = (j + box[i] + key[i]) % 256; + tmp = box[i]; + box[i] = box[j]; + box[j] = tmp; + } + + i=0; j=0; a=0; + + for (; i < str_len; i++) { + a = (a + 1) % 256; + j = (j + box[a]) % 256; + tmp = box[a]; + box[a] = box[j]; + box[j] = tmp; + k = box[((box[a] + box[j]) % 256)]; + FormatEx(output[2*i], maxlen-2*i, "%02x", input[i] ^ k); + } + } +} + +/* + * Encrypts binary data using RC4. + * + * @param input The source data to be encrypted. + * @param str_len The length of the source data. + * @param pwd The password/key used to encode and decode the data. + * @param output The encoded result. + * @param maxlen The maximum length of the output buffer. + */ +stock int Crypt_RC4EncodeBinary(const char[] input, int str_len, const char[] pwd, char[] output, int maxlen) +{ + int pwd_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; + + pwd_len = strlen(pwd); + + if (pwd_len > 0 && str_len > 0) { + + for(i=0;i<256;i++) { + key[i] = pwd[i%pwd_len]; + box[i]=i; + } + + i=0; j=0; + + for (; i < 256; i++) { + j = (j + box[i] + key[i]) % 256; + tmp = box[i]; + box[i] = box[j]; + box[j] = tmp; + } + + i=0; j=0; a=0; + + if (str_len+1 > maxlen) { + str_len = maxlen - 1; + } + + for(; i < str_len; i++) { + a = (a + 1) % 256; + j = (j + box[a]) % 256; + tmp = box[a]; + box[a] = box[j]; + box[j] = tmp; + k = box[((box[a] + box[j]) % 256)]; + FormatEx(output[i], maxlen-i, "%c", input[i] ^ k); + } + + /* + * i = number of written bits (remember increment occurs at end of for loop, and THEN it fails the loop condition) + * Since we're working with binary data, the calling function should not depend on the escape + * character, but putting it here prevents crashes in case someone tries to read the data like a string + */ + output[i] = '\0'; + + return i; + } + else { + return -1; + } +} diff --git a/scripting/include/smlib/debug.inc b/scripting/include/smlib/debug.inc new file mode 100644 index 0000000..6a416ed --- /dev/null +++ b/scripting/include/smlib/debug.inc @@ -0,0 +1,28 @@ +#if defined _smlib_debug_included + #endinput +#endif +#define _smlib_debug_included + +#include + +/** + * Prints the values of a static Float-Array to the server console. + * + * @param array Static Float-Array. + * @param size Size of the Array. + */ +stock void Debug_FloatArray(const float[] array, int size=3) +{ + char output[64] = ""; + + for (int i=0; i < size; ++i) { + + if (i > 0 && i < size) { + StrCat(output, sizeof(output), ", "); + } + + Format(output, sizeof(output), "%s%f", output, array[i]); + } + + PrintToServer("[DEBUG] Vector[%d] = { %s }", size, output); +} diff --git a/scripting/include/smlib/dynarrays.inc b/scripting/include/smlib/dynarrays.inc new file mode 100644 index 0000000..35a8951 --- /dev/null +++ b/scripting/include/smlib/dynarrays.inc @@ -0,0 +1,24 @@ +#if defined _smlib_dynarray_included + #endinput +#endif +#define _smlib_dynarray_included + +#include + +/** + * Retrieves a cell value from an array. + * This is a wrapper around the Sourcemod Function GetArrayCell, + * but it casts the result as bool + * + * @param array Array Handle. + * @param index Index in the array. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). + * @param asChar Optionally read as a byte instead of a cell. + * @return Value read. + * @error Invalid Handle, invalid index, or invalid block. + */ +stock bool DynArray_GetBool(ArrayList array, int index, int block=0, bool asChar=false) +{ + return array.Get(index, block, asChar) != 0; +} diff --git a/scripting/include/smlib/edicts.inc b/scripting/include/smlib/edicts.inc new file mode 100644 index 0000000..86f4e2a --- /dev/null +++ b/scripting/include/smlib/edicts.inc @@ -0,0 +1,127 @@ +#if defined _smlib_edicts_included + #endinput +#endif +#define _smlib_edicts_included + +#include +#include + +/* + * Finds an edict by it's name + * It only finds the first occurence. + * + * @param name Name of the entity you want so search. + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_FindByName(const char[] name) +{ + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (Entity_NameMatches(edict, name)) { + return edict; + } + } + + return INVALID_ENT_REFERENCE; +} + +/* + * Finds an edict by its HammerID. + * The newer version of Valve's Hammer editor + * sets a unique ID for each entity in a map. + * It only finds the first occurence. + * + * @param hammerId Hammer editor ID + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_FindByHammerId(int hammerId) +{ + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (Entity_GetHammerId(edict) == hammerId) { + return edict; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Searches for the closest edict in relation to the given origin + * + * @param vecOrigin_center 3 dimensional origin array + * @param clientsOnly True if you only want to search for clients + * @param ignoreEntity Ignore this entity + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_GetClosest(float vecOrigin_center[3], bool clientsOnly=false, int ignoreEntity=-1) +{ + float vecOrigin_edict[3]; + float smallestDistance = 0.0; + int closestEdict = INVALID_ENT_REFERENCE; + + int maxEntities; + + if (clientsOnly) { + maxEntities = MaxClients; + } + else { + maxEntities = GetMaxEntities(); + } + + for (int edict=1; edict <= maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (ignoreEntity >= 0 && edict == ignoreEntity) { + continue; + } + + if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) { + continue; + } + + Entity_GetAbsOrigin(edict, vecOrigin_edict); + + float edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true); + + if (edict_distance < smallestDistance || smallestDistance == 0.0) { + smallestDistance = edict_distance; + closestEdict = edict; + } + } + + return closestEdict; +} + +/** + * Searches for the closest edict in relation to the given edict. + * + * @param edict Edict index + * @param clientsOnly True if you only want to search for clients + * @return The closest edict or INVALID_ENT_REFERENCE + */ +stock int Edict_GetClosestToEdict(int edict, bool clientsOnly=false) +{ + float vecOrigin[3]; + + if (!HasEntProp(edict, Prop_Send, "m_vecOrigin")) { + return INVALID_ENT_REFERENCE; + } + + Entity_GetAbsOrigin(edict, vecOrigin); + + return Edict_GetClosest(vecOrigin, clientsOnly, edict); +} diff --git a/scripting/include/smlib/effects.inc b/scripting/include/smlib/effects.inc new file mode 100644 index 0000000..b5e9122 --- /dev/null +++ b/scripting/include/smlib/effects.inc @@ -0,0 +1,722 @@ +#if defined _smlib_effects_included + #endinput +#endif +#define _smlib_effects_included + +#include +#include +#include +#include +#include +#include +#include +#include + + + +// Entity Dissolve types +enum DissolveType +{ + DISSOLVE_NORMAL = 0, + DISSOLVE_ELECTRICAL, + DISSOLVE_ELECTRICAL_LIGHT, + DISSOLVE_CORE +}; + +/** + * Dissolves a player + * + * @param client Client Index. + * @param dissolveType Dissolve Type, use the DissolveType enum. + * @param magnitude How strongly to push away from the center. + * @return True on success, otherwise false. + */ +stock bool Effect_DissolveEntity(int entity, DissolveType dissolveType=DISSOLVE_NORMAL, int magnitude=1) +{ + int env_entity_dissolver = CreateEntityByName("env_entity_dissolver"); + + if (env_entity_dissolver == -1) { + return false; + } + + Entity_PointAtTarget(env_entity_dissolver, entity); + SetEntProp(env_entity_dissolver, Prop_Send, "m_nDissolveType", dissolveType); + SetEntProp(env_entity_dissolver, Prop_Send, "m_nMagnitude", magnitude); + AcceptEntityInput(env_entity_dissolver, "Dissolve"); + Entity_Kill(env_entity_dissolver); + + return true; +} + +/** + * Dissolves a player's Ragdoll + * + * @param client Client Index. + * @param dissolveType Dissolve Type, use the DissolveType enum. + * @return True on success, otherwise false. + */ +stock bool Effect_DissolvePlayerRagDoll(int client, DissolveType dissolveType=DISSOLVE_NORMAL) +{ + int m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll"); + + if (m_hRagdoll == -1) { + return false; + } + + return Effect_DissolveEntity(m_hRagdoll, dissolveType); +} + +typedef EffectCallback = function void(int entity, any data); + +/** + * Fades an entity in our out. + * You can specifiy a callback function which will get called + * when the fade is finished. + * Important: The callback will be called if it is passed, + * no matter if the entity is still valid or not. That means you + * have to check if the entity is valid yourself. + * + * @param entity Entity Index. + * @param fadeOut Optional: Fade the entity out (true) or in (false). + * @param kill Optional: If to kill the entity when the fade is finished. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_Fade(int entity, bool fadeOut=true, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + float timerTime = 0.0; + + if (fast) { + timerTime = 0.6; + + if (fadeOut) { + SetEntityRenderFx(entity, RENDERFX_FADE_FAST); + } + else { + SetEntityRenderFx(entity, RENDERFX_SOLID_FAST); + } + } + else { + timerTime = 3.0; + + if (fadeOut) { + SetEntityRenderFx(entity, RENDERFX_FADE_SLOW); + } + else { + SetEntityRenderFx(entity, RENDERFX_SOLID_SLOW); + } + } + + ChangeEdictState(entity, GetEntSendPropOffs(entity, "m_nRenderFX", true)); + + if (kill || callback != INVALID_FUNCTION) { + DataPack dataPack = null; + CreateDataTimer(timerTime, _smlib_Timer_Effect_Fade, dataPack, TIMER_FLAG_NO_MAPCHANGE | TIMER_DATA_HNDL_CLOSE); + + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackCell(dataPack, kill); + WritePackFunction(dataPack, callback); + WritePackCell(dataPack, data); + ResetPack(dataPack); + } +} + +/** + * Fades the entity in. + * A wrapper function around Effect_Fade(). + * + * @param entity Entity Index. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_FadeIn(int entity, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + Effect_Fade(entity, false, false, fast, callback, data); +} + +/** + * Fades the entity out. + * A wrapper function around Effect_Fade(). + * + * @param entity Entity Index. + * @param fadeOut Optional: Fade the entity out (true) or in (false). + * @param kill Optional: If to kill the entity when the fade is finished. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_FadeOut(int entity, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + Effect_Fade(entity, true, kill, fast, callback, data); +} + +public Action _smlib_Timer_Effect_Fade(Handle Timer, DataPack dataPack) +{ + int entity = ReadPackCell(dataPack); + int kill = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); + any data = ReadPackCell(dataPack); + + if (callback != INVALID_FUNCTION) { + Call_StartFunction(INVALID_HANDLE, callback); + Call_PushCell(entity); + Call_PushCell(data); + Call_Finish(); + } + + if (kill && IsValidEntity(entity)) { + Entity_Kill(entity); + } + + return Plugin_Stop; +} + +/** + * Sends a boxed beam effect to one player. + * + * Ported from eventscripts vecmath library. + * + * @param client The client to show the box to. + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxToClient( + int client, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawBeamBox(clients, 1, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to all players. + * + * Ported from eventscripts vecmath library. + * + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxToAll( + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawBeamBox(clients, numClients, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to a list of players. + * + * Ported from eventscripts vecmath library. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBox( + int[] clients, + int numClients, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + // Create the additional corners of the box + float corners[8][3]; + + for (int i=0; i < 4; i++) { + Array_Copy(bottomCorner, corners[i], 3); + Array_Copy(upperCorner, corners[i+4], 3); + } + + corners[1][0] = upperCorner[0]; + corners[2][0] = upperCorner[0]; + corners[2][1] = upperCorner[1]; + corners[3][1] = upperCorner[1]; + corners[4][0] = bottomCorner[0]; + corners[4][1] = bottomCorner[1]; + corners[5][1] = bottomCorner[1]; + corners[7][0] = bottomCorner[0]; + + // Draw all the edges + + // Horizontal Lines + // Bottom + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // Top + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // All Vertical Lines + for (int i=0; i < 4; i++) { + TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } +} + + +/** + * Sends a boxed beam effect to one player. + * + * Ported from eventscripts vecmath library. + * + * @param client The client to show the box to. + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatableToClient( + int client, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawBeamBoxRotatable(clients, 1, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + + + +/** + * Sends a boxed beam effect to all players. + * + * Ported from eventscripts vecmath library. + * + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatableToAll( + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawBeamBoxRotatable(clients, numClients, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to a list of players. + * + * Ported from eventscripts vecmath library. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatable( + int[] clients, + int numClients, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + // Create the additional corners of the box + float corners[8][3]; + Array_Copy(mins, corners[0], 3); + Math_MakeVector(maxs[0], mins[1], mins[2], corners[1]); + Math_MakeVector(maxs[0], maxs[1], mins[2], corners[2]); + Math_MakeVector(mins[0], maxs[1], mins[2], corners[3]); + Math_MakeVector(mins[0], mins[1], maxs[2], corners[4]); + Math_MakeVector(maxs[0], mins[1], maxs[2], corners[5]); + Array_Copy(maxs, corners[6], 3); + Math_MakeVector(mins[0], maxs[1], maxs[2], corners[7]); + + // Rotate all edges + for (int i=0; i < sizeof(corners); i++) { + Math_RotateVector(corners[i], angles, corners[i]); + } + + // Apply world offset (after rotation) + for (int i=0; i < sizeof(corners); i++) { + AddVectors(origin, corners[i], corners[i]); + } + + // Draw all the edges + // Horizontal Lines + // Bottom + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // Top + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // All Vertical Lines + for (int i=0; i < 4; i++) { + TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } +} + +/** + * Displays the given axis of rotation as beam effect to one player. + * + * @param client The client to show the box to. + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotationToClient( + int client, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawAxisOfRotation(clients, 1, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); +} + +/** + * Displays the given axis of rotation as beam effect to all players. + * + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotationToAll( + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawAxisOfRotation(clients, numClients, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); +} + +/** + * Displays the given axis of rotation as beam effect to a list of players. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotation( + int[] clients, + int numClients, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) { + // Create the additional corners of the box + float xAxis[3], yAxis[3], zAxis[3]; + xAxis[0] = length[0]; + yAxis[1] = length[1]; + zAxis[2] = length[2]; + + // Rotate all edges + Math_RotateVector(xAxis, angles, xAxis); + Math_RotateVector(yAxis, angles, yAxis); + Math_RotateVector(zAxis, angles, zAxis); + + // Apply world offset (after rotation) + AddVectors(origin, xAxis, xAxis); + AddVectors(origin, yAxis, yAxis); + AddVectors(origin, zAxis, zAxis); + + // Draw all + TE_SetupBeamPoints(origin, xAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {255, 0, 0, 255}, speed); + TE_Send(clients, numClients); + + TE_SetupBeamPoints(origin, yAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 255, 0, 255}, speed); + TE_Send(clients, numClients); + + TE_SetupBeamPoints(origin, zAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 0, 255, 255}, speed); + TE_Send(clients, numClients); +} + + +/** + * Creates an env_sprite. + * + * @param origin Origin of the Sprite. + * @param modelIndex Precached model index. + * @param color Color array (r, g, b, a). + * @param scale Scale (Note: many materials ignore a lower value than 0.25). + * @param targetName Targetname of the sprite. + * @param parent Entity Index of this sprite's parent in the movement hierarchy. + * @param renderMode Render mode (use the enum). + * @param renderFx Render fx (use the enum). + * @param glowProxySize Radius size of the glow when to be rendered, if inside a geometry. Ex: a block 2x2x2 units big, if the glowProxySize is between 0.0 and 2.0 the sprite will not be rendered, even if the actual size of the sprite is bigger, everything above 2.0 will render the sprite. Using an abnormal high value will render Sprites trough walls. + * @param frameRate Sprite frame rate. + * @param hdrColorScale Float value to multiply sprite color by when running with HDR. + * @param receiveShadows When false then this prevents the sprite from receiving shadows. + * @return Entity Index of the created Sprite. + */ +stock int Effect_EnvSprite( + const float origin[3], + int modelIndex, + const int color[4]={255, 255, 255, 255}, + float scale=0.25, + const char targetName[MAX_NAME_LENGTH]="", + int parent=-1, + RenderMode renderMode=RENDER_WORLDGLOW, + RenderFx renderFx=RENDERFX_NONE, + float glowProxySize=2.0, + float framerate=10.0, + float hdrColorScale=1.0, + bool receiveShadows = true +) { + int entity = Entity_Create("env_sprite"); + + if (entity == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + DispatchKeyValue (entity, "disablereceiveshadows", (receiveShadows) ? "0" : "1"); + DispatchKeyValueFloat (entity, "framerate", framerate); + DispatchKeyValueFloat (entity, "GlowProxySize", glowProxySize); + DispatchKeyValue (entity, "spawnflags", "1"); + DispatchKeyValueFloat (entity, "HDRColorScale", hdrColorScale); + DispatchKeyValue (entity, "maxdxlevel", "0"); + DispatchKeyValue (entity, "mindxlevel", "0"); + DispatchKeyValueFloat (entity, "scale", scale); + + DispatchSpawn(entity); + + SetEntityRenderMode(entity, renderMode); + SetEntityRenderColor(entity, color[0], color[1], color[2], color[3]); + SetEntityRenderFx(entity, renderFx); + + Entity_SetName(entity, targetName); + Entity_SetModelIndex(entity, modelIndex); + Entity_SetAbsOrigin(entity, origin); + + if (parent != -1) { + Entity_SetParent(entity, parent); + } + + return entity; +} diff --git a/scripting/include/smlib/entities.inc b/scripting/include/smlib/entities.inc new file mode 100644 index 0000000..91c136b --- /dev/null +++ b/scripting/include/smlib/entities.inc @@ -0,0 +1,2098 @@ +#if defined _smlib_entities_included + #endinput +#endif +#define _smlib_entities_included + +#include +#include +#include + +/** + * Macro for iterating trough all children (entities it is parent of) of an entity. + * + * @param 1 Entity Index of the parent. + * @param 2 Name of the children entity index variable (will be only valid in the loop). + */ +#define LOOP_CHILDREN(%1,%2) for (int %2=Entity_GetNextChild(%1); %2 != INVALID_ENT_REFERENCE; %2=Entity_GetNextChild(%1, ++%2)) + +/* + * Checks if an entity is valid and exists. + * + * @param entity Entity Index. + * @return True if the entity is valid, false otherwise. + */ +stock bool Entity_IsValid(int entity) +{ + return IsValidEntity(entity); +} + +/** + * Finds an entity by its name. + * You can optionally specify the classname to search for. + * Note: If the classname is specified it uses The Sourcemod native + * function FindEntityByClassname() which uses the engine's + * linked entity list for finding entities. This might be + * cheaper, use this if you call this function very often. + * + * @param name Name of the entity you want so search. + * @param className Optional: Classname of the entity + * @return Entity index or INVALID_ENT_REFERENCE if not matching entity was found. + */ +stock int Entity_FindByName(const char[] name, const char[] className="") +{ + if (className[0] == '\0') { + // Hack: Double the limit to gets none-networked entities too. + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_NameMatches(entity, name)) { + return entity; + } + } + } + else { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + + if (Entity_NameMatches(entity, name)) { + return entity; + } + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Finds an entity by its HammerID. + * The newer version of Valve's Hammer editor + * sets a unique ID for each entity in a map. + * It only finds the first occurence. + * Note: If the classname is specified it uses The Sourcemod native + * function FindEntityByClassname() which uses the engine's + * linked entity list for finding entities. This might be + * cheaper, use this if you call this function very often. + * + * @param hammerId Hammer editor ID + * @param className Optional: Classname of the entity + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Entity_FindByHammerId(int hammerId, const char[] className="") +{ + if (className[0] == '\0') { + // Hack: Double the limit to gets none-networked entities too. + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_GetHammerId(entity) == hammerId) { + return entity; + } + } + } + else { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + + if (Entity_GetHammerId(entity) == hammerId) { + return entity; + } + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Searches for an entity by classname. + * This is a wrapper around FindEntityByClassname + * and has been added for completion. + * + * @param startEnt The entity index after which to begin searching from. Use -1 to start from the first entity. + * @param classname Classname of the entity to find. + * @return Entity index >= 0 if found, -1 otherwise. + */ + +stock int Entity_FindByClassName(int startEntity, const char[] className) +{ + return FindEntityByClassname(startEntity, className); +} + +/** + * Checks if an entity (partially) matches a specific entity class. + * + * @param entity Entity Index. + * @param className Classname String. + * @partialMatch If to do a partial classname check. + * @return True if the classname matches, false otherwise. + */ +stock bool Entity_ClassNameMatches(int entity, const char[] className, bool partialMatch=false) +{ + char entity_className[64]; + Entity_GetClassName(entity, entity_className, sizeof(entity_className)); + + if (partialMatch) { + return (StrContains(entity_className, className) != -1); + } + + return StrEqual(entity_className, className); +} + +/** + * Checks if an entity matches a name + * + * @param entity Entity Index. + * @param class Name String. + * @return True if the name matches, false otherwise. + */ +stock bool Entity_NameMatches(int entity, const char[] name) +{ + char entity_name[128]; + Entity_GetName(entity, entity_name, sizeof(entity_name)); + + return StrEqual(name, entity_name); +} + +/** + * Gets the Name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iName", buffer, size); +} + +/** + * Sets the Name of an entity. + * + * @param entity Entity index. + * @param name The name you want to give. + * @return True on success, false otherwise. + */ +stock bool Entity_SetName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "targetname", format); +} + +/** + * Gets the Classname of an entity. + * This is like GetEdictClassname(), except it works for ALL + * entities, not just edicts. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetClassName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); +} + +/** + * Sets the Classname of an entity. + * + * @param entity Entity index. + * @param name The name you want to give. + * @return True on success, false otherwise. + */ +stock bool Entity_SetClassName(int entity, const char[] className) +{ + return DispatchKeyValue(entity, "classname", className); +} + +/** + * Gets the Target name of an other entity + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetTargetName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_target", buffer, size); +} + +/** + * Sets the Target name of an other Entity + * + * @param entity Entity index. + * @param name The target name you want to set + * @return True on success, false otherwise. + */ +stock bool Entity_SetTargetName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "target", format); +} + +/** + * Gets the Global Name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetGlobalName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iGlobalname", buffer, size); +} + +/** + * Sets the Global Name of an entity. + * + * @param entity Entity index. + * @param name The global name you want to set. + * @return True on success, false otherwise. + */ +stock bool Entity_SetGlobalName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "globalname", format); +} + +/** + * Gets the Parent name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetParentName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iParent", buffer, size); +} + +/** + * Sets the Parent name of an entity. + * + * @param entity Entity index. + * @param name The parent name you want to set. + * @return True on success, false otherwise. + */ +stock bool Entity_SetParentName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "parentname", format); +} + +/** + * Gets the Hammer-ID of an entity. + * The Hammer Editor gives every entity a unique ID. + * Note: Old maps don't have Hammer-ID's set for entities + * + * @param entity Entity index. + * @return Hammer ID. + */ +stock int Entity_GetHammerId(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iHammerID"); +} + +/** + * Gets the radius (m_flRadius) of an entity. + * + * @param entity Entity index. + * @return Radius + */ +stock float Entity_GetRadius(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flRadius"); +} + +/** + * Sets the radius (m_flRadius) of an entity. + * + * @param entity Entity index. + * @param radius Radius value + */ +stock void Entity_SetRadius(int entity, float radius) +{ + SetEntPropFloat(entity, Prop_Data, "m_flRadius", radius); +} + +/** + * Gets the Mins of an entity. + * + * @param entity Entity index. + * @param vec Buffer to hold the vector. + */ +stock void Entity_GetMinSize(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecMins", vec); +} + +/** + * Sets the Mins of an entity. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_SetMinSize(int entity, const float vecMins[3]) +{ + SetEntPropVector(entity, Prop_Send, "m_vecMins", vecMins); +} + +/** + * Gets the Mins of an entity. + * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. + * + * @param entity Entity index + * @param vec Buffer to hold the vector + */ +stock void Entity_GetMaxSize(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", vec); +} + +/** + * Sets the Maxs of an entity. + * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. + * + * @param entity Entity index. + * @param vec Buffer to hold the vector. + */ +stock void Entity_SetMaxSize(int entity, const float vecMaxs[3]) +{ + SetEntPropVector(entity, Prop_Send, "m_vecMaxs", vecMaxs); +} + +/** + * Sets the Min and Max Size of an entity. + * Code is taken from HL2SDK and rewritten for Sourcemod. + * + * @param entity Entity index. + * @param vecMins Min size Vector + * @param vecMaxs Max size Vector + */ +stock void Entity_SetMinMaxSize(int entity, float vecMins[3], float vecMaxs[3]) +{ + // Taken from hl2sdk-ob-valve\game\server\util.cpp SetMinMaxSize() + // Todo: Replace this by a SDK call + for (int i=0; i<3; i++) { + + if (vecMins[i] > vecMaxs[i]) { + ThrowError("Error: mins[%d] > maxs[%d] of entity %d", i, i, EntRefToEntIndex(entity)); + } + } + + float m_vecMins[3], m_vecMaxs[3]; + Entity_GetMinSize(entity, m_vecMins); + Entity_GetMaxSize(entity, m_vecMaxs); + + if (Math_VectorsEqual(m_vecMins, vecMins) && Math_VectorsEqual(m_vecMaxs, vecMaxs)) { + return; + } + + Entity_SetMinSize(entity, vecMins); + Entity_SetMaxSize(entity, vecMaxs); + + float vecSize[3]; + SubtractVectors(vecMaxs, vecMins, vecSize); + Entity_SetRadius(entity, GetVectorLength(vecSize) * 0.5); + + Entity_MarkSurrBoundsDirty(entity); +} + +/* + * Spawn Flags + * Many entities define their specific spawnflags, check the HL2SDK. + */ + +/* + * Phys prop spawnflags + * Taken from hl2sdk-ob-valve\game\shared\props_shared.h + */ +#define SF_PHYSPROP_START_ASLEEP 0x000001 +#define SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE 0x000002 // this prop can't be damaged by physics collisions +#define SF_PHYSPROP_DEBRIS 0x000004 +#define SF_PHYSPROP_MOTIONDISABLED 0x000008 // motion disabled at startup (flag only valid in spawn - motion can be enabled via input) +#define SF_PHYSPROP_TOUCH 0x000010 // can be 'crashed through' by running player (plate glass) +#define SF_PHYSPROP_PRESSURE 0x000020 // can be broken by a player standing on it +#define SF_PHYSPROP_ENABLE_ON_PHYSCANNON 0x000040 // enable motion only if the player grabs it with the physcannon +#define SF_PHYSPROP_NO_ROTORWASH_PUSH 0x000080 // The rotorwash doesn't push these +#define SF_PHYSPROP_ENABLE_PICKUP_OUTPUT 0x000100 // If set, allow the player to +USE this for the purposes of generating an output +#define SF_PHYSPROP_PREVENT_PICKUP 0x000200 // If set, prevent +USE/Physcannon pickup of this prop +#define SF_PHYSPROP_PREVENT_PLAYER_TOUCH_ENABLE 0x000400 // If set, the player will not cause the object to enable its motion when bumped into +#define SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS 0x000800 // Need to remove attached ragdolls on enable motion/etc +#define SF_PHYSPROP_FORCE_TOUCH_TRIGGERS 0x001000 // Override normal debris behavior and respond to triggers anyway +#define SF_PHYSPROP_FORCE_SERVER_SIDE 0x002000 // Force multiplayer physics object to be serverside +#define SF_PHYSPROP_RADIUS_PICKUP 0x004000 // For Xbox, makes small objects easier to pick up by allowing them to be found +#define SF_PHYSPROP_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. +#define SF_PHYSPROP_NO_COLLISIONS 0x200000 // Don't enable collisions on spawn +#define SF_PHYSPROP_IS_GIB 0x400000 // Limit # of active gibs + +/* + * Physbox Spawnflags. Start at 0x01000 to avoid collision with CBreakable's + * Taken from hl2sdk-ob-valve\game\server\physobj.h + */ +#define SF_PHYSBOX_ASLEEP 0x01000 +#define SF_PHYSBOX_IGNOREUSE 0x02000 +#define SF_PHYSBOX_DEBRIS 0x04000 +#define SF_PHYSBOX_MOTIONDISABLED 0x08000 +#define SF_PHYSBOX_USEPREFERRED 0x10000 +#define SF_PHYSBOX_ENABLE_ON_PHYSCANNON 0x20000 +#define SF_PHYSBOX_NO_ROTORWASH_PUSH 0x40000 // The rotorwash doesn't push these +#define SF_PHYSBOX_ENABLE_PICKUP_OUTPUT 0x80000 +#define SF_PHYSBOX_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. +#define SF_PHYSBOX_NEVER_PICK_UP 0x200000 // Physcannon will never be able to pick this up. +#define SF_PHYSBOX_NEVER_PUNT 0x400000 // Physcannon will never be able to punt this object. +#define SF_PHYSBOX_PREVENT_PLAYER_TOUCH_ENABLE 0x800000 // If set, the player will not cause the object to enable its motion when bumped into + +/* + * Spawnflags for func breakable + * Taken from hl2sdk-ob-valve\game\server\func_break.h + */ +#define SF_BREAK_TRIGGER_ONLY 0x0001 // may only be broken by trigger +#define SF_BREAK_TOUCH 0x0002 // can be 'crashed through' by running player (plate glass) +#define SF_BREAK_PRESSURE 0x0004 // can be broken by a player standing on it +#define SF_BREAK_PHYSICS_BREAK_IMMEDIATELY 0x0200 // the first physics collision this breakable has will immediately break it +#define SF_BREAK_DONT_TAKE_PHYSICS_DAMAGE 0x0400 // this breakable doesn't take damage from physics collisions +#define SF_BREAK_NO_BULLET_PENETRATION 0x0800 // don't allow bullets to penetrate + +/* + * Spawnflags for func_pushable (it's also func_breakable, so don't collide with those flags) + * Taken from hl2sdk-ob-valve\game\server\func_break.h + */ +#define SF_PUSH_BREAKABLE 0x0080 +#define SF_PUSH_NO_USE 0x0100 // player cannot +use pickup this ent + +/** + * Gets the Spawnflags of an entity. + * + * @param entity Entity index. + * @return Spawnflags value + */ +stock int Entity_GetSpawnFlags(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_spawnflags"); +} + +/** + * Sets the Spawnflags of an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_SetSpawnFlags(int entity, int flags) +{ + SetEntProp(entity, Prop_Data, "m_spawnflags", flags); +} + +/** + * Adds Spawnflags to an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_AddSpawnFlags(int entity, int flags) +{ + int spawnFlags = Entity_GetSpawnFlags(entity); + spawnFlags |= flags; + Entity_SetSpawnFlags(entity, spawnFlags); +} + +/** + * Removes Spawnflags from an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_RemoveSpawnFlags(int entity, int flags) +{ + int spawnFlags = Entity_GetSpawnFlags(entity); + spawnFlags &= ~flags; + Entity_SetSpawnFlags(entity, spawnFlags); +} + +/** + * Clears all Spawnflags of an entity. + * + * @param entity Entity index. + * @noretur */ +stock void Entity_ClearSpawnFlags(int entity) +{ + Entity_SetSpawnFlags(entity, 0); +} + +/** + * Returns whether the entity has specific Spawnflags. + * + * @param entity Entity index. + * @param flags Flags value. + * @return True if the entity has the spawnflags set, false otherwise. + */ +stock bool Entity_HasSpawnFlags(int entity, int flags) +{ + return Entity_GetSpawnFlags(entity) & flags == flags; +} + +/* + * Entity flags, CBaseEntity::m_iEFlags + * Taken from: hl2sdk-ob-valve\game\shared\shareddefs.h + */ +enum Entity_Flags +{ + EFL_KILLME = (1<<0), // This entity is marked for death -- This allows the game to actually delete ents at a safe time + EFL_DORMANT = (1<<1), // Entity is dormant, no updates to client + EFL_NOCLIP_ACTIVE = (1<<2), // Lets us know when the noclip command is active. + EFL_SETTING_UP_BONES = (1<<3), // Set while a model is setting up its bones. + EFL_KEEP_ON_RECREATE_ENTITIES = (1<<4), // This is a special entity that should not be deleted when we restart entities only + + EFL_HAS_PLAYER_CHILD= (1<<4), // One of the child entities is a player. + + EFL_DIRTY_SHADOWUPDATE = (1<<5), // Client only- need shadow manager to update the shadow... + EFL_NOTIFY = (1<<6), // Another entity is watching events on this entity (used by teleport) + + // The default behavior in ShouldTransmit is to not send an entity if it doesn't + // have a model. Certain entities want to be sent anyway because all the drawing logic + // is in the client DLL. They can set this flag and the engine will transmit them even + // if they don't have a model. + EFL_FORCE_CHECK_TRANSMIT = (1<<7), + + EFL_BOT_FROZEN = (1<<8), // This is set on bots that are frozen. + EFL_SERVER_ONLY = (1<<9), // Non-networked entity. + EFL_NO_AUTO_EDICT_ATTACH = (1<<10), // Don't attach the edict; we're doing it explicitly + + // Some dirty bits with respect to abs computations + EFL_DIRTY_ABSTRANSFORM = (1<<11), + EFL_DIRTY_ABSVELOCITY = (1<<12), + EFL_DIRTY_ABSANGVELOCITY = (1<<13), + EFL_DIRTY_SURR_COLLISION_BOUNDS = (1<<14), + EFL_DIRTY_SPATIAL_PARTITION = (1<<15), +// UNUSED = (1<<16), + + EFL_IN_SKYBOX = (1<<17), // This is set if the entity detects that it's in the skybox. + // This forces it to pass the "in PVS" for transmission. + EFL_USE_PARTITION_WHEN_NOT_SOL = (1<<18), // Entities with this flag set show up in the partition even when not solid + EFL_TOUCHING_FLUID = (1<<19), // Used to determine if an entity is floating + + // FIXME: Not really sure where I should add this... + EFL_IS_BEING_LIFTED_BY_BARNACLE = (1<<20), + EFL_NO_ROTORWASH_PUSH = (1<<21), // I shouldn't be pushed by the rotorwash + EFL_NO_THINK_FUNCTION = (1<<22), + EFL_NO_GAME_PHYSICS_SIMULATION = (1<<23), + + EFL_CHECK_UNTOUCH = (1<<24), + EFL_DONTBLOCKLOS = (1<<25), // I shouldn't block NPC line-of-sight + EFL_DONTWALKON = (1<<26), // NPC;s should not walk on this entity + EFL_NO_DISSOLVE = (1<<27), // These guys shouldn't dissolve + EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1<<28), // Mega physcannon can't ragdoll these guys. + EFL_NO_WATER_VELOCITY_CHANGE = (1<<29), // Don't adjust this entity's velocity when transitioning into water + EFL_NO_PHYSCANNON_INTERACTION = (1<<30), // Physcannon can't pick these up or punt them + EFL_NO_DAMAGE_FORCES = (1<<31), // Doesn't accept forces from physics damage +}; + +/** + * Gets the Entity flags (m_iEFlags) of an entity. + * + * @param entity Entity index. + * @return Entity flags value + */ +stock Entity_Flags Entity_GetEFlags(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_iEFlags")); +} + +/** + * Sets the entity's Entity flags (m_iEFlags). + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_SetEFlags(int entity, Entity_Flags flags) +{ + SetEntProp(entity, Prop_Data, "m_iEFlags", flags); +} + +/** + * Adds Entity flags (m_iEFlags) to an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_AddEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags setFlags = Entity_GetEFlags(entity); + setFlags |= flags; + Entity_SetEFlags(entity, setFlags); +} + +/** + * Removes Entity flags (m_iEFlags) from an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_RemoveEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags setFlags = Entity_GetEFlags(entity); + setFlags &= ~flags; + Entity_SetEFlags(entity, setFlags); +} + +/** + * Checks if the entity has specific Entity flags (m_iEFlags) set. + * + * @param entity Entity index. + * @param flags Flags value + * @return True if the flags are set, false otherwise. + */ +stock bool Entity_HasEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags currentEFlags = Entity_GetEFlags(entity); + + return currentEFlags & flags == flags; +} + +/** + * Marks the surrounding bounds of an entity as outdated. + * You normally call this when a collision setting has changed. + * + * @param entity Entity index. + */ +stock void Entity_MarkSurrBoundsDirty(int entity) +{ + Entity_AddEFlags(entity, EFL_DIRTY_SURR_COLLISION_BOUNDS); +} + +/* + * CBaseEntity::m_fFlags Functions + * Use the FL_ Defines (FL_ONGROUND, ...) or + * special entity specific flags. + * Note: The flag FL_AIMTARGET probably doesn't work as + * we have current no way of adding/removing it to the AimTarget List. + */ + +/** + * Gets the Flags of an entity. + * + * @param entity Entity Index. + * @return Entity Flags. + */ +stock int Entity_GetFlags(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_fFlags"); +} + +/** + * Sets the Flags of an entity. + * + * @param entity Entity index. + * @param flags New Flags value + */ +stock void Entity_SetFlags(int entity, int flags) +{ + SetEntProp(entity, Prop_Data, "m_fFlags", flags); +} + +/** + * Adds Flags to the entity + * + * @param entity Entity index. + * @param flags Flags to add + * @noreturn + */ +stock void Entity_AddFlags(int entity, int flags) +{ + int setFlags = Entity_GetFlags(entity); + setFlags |= flags; + Entity_SetFlags(entity, setFlags); +} + +/** + * Removes flags from the entity + * + * @param entity Entity index. + * @param flags Flags to remove + */ +stock void Entity_RemoveFlags(int entity, int flags) +{ + int setFlags = Entity_GetFlags(entity); + setFlags &= ~flags; + Entity_SetFlags(entity, setFlags); +} + +/** + * Toggles the specified flag on the entity. + * Adds the flag to the entity if it doesn't exists + * or removes it otherwise. + * + * @param entity Entity index. + * @param flags Flag to Toggle + */ +stock void Entity_ToggleFlag(int entity, int flag) +{ + int setFlag = Entity_GetFlags(entity); + setFlag ^= flag; + Entity_SetFlags(entity, setFlag); +} + +/** + * Removes all flags from the entity + * + * @param entity Entity index. + */ +stock void Entity_ClearFlags(int entity) +{ + Entity_SetFlags(entity, 0); +} + +/* edict->solid values + * NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves + * SOLID only effects OTHER entities colliding with this one when they move - UGH! + * + * Solid type basically describes how the bounding volume of the object is represented + * NOTE: These numerical values are used in the FGD by the prop code (see prop_dynamic) + * Taken from: hl2sdk-ob-valve\public\const.h + */ + +enum SolidFlags_t +{ + FSOLID_CUSTOMRAYTEST = 0x0001, // Ignore solid type + always call into the entity for ray tests + FSOLID_CUSTOMBOXTEST = 0x0002, // Ignore solid type + always call into the entity for swept box tests + FSOLID_NOT_SOLID = 0x0004, // Are we currently not solid? + FSOLID_TRIGGER = 0x0008, // This is something may be collideable but fires touch functions + // even when it's not collideable (when the FSOLID_NOT_SOLID flag is set) + FSOLID_NOT_STANDABLE = 0x0010, // You can't stand on this + FSOLID_VOLUME_CONTENTS = 0x0020, // Contains volumetric contents (like water) + FSOLID_FORCE_WORLD_ALIGNED = 0x0040, // Forces the collision rep to be world-aligned even if it's SOLID_BSP or SOLID_VPHYSICS + FSOLID_USE_TRIGGER_BOUNDS = 0x0080, // Uses a special trigger bounds separate from the normal OBB + FSOLID_ROOT_PARENT_ALIGNED = 0x0100, // Collisions are defined in root parent's local coordinate space + FSOLID_TRIGGER_TOUCH_DEBRIS = 0x0200, // This trigger will touch debris objects + + FSOLID_MAX_BITS = 10 +}; + +/** + * Gets the solid flags of the entity + * + * @param entity Entity index. + * @return Solid Flags. + */ +stock SolidFlags_t Entity_GetSolidFlags(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2)); +} + +/** + * Sets the solid flags of the entity + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_SetSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t oldFlags = Entity_GetSolidFlags(entity); + flags = flags & view_as(0xFFFF); + + if (oldFlags == flags) { + return; + } + + SetEntProp(entity, Prop_Data, "m_usSolidFlags", flags, 2); + + // These two flags, if changed, can produce different surrounding bounds + if ((oldFlags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS)) != + (flags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS))) + { + Entity_MarkSurrBoundsDirty(entity); + } +} + +/** + * Adds solid flags to the entity + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_AddSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); + newFlags |= flags; + Entity_SetSolidFlags(entity, newFlags); +} + +/** + * Removes solid flags from the entity. + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_RemoveSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); + newFlags &= ~flags; + Entity_SetSolidFlags(entity, newFlags); +} + +/** + * Removes all solid flags from the entity. + * + * @param entity Entity index. + */ +stock void Entity_ClearSolidFlags(int entity) +{ + Entity_SetSolidFlags(entity, view_as(0)); +} + +/** + * Checks whether certain solid flags are set on the entity. + * + * @param entity Entity index. + * @param flags Solid Flags. + * @return True if the specified flags are set, false otherwise. + */ +stock bool Entity_SolidFlagsSet(int entity, SolidFlags_t flagMask) +{ + return Entity_GetSolidFlags(entity) & flagMask == flagMask; +} + +enum SolidType_t +{ + SOLID_NONE = 0, // no solid model + SOLID_BSP = 1, // a BSP tree + SOLID_BBOX = 2, // an AABB + SOLID_OBB = 3, // an OBB (not implemented yet) + SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw + SOLID_CUSTOM = 5, // Always call into the entity for tests + SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that + SOLID_LAST, +}; + +/** + * Gets the solidity type of the entity + * + * @param entity Entity index. + * @return Solid Type + */ +stock SolidType_t Entity_GetSolidType(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_nSolidType", 1)); +} + +/** + * Sets the solidity type of the entity + * + * @param entity Entity index. + * @param Solid Type value. + */ +stock void Entity_SetSolidType(int entity, SolidType_t value) +{ + SetEntProp(entity, Prop_Send, "m_nSolidType", value, 1); + Entity_MarkSurrBoundsDirty(entity); +} + +/** + * Checks whether the entity is solid or not. + * + * @param entity Entity index. + * @return True if the entity is solid, false otherwise. + */ +stock bool Entity_IsSolid(int entity) +{ + return (Entity_GetSolidType(entity) != SOLID_NONE && + !Entity_SolidFlagsSet(entity, FSOLID_NOT_SOLID)); +} + +/** + * Retrieves the model path of a given entity. + * Returns "*num" for Brush entities. + * + * @param entity entity reference or index + * @param model buffer String for the model + * @param size max size of buffer string + * @return Number of non-null bytes written. + */ +stock int Entity_GetModel(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, size); +} + +/** + * Sets the model to a given entity. + * Be sure it has been precached. + * This is an alias for SetEntityModel() + * + * @param entity Entity index + * @param model Model name + */ +stock void Entity_SetModel(int entity, const char[] model) +{ + SetEntityModel(entity, model); +} + +/** + * Gets the entity's model index, if it has one set. + * + * @param entity Entity index. + * @return The Entity's model index + */ +stock int Entity_GetModelIndex(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_nModelIndex", 2); +} + +/** + * Sets the entity's model index (must be precached) + * + * @param entity Entity index. + * @param index Model Index. + */ +stock void Entity_SetModelIndex(int entity, int index) +{ + SetEntProp(entity, Prop_Data, "m_nModelIndex", index, 2); +} + +/** +* Sets the entity's maxspeed to the given value (in units per second) +* +* @param entity Entity index +* @param maxspeed the maximum speed the entity can move +* @noreturn +*/ +stock void Entity_SetMaxSpeed(int entity, float value) +{ + SetEntPropFloat(entity, Prop_Data, "m_flMaxspeed", value); +} + +/* + * Collision groups + * Taken from hl2sdk-ob-valve/public/const.h + */ +enum Collision_Group_t +{ + COLLISION_GROUP_NONE = 0, + COLLISION_GROUP_DEBRIS, // Collides with nothing but world and static stuff + COLLISION_GROUP_DEBRIS_TRIGGER, // Same as debris, but hits triggers + COLLISION_GROUP_INTERACTIVE_DEB, // Collides with everything except other interactive debris or debris + COLLISION_GROUP_INTERACTIVE, // Collides with everything except interactive debris or debris + COLLISION_GROUP_PLAYER, + COLLISION_GROUP_BREAKABLE_GLASS, + COLLISION_GROUP_VEHICLE, + COLLISION_GROUP_PLAYER_MOVEMENT, // For HL2, same as Collision_Group_Player, for + // TF2, this filters out other players and CBaseObjects + COLLISION_GROUP_NPC, // Generic NPC group + COLLISION_GROUP_IN_VEHICLE, // for any entity inside a vehicle + COLLISION_GROUP_WEAPON, // for any weapons that need collision detection + COLLISION_GROUP_VEHICLE_CLIP, // vehicle clip brush to restrict vehicle movement + COLLISION_GROUP_PROJECTILE, // Projectiles! + COLLISION_GROUP_DOOR_BLOCKER, // Blocks entities not permitted to get near moving doors + COLLISION_GROUP_PASSABLE_DOOR, // Doors that the player shouldn't collide with + COLLISION_GROUP_DISSOLVING, // Things that are dissolving are in this group + COLLISION_GROUP_PUSHAWAY, // Nonsolid on client and server, pushaway in player code + + COLLISION_GROUP_NPC_ACTOR, // Used so NPCs in scripts ignore the player. + COLLISION_GROUP_NPC_SCRIPTED // USed for NPCs in scripts that should not collide with each other +}; + +/** + * Gets the collision group of an entity. + * + * @param entity entity index + * @return Entity collision group. + */ +stock Collision_Group_t Entity_GetCollisionGroup(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_CollisionGroup")); +} + +/** + * Sets the collision group of an entity. + * + * @param entity entity index + * @param value the new collision group. + */ +stock void Entity_SetCollisionGroup(int entity, Collision_Group_t value) +{ + SetEntProp(entity, Prop_Data, "m_CollisionGroup", value); +} + +/** + * Functions for getting / setting the origin (position) of an entity. + * Go to http://developer.valvesoftware.com/wiki/Origin + * if you want to learn more about origins + */ + +/** + * Gets the Absolute Origin (position) of an entity. + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_GetAbsOrigin(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", vec); +} + +/** + * Sets the Absolute Origin (position) of an entity. + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_SetAbsOrigin(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the origin more safely + // Todo: Replace this with a call to UTIL_SetOrigin() or CBaseEntity::SetLocalOrigin() + TeleportEntity(entity, vec, NULL_VECTOR, NULL_VECTOR); +} + +/** + * Functions for getting / setting the angles (rotation) of an entity. + * http://developer.valvesoftware.com/wiki/Angles + * if you want to learn more about angles + */ + +/** + * Gets the Angles of an entity + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + * @noreturn + */ +stock void Entity_GetAbsAngles(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_angAbsRotation", vec); +} + +/** + * Sets the Angles of an entity + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_SetAbsAngles(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the angles more safely + // Todo: Replace this with a call to CBaseEntity::SetLocalAngles() + TeleportEntity(entity, NULL_VECTOR, vec, NULL_VECTOR); +} + +/** + * Functions for getting / setting the velocity of an entity. + * Go to http://developer.valvesoftware.com/wiki/Velocity + * if you want to learn more about the different kind of velocities. + */ + +/** + * Gets the Local velocity of an entity. + * The local velocity is the velocity generated by the entity. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetLocalVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); +} + +/** + * Sets the Local velocity of an entity. + * The local velocity is the velocity generated by the entity. + * Only use this if you know what you are doing, + * the entity can overwrite this value on next frame. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetLocalVelocity(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); +} + +/** + * Gets the Base velocity of an entity. + * The base velocity is the velocity applied + * to the entity from other sources . + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetBaseVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); +} + +/** + * Sets the Base velocity of an entity. + * The base velocity is the velocity applied + * to the entity from other sources . + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetBaseVelocity(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); +} + +/** + * Gets the Absolute velocity of an entity. + * The absolute velocity is the sum of the local + * and base velocities. It's the actual value used to move. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetAbsVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecAbsVelocity", vec); +} + +/** + * Sets the Absolute velocity of an entity. + * The absolute velocity is the sum of the local + * and base velocities. It's the actual value used to move. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetAbsVelocity(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the velocity more safely + // Todo: Replace this with a call to CBaseEntity::SetAbsVelocity() + TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, vec); +} + +/** + * Returns true if the entity is locked. + * + * @param entity Entity index. + * @return True if locked otherwise false. + */ +stock bool Entity_IsLocked(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bLocked", 1) != 0; +} + +/** + * Locks an entity. + * + * @param entity Entity index. + */ +stock void Entity_Lock(int entity) +{ + SetEntProp(entity, Prop_Data, "m_bLocked", 1, 1); +} +/** + * Unlocks an entity. + * + * @param entity Entity index. + */ +stock void Entity_UnLock(int entity) +{ + SetEntProp(entity, Prop_Data, "m_bLocked", 0, 1); +} + +/** + * Gets the health of an entity. + * + * @param entity entity index. + * @return current health points + */ +stock int Entity_GetHealth(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iHealth"); +} + +/** + * Sets the health of an entity. + * + * @param entity Entity index. + * @param value Health to set (anything above 511 will overload) + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return The health the entity actually got set to. + */ +stock int Entity_SetHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = value; + + if (!ignoreMax) { + int maxHealth = Entity_GetMaxHealth(entity); + + if (health > maxHealth) { + health = maxHealth; + } + } + + if (health < 0) { + health = 0; + } + + SetEntProp(entity, Prop_Data, "m_iHealth", health); + + if (health <= 0) { + Entity_Kill(entity); + } + + return health; +} + +/** + * Add health to an entity + * + * @param entity Entity index + * @param value Health to add + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return Returns the new health value set + */ +stock int Entity_AddHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = Entity_GetHealth(entity); + + health += value; + + return Entity_SetHealth(entity, health, ignoreMax, kill); +} + +/** + * Takes health from an entity + * + * @param entity entity index + * @param value health to add + * @return returns the new health value set + */ +stock int Entity_TakeHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = Entity_GetHealth(entity); + + health -= value; + + return Entity_SetHealth(entity, health, ignoreMax, kill); +} + +/** + * Get the max health of an entity + * + * @param entity Entity Index + * @return Max health points + */ +stock int Entity_GetMaxHealth(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iMaxHealth"); +} + + +/** + * Set the max health of an entity. + * + * @param entity Entity index + * @param value Max health to set (anything above 511 will overload) + */ +stock void Entity_SetMaxHealth(int entity, int value) +{ + SetEntProp(entity, Prop_Data, "m_iMaxHealth", value); +} + +/** + * Returns the Float distance between an entity + * and a vector origin. + * + * @param entity Entity Index. + * @param target Vector Origin. + * @return Distance Float value. + */ +stock float Entity_GetDistanceOrigin(int entity, const float vec[3]) +{ + float entityVec[3]; + Entity_GetAbsOrigin(entity, entityVec); + + return GetVectorDistance(entityVec, vec); +} + +/** + * Returns the Float distance between two entities. + * Both entities must be valid. + * + * @param entity Entity Index. + * @param target Target Entity Index. + * @return Distance Float value. + */ +stock float Entity_GetDistance(int entity, int target) +{ + float targetVec[3]; + Entity_GetAbsOrigin(target, targetVec); + + return Entity_GetDistanceOrigin(entity, targetVec); +} + +/** + * Checks if the given 2 entitys are within a given range. + * + * @param entity Entity Index. + * @param target Target Entity Index. + * @param distance Max Float distance. + * @return True if the given entities are closer than the given distance value, false otherwise. + */ +stock bool Entity_InRange(int entity, int target, float distance) +{ + if (Entity_GetDistance(entity, target) > distance) { + return false; + } + + return true; +} + +/** + * Enables the motion of an entity. + * + * @param entity Entity index. + * @return True on success, false otherwise + */ +stock bool Entity_EnableMotion(int entity) +{ + return AcceptEntityInput(entity, "enablemotion"); +} + +/** + * Disables the motion of an entity. + * + * @param entity Entity index. + * @return True on success, false otherwise + */ +stock bool Entity_DisableMotion(int entity) +{ + return AcceptEntityInput(entity, "disablemotion"); +} + +/** + * Freezes an entity by setting the FL_FROZEN flag. + * + * @param entity Entity index. + */ +stock void Entity_Freeze(int entity) +{ + Entity_AddFlags(entity, FL_FROZEN); +} + +/** + * Unfreezes an entity by removing the FL_FROZEN flag. + * + * @param entity Entity index. + */ +stock void Entity_UnFreeze(int entity) +{ + Entity_RemoveFlags(entity, FL_FROZEN); +} + + +/** + * This function points an entity to another with the targetname + * and name. Useful for allot of entities like trigger_teleport. + * If the name is not specified it will be generated automatically. + * + * @param entity Entity index. + * @param target Target entity index. + * @param Optional: target name + */ +stock void Entity_PointAtTarget(int entity, int target, const char[] name="") +{ + char targetName[128]; + Entity_GetTargetName(entity, targetName, sizeof(targetName)); + + if (name[0] == '\0') { + + if (targetName[0] == '\0') { + // Let's generate our own name + Format( + targetName, + sizeof(targetName), + "_smlib_Entity_PointAtTarget:%d", + target + ); + } + } + else { + strcopy(targetName, sizeof(targetName), name); + } + + Entity_SetTargetName(entity, targetName); + Entity_SetName(target, targetName); +} + +/** + * This function points a point_hurt entity to another damage target entity.. + * and name. Useful for allot of entities like trigger_teleport. + * If the name is not specified it will be generated automatically. + * + * @param entity Entity index. + * @param target Target entity index. + * @param Optional: target name + */ +stock void Entity_PointHurtAtTarget(int entity, int target, const char[] name="") +{ + char targetName[128]; + Entity_GetTargetName(entity, targetName, sizeof(targetName)); + + if (name[0] == '\0') { + + if (targetName[0] == '\0') { + // Let's generate our own name + Format( + targetName, + sizeof(targetName), + "_smlib_Entity_PointHurtAtTarget:%d", + target + ); + } + } + else { + strcopy(targetName, sizeof(targetName), name); + } + + DispatchKeyValue(entity, "DamageTarget", targetName); + Entity_SetName(target, targetName); +} + +/** + * Checks if an entity is a player or not. + * No checks are done if the entity is actually valid, + * the player is connected or ingame. + * + * @param entity Entity index. + * @return True if the entity is a player, false otherwise. + */ +stock bool Entity_IsPlayer(int entity) +{ + if (entity < 1 || entity > MaxClients) { + return false; + } + + return true; +} + +/** + * Creates an entity by classname. + * + * @param className Classname String. + * @param ForceEdictIndex Edict Index to use. + * @return Entity Index or INVALID_ENT_REFERENCE if the slot is already in use. + */ +stock int Entity_Create(const char[] className, int ForceEdictIndex=-1) +{ + if (ForceEdictIndex != -1 && Entity_IsValid(ForceEdictIndex)) { + return INVALID_ENT_REFERENCE; + } + + return CreateEntityByName(className, ForceEdictIndex); +} + +/** + * Kills an entity on the next frame (delayed). + * It is safe to use with entity loops. + * If the entity is is player ForcePlayerSuicide() is called. + * + * @param kenny Entity index. + * @param killChildren When true, kennys children are killed too. + * @return True on success, false otherwise. + */ +stock bool Entity_Kill(int kenny, bool killChildren=false) +{ + if (Entity_IsPlayer(kenny)) { + // Oh My God! They Killed Kenny!! + ForcePlayerSuicide(kenny); + return true; + } + + if(killChildren){ + return AcceptEntityInput(kenny, "KillHierarchy"); + } + else { + return AcceptEntityInput(kenny, "Kill"); + } +} + +/** + * Kills all entities with the given networked classname. + * It is safe to use with entity loops. + * If the entity is is player ForcePlayerSuicide() is called. + * + * @param className Entity Network Class to search for. + * @return Number of entities killed. + */ +stock int Entity_KillAllByClassName(const char[] className) +{ + int x = 0; + + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "kill"); + x++; + } + + return x; +} + +/** + * Gets the owner of an entity. + * For example the owner of a weapon entity. + * + * @param entity Entity index. + * @return Ground Entity or -1 + */ +stock int Entity_GetOwner(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); +} + +/** + * Sets the owner of an entity. + * For example the owner of a weapon entity. + * + * @param entity Entity index. + */ +stock void Entity_SetOwner(int entity, int newOwner) +{ + SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", newOwner); +} + +/** + * Get's the ground entity this entity stands on. + * + * @param entity Entity index. + * @return Ground Entity or -1 + */ +stock int Entity_GetGroundEntity(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_hGroundEntity"); +} + +/* + * Damage definitions + */ + +#if !defined DMG_GENERIC + +#define DMG_GENERIC 0 // generic damage was done +#define DMG_CRUSH (1 << 0) // crushed by falling or moving object. + // NOTE: It's assumed crush damage is occurring as a result of physics collision, so no extra physics force is generated by crush damage. + // DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics collision. You probably want DMG_CLUB instead. +#define DMG_BULLET (1 << 1) // shot +#define DMG_SLASH (1 << 2) // cut, clawed, stabbed +#define DMG_BURN (1 << 3) // heat burned +#define DMG_VEHICLE (1 << 4) // hit by a vehicle +#define DMG_FALL (1 << 5) // fell too far +#define DMG_BLAST (1 << 6) // explosive blast damage +#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt +#define DMG_SHOCK (1 << 8) // electric shock +#define DMG_SONIC (1 << 9) // sound pulse shockwave +#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam +#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) // Prevent a physics force +#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death +#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death. +#define DMG_DROWN (1 << 14) // Drowning + + +#define DMG_PARALYZE (1 << 15) // slows affected creature down +#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad +#define DMG_POISON (1 << 17) // blood poisoning - heals over time like drowning damage +#define DMG_RADIATION (1 << 18) // radiation exposure +#define DMG_DROWNRECOVER (1 << 19) // drowning recovery +#define DMG_ACID (1 << 20) // toxic chemicals or acid burns +#define DMG_SLOWBURN (1 << 21) // in an oven + +#define DMG_REMOVENORAGDOLL (1<<22) // with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. + // use this to kill an entity that you've already got a server-side ragdoll for + +#define DMG_PHYSGUN (1<<23) // Hit by manipulator. Usually doesn't do any damage. +#define DMG_PLASMA (1<<24) // Shot by Cremator +#define DMG_AIRBOAT (1<<25) // Hit by the airboat's gun + +#define DMG_DISSOLVE (1<<26) // Dissolving! +#define DMG_BLAST_SURFACE (1<<27) // A blast on the surface of water that cannot harm things underwater +#define DMG_DIRECT (1<<28) +#define DMG_BUCKSHOT (1<<29) // not quite a bullet. Little, rounder, different. + +#endif + +/** + * Does damage to an entity. + * This is a powerful function that allows you to specify + * who the attacker is, the damage type and also what weapon + * should be displayed in the hud kill message. + * Note that for entities that fire another entity (RPG's, Crossbow's, + * you have to pass the bullet's class, not the weapon's class ! + * It hasn't been tested how expensive this function is, as it + * uses the entity point_hurt. + * If you need a cheaper function use Entity_RemoveHealth(). + * + * @param entity Entity index. + * @param damage Amount of damage. + * @param attacker Entity Index of the attacker. + * @param damageType Use the DMG_ definations. + * @param fakeClassName Classname to fake, you can set this if you + * want a specific weapon to be shown in the HUD kill message. + * @param customOrigin Teleport point_hurt to origin before triggering hurt + * useful for damage force calculations e.g. explosions, gun fire direction, ect. + * @return True on success, false otherwise. + */ +stock bool Entity_Hurt(int entity, int damage, int attacker=0, int damageType=DMG_GENERIC, const char[] fakeClassName="", float customOrigin[3]={0.0, 0.0, 0.0}) +{ + static int point_hurt = INVALID_ENT_REFERENCE; + + if (point_hurt == INVALID_ENT_REFERENCE || !IsValidEntity(point_hurt)) { + point_hurt = EntIndexToEntRef(Entity_Create("point_hurt")); + + if (point_hurt == INVALID_ENT_REFERENCE) { + return false; + } + + DispatchSpawn(point_hurt); + } + + AcceptEntityInput(point_hurt, "TurnOn"); + SetEntProp(point_hurt, Prop_Data, "m_nDamage", damage); + SetEntProp(point_hurt, Prop_Data, "m_bitsDamageType", damageType); + + char orignalTargetName[128]; + Entity_GetName(entity, orignalTargetName, sizeof(orignalTargetName)); + Entity_PointHurtAtTarget(point_hurt, entity); + + if (fakeClassName[0] != '\0') { + Entity_SetClassName(point_hurt, fakeClassName); + } + + TeleportEntity(point_hurt, customOrigin, NULL_VECTOR, NULL_VECTOR); + + AcceptEntityInput(point_hurt, "Hurt", attacker); + AcceptEntityInput(point_hurt, "TurnOff"); + + if (fakeClassName[0] != '\0') { + Entity_SetClassName(point_hurt, "point_hurt"); + } + + DispatchKeyValue(entity, "targetname", orignalTargetName); + return true; +} + +/* + * Gets the parent entity of an entity. + * + * @param entity Entity Index. + * @return Entity Index of the parent. + */ +stock int Entity_GetParent(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_pParent"); +} + +/* + * Clears the parent of an entity. + * + * @param entity Entity Index. + */ +stock void Entity_ClearParent(int entity) +{ + //SetVariantString(""); + AcceptEntityInput(entity, "ClearParent"); +} + +/* + * Sets the parent entity of an entity. + * + * @param entity Entity Index. + * @param parent Entity Index of the new parent. + */ +stock void Entity_SetParent(int entity, int parent) +{ + SetVariantString("!activator"); + AcceptEntityInput(entity, "SetParent", parent); +} + + +/* + * Callback for Change_OverTime. + * Note that every parameter is a reference and can be changed during this callback. + * You can get the elapsed time since start by multiply tick with currentCall. + * + * @param entity Entity Index. + * @param interval The current interval from the current game time to execute the next call of this function. + * @param currentCall The current call number (0 is the 1st call at 0.0 seconds, 1 the 2nd call at tick*1 seconds, ...). + * @return When true this callback will be called again at the next defined tick, otherwise it won't. + */ +typedef Entity_ChangeOverTimeCallback = function bool (int &entity, float &interval, int ¤tCall); + +/* + * Creates a timer and provides a callback to change various things about an entity over time. + * + * @param entity Entity Index. + * @param interval Interval from the current game time to execute the given function. + * @noreturn + */ +stock void Entity_ChangeOverTime(int entity, float interval=0.1, Entity_ChangeOverTimeCallback valueCallback) +{ + DataPack dataPack = CreateDataPack(); + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackFloat(dataPack, interval); + WritePackCell(dataPack, 0); + WritePackFunction(dataPack, valueCallback); + ResetPack(dataPack); + __smlib_Timer_ChangeOverTime(INVALID_HANDLE,dataPack); +} + +public Action __smlib_Timer_ChangeOverTime(Handle Timer, DataPack dataPack) +{ + int entity = EntRefToEntIndex(ReadPackCell(dataPack)); + if(!Entity_IsValid(entity)){ + return Plugin_Stop; + } + + float interval = ReadPackFloat(dataPack); + int currentCall = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); + + any result; + Call_StartFunction(INVALID_HANDLE, callback); + Call_PushCellRef(entity); + Call_PushFloatRef(interval); + Call_PushCellRef(currentCall); + Call_Finish(result); + + if(result == false){ + return Plugin_Stop; + } + + ResetPack(dataPack,true); + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackFloat(dataPack, interval); + WritePackCell(dataPack, currentCall+1); + WritePackFunction(dataPack, callback); + ResetPack(dataPack); + CreateTimer(interval, __smlib_Timer_ChangeOverTime, dataPack); + return Plugin_Stop; +} + + +/** + * Gets the next child, entity is parent of. + * + * @param parent Entity Index (of Parent) + * @param start Start Index. + * @return Entity Index or -1 if no entity was found. + */ +stock int Entity_GetNextChild(int parent, int start=0) +{ + int maxEntities = GetMaxEntities(); + for (int entity=start; entity < maxEntities; entity++) { + + if (!Entity_IsValid(entity)) { + continue; + } + + if (entity > 0 && entity <= MaxClients && !IsClientConnected(entity)) { + continue; + } + + if (Entity_GetParent(entity) == parent) { + return entity; + } + } + + return INVALID_ENT_REFERENCE; +} +/** + * Gets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). + * Ex: if vec[2] is 1.0 a func_door moves straight up. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_GetMoveDirection(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); +} +/** + * Sets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). + * Ex: if vec[2] is 1.0 a func_door moves straight up. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_SetMoveDirection(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); +} + +/** + * Returns if the entity will force close (won't be blockable by players and/or objects) or not when triggered to move. + * + * @param entity Entity index. + * @return True if the door will force close, otherwise false. + */ +stock bool Entity_GetForceClose(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bForceClosed") != 0; +} + +/** + * Sets if the door should force close (souldn't be blockable by players and/or objects) or not when triggered to move. + * + * @param entity Entity index. + * @param forceClose If true the door will force close, otherwise it won't. + */ +stock void Entity_SetForceClose(int entity, bool forceClose) +{ + SetEntProp(entity, Prop_Data, "m_bForceClosed", forceClose); +} + +/** + * Gets the speed of a moving entity (like doors: open close speed). + * + * @param entity Entity index. + * @return Speed of the entity. + */ +stock float Entity_GetSpeed(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flSpeed"); +} + +/** + * Sets how fast an entity moves (like doors: open close speed). + * + * @param entity Entity index. + * @param speed The new speed of the entity. + */ +stock void Entity_SetSpeed(int entity, float speed) +{ + SetEntPropFloat(entity, Prop_Data, "m_flSpeed", speed); +} + +/** + * Gets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). + * Note: Negative values add health to the blocking entity. + * + * @param entity Entity index. + * @return Damage. + */ +stock float Entity_GetBlockDamage(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flBlockDamage"); +} + +/** + * Sets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). + * Note: Negative values add health to the blocking entity. + * + * @param entity Entity index. + * @param damage Damage. + */ +stock void Entity_SetBlockDamage(int entity, float damage) +{ + SetEntPropFloat(entity, Prop_Data, "m_flBlockDamage", damage); +} + +/** + * Returns if the given entity is disabled or not. + * + * @param entity Entity index. + * @return True if entity is disabled, otherwise false. + */ +stock bool Entity_IsDisabled(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bDisabled", 1) != 0; +} + +/** + * Disables the given entity. + * + * @param entity Entity index. + * @return True if successful otherwise false. + */ +stock bool Entity_Disable(int entity) +{ + return AcceptEntityInput(entity, "Disable"); +} + +/** + * Enables the given entity. + * + * @param entity Entity index. + * @return True if successful otherwise false. + */ +stock bool Entity_Enable(int entity) +{ + return AcceptEntityInput(entity, "Enable"); +} + + +// settings for m_takedamage taken from hl2sdk-ob-valve\game\shared\shareddefs.h +#define DAMAGE_NO 0 +#define DAMAGE_EVENTS_ONLY 1 // Call damage functions, but don't modify health +#define DAMAGE_YES 2 +#define DAMAGE_AIM 3 + +/** + * Sets the mode for an entity to take damage. + * Note: This is used to give a client god mode (DAMAGE_NO). + * + * @param entity Entity index. + * @param value Mode, use DAMAGE_* defines. + */ +stock void Entity_SetTakeDamage(int entity, int value) +{ + SetEntProp(entity, Prop_Data, "m_takedamage", value, 1); +} + +/** + * Gets the mode for an entity to take damage. + * Note: When the return value is DAMAGE_NO then the client is using godmode. + * + * @param entity Entity index. + * @return Take damage mode (DAMAGE_*). + */ +stock int Entity_GetTakeDamage(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_takedamage", 1); +} + +/** + * Sets the minimum of damage required to hurt this entity. + * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. + * + * @param entity Entity index. + * @param minDamage Minimum required damage. + */ +stock void Entity_SetMinHealthDamage(int entity, int minDamage) +{ + SetEntProp(entity, Prop_Data, "m_iMinHealthDmg", minDamage); +} + +/** + * Gets the minimum of damage required to hurt this entity. + * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. + * + * @param entity Entity index. + * @return Minimum required damage. + */ +stock int Entity_GetMinHealthDamage(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iMinHealthDmg"); +} + +/** + * Gets an entity's color. + * + * @param entity Entity index + * @param color 4 dimensional array where [r,g,b,a] values are stored + * @error Invalid entity index, or lack of mod compliance. + */ +stock void Entity_GetRenderColor(int entity, int color[4]) +{ + static bool gotconfig = false; + static char prop[32]; + + if (!gotconfig) { + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; + + if (!exists) { + strcopy(prop, sizeof(prop), "m_clrRender"); + } + + gotconfig = true; + } + + int offset = GetEntSendPropOffs(entity, prop); + + if (offset <= 0) { + ThrowError("SetEntityRenderColor not supported by this mod"); + } + + for (int i=0; i < 4; i++) { + color[i] = GetEntData(entity, offset + i, 1); + } +} + +/** + * Sets an entity's color. + * Doesn't change the value, if set to -1. + * + * @param entity Entity index + * @param r Amount of red (0-255) + * @param g Amount of green (0-255) + * @param b Amount of blue (0-255) + * @param a Amount of alpha (0-255) + * @error Invalid entity index, or lack of mod compliance. + */ +stock void Entity_SetRenderColor(int entity, int r=-1, int g=-1, int b=-1, int a=-1) +{ + static bool gotconfig = false; + static char prop[32]; + + if (!gotconfig) { + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; + + if (!exists) { + strcopy(prop, sizeof(prop), "m_clrRender"); + } + + gotconfig = true; + } + + int offset = GetEntSendPropOffs(entity, prop); + + if (offset <= 0) { + ThrowError("SetEntityRenderColor not supported by this mod"); + } + + if(r != -1) { + SetEntData(entity, offset, r, 1, true); + } + + if(g != -1) { + SetEntData(entity, offset + 1, g, 1, true); + } + + if(b != -1) { + SetEntData(entity, offset + 2, b, 1, true); + } + + if(a != -1) { + SetEntData(entity, offset + 3, a, 1, true); + } +} + +/** + * Sends the 'addouput' command to an entity. + * + * @param entity Entity Index. + * @param input Input command. + * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). + * @param caller Entity index from which this event is sent (-1 for a NULL entity). + * @param outputid Unknown. + * @return True if successful, otherwise false. + */ +stock bool Entity_AddOutput(int entity, const char[] input, int activator=-1, int caller=-1, int outputid=0) +{ + SetVariantString(input); + return AcceptEntityInput(entity, "addoutput", activator, caller, outputid); +} diff --git a/scripting/include/smlib/files.inc b/scripting/include/smlib/files.inc new file mode 100644 index 0000000..a31d606 --- /dev/null +++ b/scripting/include/smlib/files.inc @@ -0,0 +1,451 @@ +#if defined _smlib_files_included + #endinput +#endif +#define _smlib_files_included + +#include +#include +#include + +/** + * Gets the Base name of a path. + * Examples: + * blub.txt -> "blub.txt" + * /sourcemod/extensions/example.ext.so -> "example.ext.so" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetBaseName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + int pos_start = FindCharInString(path, '/', true); + + if (pos_start == -1) { + pos_start = FindCharInString(path, '\\', true); + } + + pos_start++; + + strcopy(buffer, size, path[pos_start]); +} + +/** + * Gets the Directory of a path (without the file name). + * Does not work with "." as the path. + * Examples: + * blub.txt -> "blub.txt" + * /sourcemod/extensions/example.ext.so -> "example.ext.so" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetDirName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + int pos_start = FindCharInString(path, '/', true); + + if (pos_start == -1) { + pos_start = FindCharInString(path, '\\', true); + + if (pos_start == -1) { + buffer[0] = '\0'; + return; + } + } + + strcopy(buffer, size, path); + buffer[pos_start] = '\0'; +} + +/** + * Gets the File name of a path. + * blub.txt -> "blub" + * /sourcemod/extensions/example.ext.so -> "example.ext" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetFileName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + File_GetBaseName(path, buffer, size); + + int pos_ext = FindCharInString(buffer, '.', true); + + if (pos_ext != -1) { + buffer[pos_ext] = '\0'; + } +} + +/** + * Gets the Extension of a file. + * Examples: + * blub.inc.txt -> "txt" + * /sourcemod/extensions/example.ext.so -> "so" + * + * @param path Path String + * @param buffer String buffer array + * @param size Max length of string buffer + */ +stock void File_GetExtension(const char[] path, char[] buffer, int size) +{ + int extpos = FindCharInString(path, '.', true); + + if (extpos == -1) { + buffer[0] = '\0'; + return; + } + + strcopy(buffer, size, path[++extpos]); +} + +/** + * Adds a path to the downloadables network string table. + * This can be a file or directory and also works recursed. + * You can optionally specify file extensions that should be ignored. + * Bz2 and ztmp are automatically ignored. + * It only adds files that actually exist. + * You can also specify a wildcard * after the ., very useful for models. + * This forces a client to download the file if they do not already have it. + * + * @param path Path String + * @param recursive Whether to do recursion or not. + * @param ignoreExts Optional: 2 dimensional String array.You can define it like this: new String:ignore[][] = { ".ext1", ".ext2" }; + * @param size This should be set to the number of file extensions in the ignoreExts array (sizeof(ignore) for the example above) + */ + +// Damn you SourcePawn :( I didn't want to +char _smlib_empty_twodimstring_array[][] = { { '\0' } }; +stock void File_AddToDownloadsTable(const char[] path, bool recursive=true, const char[][] ignoreExts=_smlib_empty_twodimstring_array, int size=0) +{ + if (path[0] == '\0') { + return; + } + + if (FileExists(path)) { + + char fileExtension[5]; + File_GetExtension(path, fileExtension, sizeof(fileExtension)); + + if (StrEqual(fileExtension, "bz2", false) || StrEqual(fileExtension, "ztmp", false)) { + return; + } + + if (Array_FindString(ignoreExts, size, fileExtension) != -1) { + return; + } + + char path_new[PLATFORM_MAX_PATH]; + strcopy(path_new, sizeof(path_new), path); + ReplaceString(path_new, sizeof(path_new), "//", "/"); + + AddFileToDownloadsTable(path_new); + } + else if (recursive && DirExists(path)) { + + char dirEntry[PLATFORM_MAX_PATH]; + DirectoryListing __dir = OpenDirectory(path); + + while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { + + if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { + continue; + } + + Format(dirEntry, sizeof(dirEntry), "%s/%s", path, dirEntry); + File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); + } + + delete __dir; + } + else if (FindCharInString(path, '*', true)) { + + char fileExtension[4]; + File_GetExtension(path, fileExtension, sizeof(fileExtension)); + + if (StrEqual(fileExtension, "*")) { + + char dirName[PLATFORM_MAX_PATH], + fileName[PLATFORM_MAX_PATH], + dirEntry[PLATFORM_MAX_PATH]; + + File_GetDirName(path, dirName, sizeof(dirName)); + File_GetFileName(path, fileName, sizeof(fileName)); + StrCat(fileName, sizeof(fileName), "."); + + DirectoryListing __dir = OpenDirectory(dirName); + while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { + + if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { + continue; + } + + if (strncmp(dirEntry, fileName, strlen(fileName)) == 0) { + Format(dirEntry, sizeof(dirEntry), "%s/%s", dirName, dirEntry); + File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); + } + } + + delete __dir; + } + } +} + + +/* + * Adds all files/paths in the given text file to the download table. + * Recursive mode enabled, see File_AddToDownloadsTable() + * Comments are allowed ! Supported comment types are ; // # + * + * @param path Path to the .txt file. + */ +stock void File_ReadDownloadList(const char[] path) +{ + File file = OpenFile(path, "r"); + + if (file == INVALID_HANDLE) { + return; + } + + char buffer[PLATFORM_MAX_PATH]; + while (!IsEndOfFile(file)) { + ReadFileLine(file, buffer, sizeof(buffer)); + + int pos; + pos = StrContains(buffer, "//"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + pos = StrContains(buffer, "#"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + pos = StrContains(buffer, ";"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + TrimString(buffer); + + if (buffer[0] == '\0') { + continue; + } + + File_AddToDownloadsTable(buffer); + } + + delete file; +} + +/* + * Attempts to load a translation file and optionally unloads the plugin if the file + * doesn't exist (also prints an error message). + * + * @param file Filename of the translations file (eg. .phrases). + * @param setFailState If true, it sets the failstate if the translations file doesn't exist + * @return True on success, false otherwise (only if setFailState is set to false) + */ +stock bool File_LoadTranslations(const char[] file, bool setFailState=true) +{ + char path[PLATFORM_MAX_PATH]; + + BuildPath(Path_SM, path, sizeof(path), "translations/%s", file); + + if (FileExists(path)) { + LoadTranslations(file); + return true; + } + + Format(path,sizeof(path), "%s.txt", path); + + if (!FileExists(path)) { + + if (setFailState) { + SetFailState("Unable to locate translation file (%s).", path); + } + + return false; + } + + LoadTranslations(file); + + return true; +} + +/* + * Reads the contents of a given file into a string buffer in binary mode. + * + * @param path Path to the file + * @param buffer String buffer + * @param size If -1, reads until a null terminator is encountered in the file. Otherwise, read_count bytes are read into the buffer provided. In this case the buffer is not explicitly null terminated, and the buffer will contain any null terminators read from the file. + * @return Number of characters written to the buffer, or -1 if an error was encountered. + */ +stock int File_ToString(const char[] path, char[] buffer, int size) +{ + File file = OpenFile(path, "rb"); + + if (file == INVALID_HANDLE) { + buffer[0] = '\0'; + return -1; + } + + int num_bytes_written = ReadFileString(file, buffer, size); + delete file; + + return num_bytes_written; +} + +/* + * Writes a string into a file in binary mode. + * + * @param file Path to the file + * @param str String to write + * @return True on success, false otherwise + */ +stock bool File_StringToFile(const char[] path, char[] str) +{ + File file = OpenFile(path, "wb"); + + if (file == INVALID_HANDLE) { + return false; + } + + bool success = WriteFileString(file, str, false); + delete file; + + return success; +} + +/* + * Copies file source to destination + * Based on code of javalia: + * http://forums.alliedmods.net/showthread.php?t=159895 + * + * @param source Input file + * @param destination Output file + * @return True on success, false otherwise + */ +stock bool File_Copy(const char[] source, const char[] destination) +{ + File file_source = OpenFile(source, "rb"); + + if (file_source == INVALID_HANDLE) { + return false; + } + + File file_destination = OpenFile(destination, "wb"); + + if (file_destination == INVALID_HANDLE) { + delete file_source; + return false; + } + + int buffer[32]; + int cache; + + while (!IsEndOfFile(file_source)) { + cache = ReadFile(file_source, buffer, sizeof(buffer), 1); + WriteFile(file_destination, buffer, cache, 1); + } + + delete file_source; + delete file_destination; + + return true; +} + +/* + * Recursively copies (the content) of a directory or file specified + * by "path" to "destination". + * Note that because of Sourcemod API limitations this currently does not + * takeover the file permissions (it leaves them default). + * Links will be resolved. + * + * @param path Source path + * @param destination Destination directory (This can only be a directory) + * @param stop_on_error Optional: Set to true to stop on error (ie can't read a file) + * @param dirMode Optional: File mode for directories that will be created (Default = 0755), don't forget to convert FROM octal + * @return True on success, false otherwise + */ +stock bool File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, int dirMode=493) +{ + if (FileExists(path)) { + return File_Copy(path, destination); + } + else if (DirExists(path)) { + return Sub_File_CopyRecursive(path, destination, stop_on_error, FileType_Directory, dirMode); + } + else { + return false; + } +} + +static stock bool Sub_File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, FileType fileType, int dirMode) +{ + if (fileType == FileType_File) { + return File_Copy(path, destination); + } + else if (fileType == FileType_Directory) { + + if (!CreateDirectory(destination, dirMode) && stop_on_error) { + return false; + } + + DirectoryListing directory = OpenDirectory(path); + + if (directory == INVALID_HANDLE) { + return false; + } + + char + source_buffer[PLATFORM_MAX_PATH], + destination_buffer[PLATFORM_MAX_PATH]; + FileType type; + + while (ReadDirEntry(directory, source_buffer, sizeof(source_buffer), type)) { + + if (StrEqual(source_buffer, "..") || StrEqual(source_buffer, ".")) { + continue; + } + + Format(destination_buffer, sizeof(destination_buffer), "%s/%s", destination, source_buffer); + Format(source_buffer, sizeof(source_buffer), "%s/%s", path, source_buffer); + + if (type == FileType_File) { + File_Copy(source_buffer, destination_buffer); + } + else if (type == FileType_Directory) { + + if (!File_CopyRecursive(source_buffer, destination_buffer, stop_on_error, dirMode) && stop_on_error) { + delete directory; + return false; + } + } + } + + delete directory; + } + else if (fileType == FileType_Unknown) { + return false; + } + + return true; +} diff --git a/scripting/include/smlib/game.inc b/scripting/include/smlib/game.inc new file mode 100644 index 0000000..ee3d145 --- /dev/null +++ b/scripting/include/smlib/game.inc @@ -0,0 +1,57 @@ +#if defined _smlib_game_included + #endinput +#endif +#define _smlib_game_included + +#include +#include +#include + +/* + * End's the game and displays the scoreboard with intermission time. + * + * @return True on success, false otherwise + */ +stock bool Game_End() +{ + int game_end = FindEntityByClassname(-1, "game_end"); + + if (game_end == -1) { + game_end = CreateEntityByName("game_end"); + + if (game_end == -1) { + ThrowError("Unable to find or create entity \"game_end\""); + } + } + + return AcceptEntityInput(game_end, "EndGame"); +} + +/* + * End's the current round, allows specifying the winning + * team and more. + * This function currently works in TF2 only (it uses the game_round_win entity). + * + * @param team The winning Team, pass 0 for Sudden Death mode (no winning team) + * @param forceMapReset If to force the map to reset during the force respawn after the round is over. + * @param switchTeams If to switch the teams when the game is going to be reset. + * @return True on success, false otherwise + */ +stock bool Game_EndRound(int team=0, bool forceMapReset=false, bool switchTeams=false) +{ + int game_round_win = FindEntityByClassname(-1, "game_round_win"); + + if (game_round_win == -1) { + game_round_win = CreateEntityByName("game_round_win"); + + if (game_round_win == -1) { + ThrowError("Unable to find or create entity \"game_round_win\""); + } + } + + DispatchKeyValue(game_round_win, "TeamNum" , (team ? "true" : "false")); + DispatchKeyValue(game_round_win, "force_map_reset" , (forceMapReset? "true" : "false")); + DispatchKeyValue(game_round_win, "switch_teams" , (switchTeams ? "true" : "false")); + + return AcceptEntityInput(game_round_win, "RoundWin"); +} diff --git a/scripting/include/smlib/general.inc b/scripting/include/smlib/general.inc new file mode 100644 index 0000000..a7e4d35 --- /dev/null +++ b/scripting/include/smlib/general.inc @@ -0,0 +1,251 @@ +#if defined _smlib_general_included + #endinput +#endif +#define _smlib_general_included + +#include +#include +#include + +#define TIME_TO_TICKS(%1) ( (int)( 0.5 + (float)(%1) / GetTickInterval() ) ) +#define TICKS_TO_TIME(%1) ( GetTickInterval() * %1 ) +#define ROUND_TO_TICKS(%1) ( TICK_INTERVAL * TIME_TO_TICKS( %1 ) ) + +/* + * Precaches the given model. + * It's best to call this OnMapStart(). + * + * @param material Path of the material to precache. + * @return Returns the material index, INVALID_STRING_INDEX on error. + */ +stock int PrecacheMaterial(const char[] material) +{ + static int materialNames = INVALID_STRING_TABLE; + + if (materialNames == INVALID_STRING_TABLE) { + if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + } + + int index = FindStringIndex2(materialNames, material); + if (index == INVALID_STRING_INDEX) { + int numStrings = GetStringTableNumStrings(materialNames); + if (numStrings >= GetStringTableMaxStrings(materialNames)) { + return INVALID_STRING_INDEX; + } + + AddToStringTable(materialNames, material); + index = numStrings; + } + + return index; +} + +/* + * Checks if the material is precached. + * + * @param material Path of the material. + * @return True if it is precached, false otherwise. + */ +stock bool IsMaterialPrecached(const char[] material) +{ + static int materialNames = INVALID_STRING_TABLE; + + if (materialNames == INVALID_STRING_TABLE) { + if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { + return false; + } + } + + return (FindStringIndex2(materialNames, material) != INVALID_STRING_INDEX); +} + +/* + * Precaches the given particle system. + * It's best to call this OnMapStart(). + * Code based on Rochellecrab's, thanks. + * + * @param particleSystem Name of the particle system to precache. + * @return Returns the particle system index, INVALID_STRING_INDEX on error. + */ +stock int PrecacheParticleSystem(const char[] particleSystem) +{ + static int particleEffectNames = INVALID_STRING_TABLE; + + if (particleEffectNames == INVALID_STRING_TABLE) { + if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + } + + int index = FindStringIndex2(particleEffectNames, particleSystem); + if (index == INVALID_STRING_INDEX) { + int numStrings = GetStringTableNumStrings(particleEffectNames); + if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) { + return INVALID_STRING_INDEX; + } + + AddToStringTable(particleEffectNames, particleSystem); + index = numStrings; + } + + return index; +} + +/* + * Checks if the particle system is precached. + * + * @param material Name of the particle system + * @return True if it is precached, false otherwise. + */ +stock bool IsParticleSystemPrecached(const char[] particleSystem) +{ + static int particleEffectNames = INVALID_STRING_TABLE; + + if (particleEffectNames == INVALID_STRING_TABLE) { + if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return false; + } + } + + return (FindStringIndex2(particleEffectNames, particleSystem) != INVALID_STRING_INDEX); +} + +/* + * Searches for the index of a given string in a string table. + * + * @param table String table name. + * @param str String to find. + * @return String index if found, INVALID_STRING_INDEX otherwise. + */ +stock int FindStringIndexByTableName(const char[] table, const char[] str) +{ + int tableIndex = INVALID_STRING_TABLE; + if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + + return FindStringIndex2(tableIndex, str); +} + +/* + * Rewrite of FindStringIndex, because in my tests + * FindStringIndex failed to work correctly. + * Searches for the index of a given string in a string table. + * + * @param tableidx A string table index. + * @param str String to find. + * @return String index if found, INVALID_STRING_INDEX otherwise. + */ +stock int FindStringIndex2(int tableidx, const char[] str) +{ + char buf[1024]; + + int numStrings = GetStringTableNumStrings(tableidx); + for (int i=0; i < numStrings; i++) { + ReadStringTable(tableidx, i, buf, sizeof(buf)); + + if (StrEqual(buf, str)) { + return i; + } + } + + return INVALID_STRING_INDEX; +} + +/* + * Converts a long IP to a dotted format String. + * + * @param ip IP Long + * @param buffer String Buffer (size = 16) + * @param size String Buffer size + */ +stock void LongToIP(int ip, char[] buffer, int size) +{ + Format( + buffer, size, + "%d.%d.%d.%d", + (ip >> 24) & 0xFF, + (ip >> 16) & 0xFF, + (ip >> 8 ) & 0xFF, + ip & 0xFF + ); +} + +/* + * Converts a dotted format String IP to a long. + * + * @param ip IP String + * @return Long IP + */ +stock int IPToLong(const char[] ip) +{ + char pieces[4][4]; + + if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) { + return 0; + } + + return ( + StringToInt(pieces[0]) << 24 | + StringToInt(pieces[1]) << 16 | + StringToInt(pieces[2]) << 8 | + StringToInt(pieces[3]) + ); +} + +static int localIPRanges[] = +{ + 10 << 24, // 10. + 127 << 24 | 1 , // 127.0.0.1 + 127 << 24 | 16 << 16, // 127.16. + 192 << 24 | 168 << 16, // 192.168. +}; + +/* + * Checks whether an IP is a private/internal IP + * + * @param ip IP Long + * @return True if the IP is local, false otherwise. + */ +stock bool IsIPLocal(int ip) +{ + int range, bits, move; + bool matches; + + for (int i=0; i < sizeof(localIPRanges); i++) { + + range = localIPRanges[i]; + matches = true; + + for (int j=0; j < 4; j++) { + move = j * 8; + bits = (range >> move) & 0xFF; + + if (bits && bits != ((ip >> move) & 0xFF)) { + matches = false; + } + } + + if (matches) { + return true; + } + } + + return false; +} + +/* + * Closes the given hindle and sets it to INVALID_HANDLE. + * Obsolete now. Just use |delete handle|. + * + * @param handle handle + */ +stock void ClearHandle(Handle &handle) +{ + if (handle != INVALID_HANDLE) { + CloseHandle(handle); + handle = INVALID_HANDLE; + } +} diff --git a/scripting/include/smlib/math.inc b/scripting/include/smlib/math.inc new file mode 100644 index 0000000..2e584fb --- /dev/null +++ b/scripting/include/smlib/math.inc @@ -0,0 +1,346 @@ +#if defined _smlib_math_included + #endinput +#endif +#define _smlib_math_included + +#include + +#define SIZE_OF_INT 2147483647 // without 0 +#define INT_MAX_DIGITS 10 + +#define GAMEUNITS_TO_METERS 0.01905 +#define METERS_TO_GAMEUNITS 52.49343832020997 +#define METERS_TO_FEET 3.2808399 +#define FEET_TO_METERS 0.3048 +#define KILOMETERS_TO_MILES 0.62137 + +enum VecAngle +{ + ANG_ALPHA, + ANG_BETA, + ANG_GAMMA +}; + +/** + * Makes a negative integer number to a positive integer number. + * This is faster than Sourcemod's native FloatAbs() for integers. + * Use FloatAbs() for Float numbers. + * + * @param number A number that can be positive or negative. + * @return Positive number. + */ +stock int Math_Abs(int value) +{ + return (value ^ (value >> 31)) - (value >> 31); +} + +/** + * Checks if 2 vectors are equal. + * You can specfiy a tolerance, which is the maximum distance at which vectors are considered equals + * + * @param vec1 First vector (3 dim array) + * @param vec2 Second vector (3 dim array) + * @param tolerance If you want to check that those vectors are somewhat even. 0.0 means they are 100% even if this function returns true. + * @return True if vectors are equal, false otherwise. + */ +stock bool Math_VectorsEqual(float vec1[3], float vec2[3], float tolerance=0.0) +{ + float distance = GetVectorDistance(vec1, vec2, true); + + return distance <= (tolerance * tolerance); +} + +/** + * Sets the given value to min + * if the value is smaller than the given. + * Don't use this with float values. + * + * @param value Value + * @param min Min Value used as lower border + * @return Correct value not lower than min + */ +stock any Math_Min(any value, any min) +{ + if (value < min) { + value = min; + } + + return value; +} + +/** + * Sets the given value to max + * if the value is greater than the given. + * Don't use this with float values. + * + * @param value Value + * @param max Max Value used as upper border + * @return Correct value not upper than max + */ +stock any Math_Max(any value, any max) +{ + if (value > max) { + value = max; + } + + return value; +} + +/** + * Makes sure a value is within a certain range and + * returns the value. + * If the value is outside the range it is set to either + * min or max, if it is inside the range it will just return + * the specified value. + * Don't use this with float values. + * + * @param value Value + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Correct value not lower than min and not greater than max. + */ +stock any Math_Clamp(any value, any min, any max) +{ + value = Math_Min(value, min); + value = Math_Max(value, max); + + return value; +} + +/* + * Checks if the value is within the given bounds (min & max). + * Don't use this with float values. + * + * @param value The value you want to check. + * @param min The lower border. + * @param max The upper border. + * @return True if the value is within bounds (bigger or equal min / smaller or equal max), false otherwise. + */ +stock bool Math_IsInBounds(any value, any min, any max) +{ + if (value < min || value > max) { + return false; + } + + return true; +} + +/** + * Let's the specified value "overflow" if it is outside the given limit. + * This is like with integers when it reaches a value above the max possible + * integer size. + * Don't use this with float values. + * + * @param value Value + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Overflowed number + */ +stock any Math_Overflow(any value, any min, any max) +{ + return (value % max) + min; +} + +/** + * Returns a random, uniform Integer number in the specified (inclusive) range. + * This is safe to use multiple times in a function. + * The seed is set automatically for each plugin. + * Rewritten by MatthiasVance, thanks. + * + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Random Integer number between min and max + */ +stock int Math_GetRandomInt(int min, int max) +{ + int random = GetURandomInt(); + + if (random == 0) { + random++; + } + + return RoundToCeil(float(random) / (float(SIZE_OF_INT) / float(max - min + 1))) + min - 1; +} + +/** + * Returns a random, uniform Float number in the specified (inclusive) range. + * This is safe to use multiple times in a function. + * The seed is set automatically for each plugin. + * + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Random Float number between min and max + */ +stock float Math_GetRandomFloat(float min, float max) +{ + return (GetURandomFloat() * (max - min)) + min; +} + +/** + * Gets the percentage of amount in all as Integer where + * amount and all are numbers and amount usually + * is a subset of all. + * + * @param value Integer value + * @param all Integer value + * @return An Integer value between 0 and 100 (inclusive). + */ +stock int Math_GetPercentage(int value, int all) { + return RoundToNearest((float(value) / float(all)) * 100.0); +} + +/** + * Gets the percentage of amount in all as Float where + * amount and all are numbers and amount usually + * is a subset of all. + * + * @param value Float value + * @param all Float value + * @return A Float value between 0.0 and 100.0 (inclusive). + */ +stock float Math_GetPercentageFloat(float value, float all) { + return (value / all) * 100.0; +} + +/* + * Moves the start vector on a direct line to the end vector by the given scale. + * Note: If scale is 0.0 the output will be the same as the start vector and if scale is 1.0 the output vector will be the same as the end vector. + * Exmaple usage: Move an entity to another entity but only 12 units: Vector_MoveVector(entity1Origin,entity2Origin,(12.0 / GetVectorDistance(entity1Origin,entity2Origin)),newEntity1Origin); now only teleport your entity to newEntity1Origin. + * + * @param start The start vector where the imagined line starts. + * @param end The end vector where the imagined line ends. + * @param scale The position on the line 0.0 is the start 1.0 is the end. + * @param output Output vector + */ +stock void Math_MoveVector(const float start[3], const float end[3], float scale, float output[3]) +{ + SubtractVectors(end,start,output); + ScaleVector(output,scale); + AddVectors(start,output,output); +} + +/** + * Puts x, y and z into a vector. + * + * @param x Float value. + * @param y Float value. + * @param z Float value. + * @param result Output vector. + */ +stock void Math_MakeVector(float x, float y, float z, float result[3]) +{ + result[0] = x; + result[1] = y; + result[2] = z; +} + +/** + * Rotates a vector around its zero-point. + * Note: As example you can rotate mins and maxs of an entity and then add its origin to mins and maxs to get its bounding box in relation to the world and its rotation. + * When used with players use the following angle input: + * angles[0] = 0.0; + * angles[1] = 0.0; + * angles[2] = playerEyeAngles[1]; + * + * @param vec Vector to rotate. + * @param angles How to rotate the vector. + * @param result Output vector. + */ +stock void Math_RotateVector(const float vec[3], const float angles[3], float result[3]) +{ + // First the angle/radiant calculations + float rad[3]; + // I don't really know why, but the alpha, beta, gamma order of the angles are messed up... + // 2 = xAxis + // 0 = yAxis + // 1 = zAxis + rad[0] = DegToRad(angles[2]); + rad[1] = DegToRad(angles[0]); + rad[2] = DegToRad(angles[1]); + + // Pre-calc function calls + float cosAlpha = Cosine(rad[0]); + float sinAlpha = Sine(rad[0]); + float cosBeta = Cosine(rad[1]); + float sinBeta = Sine(rad[1]); + float cosGamma = Cosine(rad[2]); + float sinGamma = Sine(rad[2]); + + // 3D rotation matrix for more information: http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions + float x = vec[0], y = vec[1], z = vec[2]; + float newX, newY, newZ; + newY = cosAlpha*y - sinAlpha*z; + newZ = cosAlpha*z + sinAlpha*y; + y = newY; + z = newZ; + + newX = cosBeta*x + sinBeta*z; + newZ = cosBeta*z - sinBeta*x; + x = newX; + z = newZ; + + newX = cosGamma*x - sinGamma*y; + newY = cosGamma*y + sinGamma*x; + x = newX; + y = newY; + + // Store everything... + result[0] = x; + result[1] = y; + result[2] = z; +} + +/** + * Converts Source Game Units to metric Meters + * + * @param units Float value + * @return Meters as Float value. + */ +stock float Math_UnitsToMeters(float units) +{ + return (units * GAMEUNITS_TO_METERS); +} + +/** + * Converts Source Game Units to Meters + * + * @param units Float value + * @return Feet as Float value. + */ +stock float Math_UnitsToFeet(float units) +{ + return (Math_UnitsToMeters(units) * METERS_TO_FEET); +} + +/** + * Converts Source Game Units to Centimeters + * + * @param units Float value + * @return Centimeters as Float value. + */ +stock float Math_UnitsToCentimeters(float units) +{ + return (Math_UnitsToMeters(units) * 100.0); +} + +/** + * Converts Source Game Units to Kilometers + * + * @param units Float value + * @return Kilometers as Float value. + */ +stock float Math_UnitsToKilometers(float units) +{ + return (Math_UnitsToMeters(units) / 1000.0); +} + +/** + * Converts Source Game Units to Miles + * + * @param units Float value + * @return Miles as Float value. + */ +stock float Math_UnitsToMiles(float units) +{ + return (Math_UnitsToKilometers(units) * KILOMETERS_TO_MILES); +} diff --git a/scripting/include/smlib/menus.inc b/scripting/include/smlib/menus.inc new file mode 100644 index 0000000..87f253e --- /dev/null +++ b/scripting/include/smlib/menus.inc @@ -0,0 +1,37 @@ +#if defined _smlib_menus_included + #endinput +#endif +#define _smlib_menus_included + +#include +#include + +/** + * Adds an option to a menu with a String display but an integer + * identifying the option. + * + * @param menu Handle to the menu + * @param value Integer value for the option + * @param display Display text for the menu + */ +stock void Menu_AddIntItem(Menu menu, any value, char[] display) +{ + char buffer[INT_MAX_DIGITS + 1]; + IntToString(value, buffer, sizeof(buffer)); + menu.AddItem(buffer, display); +} + +/** + * Retrieves an integer-value choice from a menu, where the + * menu's information strings were created as integers. + * + * @param menu Handle to the menu + * @param param2 The item position selected from the menu. + * @return Integer choice from the menu, or 0 if the integer could not be parsed. + */ +stock any Menu_GetIntItem(Menu menu, any param2) +{ + char buffer[INT_MAX_DIGITS + 1]; + menu.GetItem(param2, buffer, sizeof(buffer)); + return StringToInt(buffer); +} diff --git a/scripting/include/smlib/server.inc b/scripting/include/smlib/server.inc new file mode 100644 index 0000000..ae54cc4 --- /dev/null +++ b/scripting/include/smlib/server.inc @@ -0,0 +1,135 @@ +#if defined _smlib_server_included + #endinput +#endif +#define _smlib_server_included + +#include +#include + +/* + * Gets the server's public/external (default) or + * private/local (usually server's behind a NAT) IP. + * If your server is behind a NAT Router, you need the SteamTools + * extension available at http://forums.alliedmods.net/showthread.php?t=129763 + * to get the public IP. has to be included BEFORE . + * If the server is not behind NAT, the public IP is the same as the private IP. + * + * @param public Set to true to retrieve the server's public/external IP, false otherwise. + * @return Long IP or 0 if the IP couldn't be retrieved. + */ +stock int Server_GetIP(bool public_=true) +{ + int ip = 0; + + static ConVar cvHostip = null; + + if (cvHostip == INVALID_HANDLE) { + cvHostip = FindConVar("hostip"); + MarkNativeAsOptional("Steam_GetPublicIP"); + } + + if (cvHostip != INVALID_HANDLE) { + ip = cvHostip.IntValue; + } + + if (ip != 0 && IsIPLocal(ip) == public_) { + ip = 0; + } + +#if defined _steamtools_included + if (ip == 0) { + if (CanTestFeatures() && GetFeatureStatus(FeatureType_Native, "Steam_GetPublicIP") == FeatureStatus_Available) { + int octets[4]; + Steam_GetPublicIP(octets); + + ip = + octets[0] << 24 | + octets[1] << 16 | + octets[2] << 8 | + octets[3]; + + if (IsIPLocal(ip) == public_) { + ip = 0; + } + } + } +#endif + + return ip; +} + +/* + * Gets the server's public/external (default) or + * private/local (usually server's behind a NAT) as IP String in dotted format. + * If your server is behind a NAT Router, you need the SteamTools + * extension available at http://forums.alliedmods.net/showthread.php?t=129763 + * to get the public IP. has to be included BEFORE . + * If the public IP couldn't be found, an empty String is returned. + * If the server is not behind NAT, the public IP is the same as the private IP. + * + * @param buffer String buffer (size=16) + * @param size String buffer size. + * @param public Set to true to retrieve the server's public/external IP, false otherwise. + * @return True on success, false otherwise. + */ +stock bool Server_GetIPString(char[] buffer, int size, bool public_=true) +{ + int ip; + + if ((ip = Server_GetIP(public_)) == 0) { + buffer[0] = '\0'; + return false; + } + + LongToIP(ip, buffer, size); + + return true; +} + +/* + * Gets the server's local port. + * + * @noparam + * @return The server's port, 0 if there is no port. + */ +stock int Server_GetPort() +{ + static ConVar cvHostport = null; + + if (cvHostport == INVALID_HANDLE) { + cvHostport = FindConVar("hostport"); + } + + if (cvHostport == INVALID_HANDLE) { + return 0; + } + + int port = cvHostport.IntValue; + + return port; +} + +/* + * Gets the server's hostname + * + * @param hostname String buffer + * @param size String buffer size + * @return True on success, false otherwise. + */ +stock bool Server_GetHostName(char[] buffer, int size) +{ + static ConVar cvHostname = null; + + if (cvHostname == INVALID_HANDLE) { + cvHostname = FindConVar("hostname"); + } + + if (cvHostname == INVALID_HANDLE) { + buffer[0] = '\0'; + return false; + } + + cvHostname.GetString(buffer, size); + + return true; +} diff --git a/scripting/include/smlib/sql.inc b/scripting/include/smlib/sql.inc new file mode 100644 index 0000000..e291cfa --- /dev/null +++ b/scripting/include/smlib/sql.inc @@ -0,0 +1,107 @@ +#if defined _smlib_sql_included + #endinput +#endif +#define _smlib_sql_included + +#include +#include + +/** + * Executes a threaded SQL Query (See: SQL_TQuery) + * This function supports the printf Syntax. + * + * + * @param database A database Handle. + * @param callback Callback; database is in "owner" and the query Handle is passed in "hndl". + * @param data Extra data value to pass to the callback. + * @param format Query string, printf syntax supported + * @param priority Priority queue to use + * @param ... Variable number of format parameters. + */ +stock void SQL_TQueryF(Database database, SQLTCallback callback, any data, DBPriority priority=DBPrio_Normal, const char[] format, any ...) { + + if (!database) { + ThrowError("[SMLIB] Error: Invalid database handle."); + return; + } + + char query[16384]; + VFormat(query, sizeof(query), format, 6); + + SQL_TQuery(database, callback, query, data, priority); +} + +/** + * Fetches an integer from a field in the current row of a result set (See: SQL_FetchInt) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return An integer value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock int SQL_FetchIntByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchInt(query, fieldNum, result); +} + +/** + * Fetches a bool from a field in the current row of a result set (See: SQL_FetchInt) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return A bool value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock bool SQL_FetchBoolByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + return SQL_FetchIntByName(query, fieldName, result) != 0; +} + +/** + * Fetches a float from a field in the current row of a result set. (See: SQL_FetchFloat) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return A float value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock float SQL_FetchFloatByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchFloat(query, fieldNum, result); +} + +/** + * Fetches a string from a field in the current row of a result set. (See: SQL_FetchString) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param buffer String buffer. + * @param maxlength Maximum size of the string buffer. + * @param result Optional variable to store the status of the return value. + * @return Number of bytes written. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock int SQL_FetchStringByName(DBResultSet query, const char[] fieldName, char[] buffer, int maxlength, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchString(query, fieldNum, buffer, maxlength, result); +} diff --git a/scripting/include/smlib/strings.inc b/scripting/include/smlib/strings.inc new file mode 100644 index 0000000..b7cf9b4 --- /dev/null +++ b/scripting/include/smlib/strings.inc @@ -0,0 +1,228 @@ +#if defined _smlib_strings_included + #endinput +#endif +#define _smlib_strings_included + +#include +#include + +/** + * Checks if the string is numeric. + * This correctly handles + - . in the String. + * + * @param str String to check. + * @return True if the String is numeric, false otherwise.. + */ +stock bool String_IsNumeric(const char[] str) +{ + int x=0; + int dotsFound=0; + int numbersFound=0; + + if (str[x] == '+' || str[x] == '-') { + x++; + } + + while (str[x] != '\0') { + + if (IsCharNumeric(str[x])) { + numbersFound++; + } + else if (str[x] == '.') { + dotsFound++; + + if (dotsFound > 1) { + return false; + } + } + else { + return false; + } + + x++; + } + + if (!numbersFound) { + return false; + } + + return true; +} + +/** + * Trims a string by removing the specified chars from beginning and ending. + * Removes all ' ', '\t', '\r', '\n' characters by default. + * The Output String can be the same as the Input String. + * + * @param str Input String. + * @param output Output String (Can be the as the input). + * @param size Size of the output String. + * @param chars Characters to remove. + */ +stock void String_Trim(const char[] str, char[] output, int size, const char[] chrs=" \t\r\n") +{ + int x=0; + while (str[x] != '\0' && FindCharInString(chrs, str[x]) != -1) { + x++; + } + + x = strcopy(output, size, str[x]); + x--; + + while (x >= 0 && FindCharInString(chrs, output[x]) != -1) { + x--; + } + + output[++x] = '\0'; +} + +/** + * Removes a list of strings from a string. + * + * @param buffer Input/Output buffer. + * @param removeList A list of strings which should be removed from buffer. + * @param size Number of Strings in the List. + * @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. + */ +stock void String_RemoveList(char[] buffer, const char[][] removeList, int size, bool caseSensitive=false) +{ + for (int i=0; i < size; i++) { + ReplaceString(buffer, SIZE_OF_INT, removeList[i], "", caseSensitive); + } +} + +/** + * Converts the whole String to lower case. + * Only works with alphabetical characters (not ÖÄÜ) because Sourcemod suxx ! + * The Output String can be the same as the Input String. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void String_ToLower(const char[] input, char[] output, int size) +{ + size--; + + int x=0; + while (input[x] != '\0' && x < size) { + + output[x] = CharToLower(input[x]); + + x++; + } + + output[x] = '\0'; +} + +/** + * Converts the whole String to upper case. + * Only works with alphabetical characters (not öäü) because Sourcemod suxx ! + * The Output String can be the same as the Input String. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void String_ToUpper(const char[] input, char[] output, int size) +{ + size--; + + int x=0; + while (input[x] != '\0' && x < size) { + + output[x] = CharToUpper(input[x]); + + x++; + } + + output[x] = '\0'; +} + +/** + * Generates a random string. + * + * + * @param buffer String Buffer. + * @param size String Buffer size (must be length+1) + * @param length Number of characters being generated. + * @param chrs String for specifying the characters used for random character generation. + * By default it will use all letters of the alphabet (upper and lower) and all numbers. + * If you pass an empty String, it will use all readable ASCII characters (33 - 126) + */ +stock void String_GetRandom(char[] buffer, int size, int length=32, const char[] chrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234556789") +{ + int random, len; + size--; + + if (chrs[0] != '\0') { + len = strlen(chrs) - 1; + } + + int n = 0; + while (n < length && n < size) { + + if (chrs[0] == '\0') { + random = Math_GetRandomInt(33, 126); + buffer[n] = random; + } + else { + random = Math_GetRandomInt(0, len); + buffer[n] = chrs[random]; + } + + n++; + } + + buffer[length] = '\0'; +} + +/** + * Checks if string str starts with subString. + * + * + * @param str String to check + * @param subString Sub-String to check in str + * @return True if str starts with subString, false otherwise. + */ +stock bool String_StartsWith(const char[] str, const char[] subString) +{ + int n = 0; + while (subString[n] != '\0') { + + if (str[n] == '\0' || str[n] != subString[n]) { + return false; + } + + n++; + } + + return true; +} + +/** + * Checks if string str ends with subString. + * + * + * @param str String to check + * @param subString Sub-String to check in str + * @return True if str ends with subString, false otherwise. + */ +stock bool String_EndsWith(const char[] str, const char[] subString) +{ + int n_str = strlen(str) - 1; + int n_subString = strlen(subString) - 1; + + if(n_str < n_subString) { + return false; + } + + while (n_str != 0 && n_subString != 0) { + + if (str[n_str--] != subString[n_subString--]) { + return false; + } + } + + return true; +} diff --git a/scripting/include/smlib/teams.inc b/scripting/include/smlib/teams.inc new file mode 100644 index 0000000..621c8b1 --- /dev/null +++ b/scripting/include/smlib/teams.inc @@ -0,0 +1,317 @@ +#if defined _smlib_teams_included + #endinput +#endif +#define _smlib_teams_included + +#include +#include +#include + +#define MAX_TEAMS 32 // Max number of teams in a game +#define MAX_TEAM_NAME_LENGTH 32 // Max length of a team's name + +// Team Defines +#define TEAM_INVALID -1 +#define TEAM_UNASSIGNED 0 +#define TEAM_SPECTATOR 1 +#define TEAM_ONE 2 +#define TEAM_TWO 3 +#define TEAM_THREE 4 +#define TEAM_FOUR 5 + +/* + * If one team is empty its assumed single team mode is enabled and the game won't start. + * + * @noparam + * @return True if one team is empty, false otherwise. + */ +stock bool Team_HaveAllPlayers(bool countFakeClients=true) { + + int teamCount = GetTeamCount(); + for (int i=2; i < teamCount; i++) { + + if (Team_GetClientCount(i, ((countFakeClients) ? CLIENTFILTER_ALL : CLIENTFILTER_NOBOTS)) == 0) { + return false; + } + } + + return true; +} + +/* + * Returns the client count of the players in a team. + * + * @param team Team Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client count in the server. + */ +stock int Team_GetClientCount(int team, int flags=0) +{ + flags |= CLIENTFILTER_INGAME; + + int numClients = 0; + for (int client=1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + if (GetClientTeam(client) == team) { + numClients++; + } + } + + return numClients; +} + +/* + * Returns the client counts of the first two teams (eg.: Terrorists - Counter). + * Use this function for optimization if you have to get the counts of both teams, + * otherwise use Team_GetClientCount(). + * + * @param team1 Pass an integer variable by reference + * @param team2 Pass an integer variable by reference + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + */ +stock void Team_GetClientCounts(int &team1=0, int &team2=0, int flags=0) +{ + flags |= CLIENTFILTER_INGAME; + + for (int client=1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + if (GetClientTeam(client) == TEAM_ONE) { + team1++; + } + else if (GetClientTeam(client) == TEAM_TWO) { + team2++; + } + } +} + +/* + * Gets the name of a team. + * Don't call this before OnMapStart() + * + * @param index Team Index. + * @param str String buffer + * @param size String Buffer Size + * @return True on success, false otherwise + */ +stock bool Team_GetName(int index, char[] str, int size) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + str[0] = '\0'; + return false; + } + + GetEntPropString(edict, Prop_Send, "m_szTeamname", str, size); + + return true; +} + +/* + * Changes a team's name. + * Use this carefully ! + * Only set the teamname OnMapStart() or OnEntityCreated() + * when no players are ingame, otherwise it can crash the server. + * + * @param index Team Index. + * @param name New Name String + * @return True on success, false otherwise + */ +stock bool Team_SetName(int index, const char[] name) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return false; + } + + SetEntPropString(edict, Prop_Send, "m_szTeamname", name); + ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_szTeamname", true)); + + return true; +} + +/* + * Changes a team's score. + * Don't use this before OnMapStart(). + * + * @param index Team Index. + * @return Team Score or -1 if the team is not valid. + */ +stock int Team_GetScore(int index) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return -1; + } + + return GetEntProp(edict, Prop_Send, "m_iScore"); +} + +/* + * Changes a team's score. + * Don't use this before OnMapStart(). + * + * @param index Team Index. + * @param score Score value. + * @return True on success, false otherwise + */ +stock bool Team_SetScore(int index, int score) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return false; + } + + SetEntProp(edict, Prop_Send, "m_iScore", score); + + ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_iScore", true)); + + return true; +} + +/* + * Gets a team's edict (*team_manager) Team Index. + * Don't call this before OnMapStart() + * + * @param edict Edict + * @return Team Index + */ +stock int Team_EdictGetNum(int edict) +{ + return GetEntProp(edict, Prop_Send, "m_iTeamNum"); +} + +/* + * Check's whether the index is a valid team index or not. + * Don't call this before OnMapStart() + * + * @param index Index. + * @return True if the Index is a valid team, false otherwise. + */ +stock bool Team_IsValid(int index) +{ + return (Team_GetEdict(index) != -1); +} + +/* + * Gets a team's edict (team_manager) Team Index. + * Don't call this before OnMapStart() + * + * @param index Edict + * @return Team Index + */ +stock int Team_EdictIsValid(int edict) +{ + return GetEntProp(edict, Prop_Send, "m_iTeamNum"); +} + +/* + * Gets a team's edict (team_manager). + * This function caches found team edicts. + * Don't call this before OnMapStart() + * + * @param index Team Index. + * @return Team edict or -1 if not found + */ +stock int Team_GetEdict(int index) +{ + static int teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... }; + + if (index < 0 || index > MAX_TEAMS) { + return -1; + } + + int edict = teams[index]; + if (Entity_IsValid(edict)) { + return edict; + } + + bool foundTeamManager = false; + + int maxEntities = GetMaxEntities(); + for (int entity=MaxClients+1; entity < maxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_ClassNameMatches(entity, "team_manager", true)) { + foundTeamManager = true; + } + // Do not continue when no team managers are found anymore (for optimization) + else if (foundTeamManager) { + return -1; + } + else { + continue; + } + + int num = Team_EdictGetNum(entity); + + if (num >= 0 && num <= MAX_TEAMS) { + teams[num] = EntIndexToEntRef(entity); + } + + if (num == index) { + return entity; + } + } + + return -1; +} + +/* + * Trys to find a client in the specified team. + * This function is NOT random, it returns the first + * or the cached player (Use Client_GetRandom() instead). + * + * @param index Team Index. + * @return Client Index or -1 if no client was found in the specified team. + */ +stock int Team_GetAnyClient(int index) +{ + static int client_cache[MAX_TEAMS] = {-1, ...}; + int client; + + if (index > 0) { + client = client_cache[index]; + + if (client > 0 && client <= MaxClients) { + + if (IsClientInGame(client) && GetClientTeam(client) == index) { + return client; + } + } + else { + client = -1; + } + } + + for (client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (GetClientTeam(client) != index) { + continue; + } + + client_cache[index] = client; + + return client; + } + + return -1; +} diff --git a/scripting/include/smlib/vehicles.inc b/scripting/include/smlib/vehicles.inc new file mode 100644 index 0000000..61006fe --- /dev/null +++ b/scripting/include/smlib/vehicles.inc @@ -0,0 +1,137 @@ +#if defined _smlib_vehicles_included + #endinput +#endif +#define _smlib_vehicles_included + +#include +#include +#include +#include + +/** + * Returns the vehicle's driver. + * If there is no driver in the vehicle, -1 is returned. + * + * @param vehicle Entity index. + * @return Client index, or -1 if there is no driver. + */ +stock int Vehicle_GetDriver(int vehicle) +{ + int m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer"); + + return m_hVehicle; +} + +/** + * Returns whether there is a driver in the vehicle or not. + * + * @param vehicle Entity index. + * @return True if the vehicle has a driver, false otherwise + */ +stock bool Vehicle_HasDriver(int vehicle) +{ + return Vehicle_GetDriver(vehicle) != -1; +} + +/** + * Kicks the driver ouf of the vehicle + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_ExitDriver(int vehicle) +{ + if (!Vehicle_HasDriver(vehicle)) { + return false; + } + + return AcceptEntityInput(vehicle, "ExitVehicle"); +} + +/** + * Start's the vehicle's engine + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_TurnOn(int vehicle) +{ + return AcceptEntityInput(vehicle, "TurnOn"); +} + +/** + * Shuts down the vehicle's engine + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_TurnOff(int vehicle) +{ + return AcceptEntityInput(vehicle, "TurnOff"); +} + +/** + * Locks the vehicle. + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_Lock(int vehicle) +{ + return AcceptEntityInput(vehicle, "Lock"); +} + +/** + * Unlocks the vehicle. + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_Unlock(int vehicle) +{ + return AcceptEntityInput(vehicle, "Unlock"); +} + +/** + * Returns wether the entity is a valid vehicle or not. + * + * @param vehicle Entity index. + * @return True if it is a valid vehicle, false otherwise. + */ +stock bool Vehicle_IsValid(int vehicle) +{ + if (!Entity_IsValid(vehicle)) { + return false; + } + + return Entity_ClassNameMatches(vehicle, "prop_vehicle", true); +} + +/** + * Reads the vehicle script from a vehicle. + * This script contains all the vehicle settings like its speed + * and that stuff. + * + * @param vehicle Entity index. + * @param buffer String Buffer. + * @param size String Buffer size. + * @noreturn + */ +stock void Vehicle_GetScript(int vehicle, char[] buffer, int size) +{ + GetEntPropString(vehicle, Prop_Data, "m_vehicleScript", buffer, size); +} + +/** + * Sets the script of a vehicle. + * This script contains all the vehicle settings like its speed + * and that stuff. + * + * @param vehicle Entity index. + * @param buffer Vehicle Script path. + * @noreturn + */ +stock void Vehicle_SetScript(int vehicle, char[] script) +{ + DispatchKeyValue(vehicle, "vehiclescript", script); +} diff --git a/scripting/include/smlib/weapons.inc b/scripting/include/smlib/weapons.inc new file mode 100644 index 0000000..417053e --- /dev/null +++ b/scripting/include/smlib/weapons.inc @@ -0,0 +1,393 @@ +#if defined _smlib_weapons_included + #endinput +#endif +#define _smlib_weapons_included + +#include +#include +#include + +#define MAX_WEAPON_OFFSET 64 +#define MAX_WEAPON_SLOTS 6 // hud item selection slots +#define MAX_WEAPON_POSITIONS 20 // max number of items within a slot +#define MAX_WEAPONS 48 // Max number of weapons availabl +#define WEAPON_NOCLIP -1 // clip sizes set to this tell the weapon it doesn't use a clip +#define MAX_AMMO_TYPES 32 +#define MAX_AMMO_SLOTS 32 // not really slots + +#define MAX_WEAPON_STRING 80 +#define MAX_WEAPON_PREFIX 16 +#define MAX_WEAPON_AMMO_NAME 32 + +/* + * Gets the owner (usually a client) of the weapon + * + * @param weapon Weapon Entity. + * @return Owner of the weapon or INVALID_ENT_REFERENCE if the weapon has no owner. + */ +stock int Weapon_GetOwner(int weapon) +{ + return GetEntPropEnt(weapon, Prop_Data, "m_hOwner"); +} + +/* + * Sets the owner (usually a client) of the weapon + * + * @param weapon Weapon Entity. + * @param entity Entity Index. + * @noreturn + */ +stock void Weapon_SetOwner(int weapon, int entity) +{ + SetEntPropEnt(weapon, Prop_Data, "m_hOwner", entity); +} + +/* + * Checks whether the entity is a valid weapon or not. + * + * @param weapon Weapon Entity. + * @return True if the entity is a valid weapon, false otherwise. + */ +stock bool Weapon_IsValid(int weapon) +{ + if (!IsValidEdict(weapon)) { + return false; + } + + return Entity_ClassNameMatches(weapon, "weapon_", true); +} + +/* + * Create's a weapon and spawns it in the world at the specified location. + * + * @param className Classname String of the weapon to spawn + * @param absOrigin Absolute Origin Vector where to spawn the weapon. + * @param absAngles Absolute Angles Vector. + * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. + */ +stock int Weapon_Create(const char[] className, float absOrigin[3], float absAngles[3]) +{ + int weapon = Entity_Create(className); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + Entity_SetAbsOrigin(weapon, absOrigin); + Entity_SetAbsAngles(weapon, absAngles); + + DispatchSpawn(weapon); + + return weapon; +} + +/* + * Create's a weapon and spawns it in the world at the specified location. + * + * @param className Classname String of the weapon to spawn + * @param absOrigin Absolute Origin Vector where to spawn the weapon. + * @param absAngles Absolute Angles Vector. + * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. + */ +stock int Weapon_CreateForOwner(int client, const char[] className) +{ + float absOrigin[3], absAngles[3]; + Entity_GetAbsOrigin(client, absOrigin); + Entity_GetAbsAngles(client, absAngles); + + int weapon = Weapon_Create(className, absOrigin, absAngles); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + Entity_SetOwner(weapon, client); + + return weapon; +} + +/* + * Gets the weapon's subtype. + * The subtype is only used when a player has multiple weapons of the same type. + * + * @param weapon Weapon Entity. + * @return Subtype of the weapon. + */ +stock int Weapon_GetSubType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSubType"); +} + +/* + * Is the weapon currently reloading ? + * + * @param weapon Weapon Entity. + * @return True if weapon is currently reloading, false if not. + */ +stock bool Weapon_IsReloading(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bInReload") != 0; +} + +/* + * Weapon m_iState + */ +#define WEAPON_IS_ONTARGET 0x40 +#define WEAPON_NOT_CARRIED 0 // Weapon is on the ground +#define WEAPON_IS_CARRIED_BY_PLAYER 1 // This client is carrying this weapon. +#define WEAPON_IS_ACTIVE 2 // This client is carrying this weapon and it's the currently held weapon + +/* + * Get's the state of the weapon. + * This returns whether the weapon is currently carried by a client, + * if it is active and if it is on a target. + * + * @param weapon Weapon Entity. + * @return Weapon State. + */ +stock int Weapon_GetState(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iState"); +} + +/* + * Returns whether the weapon can fire primary ammo under water. + * + * @param weapon Weapon Entity. + * @return True or False. + */ +stock bool Weapon_FiresUnderWater(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater") != 0; +} + +/* + * Sets if the weapon can fire primary ammo under water. + * + * @param weapon Weapon Entity. + * @param can True or False. + */ +stock void Weapon_SetFiresUnderWater(int weapon, bool can=true) +{ + SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", can); +} + +/* + * Returns whether the weapon can fire secondary ammo under water. + * + * @param weapon Weapon Entity. + * @return True or False. + */ +stock bool Weapon_FiresUnderWaterAlt(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater") != 0; +} + +/* + * Sets if the weapon can fire secondary ammo under water. + * + * @param weapon Weapon Entity. + * @param can True or False. + */ +stock void Weapon_SetFiresUnderWaterAlt(int weapon, bool can=true) +{ + SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", can); +} + +/* + * Gets the primary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @return Primary ammo type value. + */ +stock int Weapon_GetPrimaryAmmoType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); +} + +/* + * Sets the primary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @param type Primary ammo type value. + */ +stock void Weapon_SetPrimaryAmmoType(int weapon, int type) +{ + SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType", type); +} + +/* + * Gets the secondary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @return Secondary ammo type value. + */ +stock int Weapon_GetSecondaryAmmoType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType"); +} + +/* + * Sets the secondary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @param type Secondary ammo type value. + */ +stock void Weapon_SetSecondaryAmmoType(int weapon, int type) +{ + SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType", type); +} + +/* + * Gets the primary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @return Primary Clip count. + */ +stock int Weapon_GetPrimaryClip(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iClip1"); +} + +/* + * Sets the primary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param value Clip Count value. + */ +stock void Weapon_SetPrimaryClip(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iClip1", value); +} + +/* + * Gets the secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @return Secondy Clip count. + */ +stock int Weapon_GetSecondaryClip(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iClip2"); +} + +/* + * Sets the secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param value Clip Count value. + */ +stock void Weapon_SetSecondaryClip(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iClip2", value); +} + +/* + * Sets the primary & secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param primary Primary Clip Count value. + * @param secondary Primary Clip Count value. + */ +stock void Weapon_SetClips(int weapon, int primary, int secondary) +{ + Weapon_SetPrimaryClip(weapon, primary); + Weapon_SetSecondaryClip(weapon, secondary); +} + +/* + * Gets the primary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @return Primary Ammo Count. + */ +stock int Weapon_GetPrimaryAmmoCount(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount"); +} + +/* + * Sets the primary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @param value Primary Ammo Count. + */ +stock void Weapon_SetPrimaryAmmoCount(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount", value); +} + +/* + * Gets the secondary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @return Secondary Ammo Count. + */ +stock int Weapon_GetSecondaryAmmoCount(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount"); +} + +/* + * Sets the secodary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @param value Secondary Ammo Count. + */ +stock void Weapon_SetSecondaryAmmoCount(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount", value); +} + +/* + * Sets both, the primary & the secondary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @value primary Primary Ammo Count. + * @value secondary Secondary Ammo Count. + */ +stock void Weapon_SetAmmoCounts(int weapon, int primary, int secondary) +{ + Weapon_SetPrimaryAmmoCount(weapon, primary); + Weapon_SetSecondaryAmmoCount(weapon, secondary); +} + +/* + * Gets the Model Index of the weapon's view model. + * + * @param weapon Weapon Entity. + * @return View Model Index. + */ +stock int Weapon_GetViewModelIndex(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_nViewModelIndex"); +} + +/* + * Sets the Model Index of the weapon's view model. + * You can get the Model Index by precaching a model with PrecacheModel(). + * + * @param weapon Weapon Entity. + * @param index Model Index. + * @noreturn + */ +stock void Weapon_SetViewModelIndex(int weapon, int index) +{ + SetEntProp(weapon, Prop_Data, "m_nViewModelIndex", index); + ChangeEdictState(weapon, FindDataMapInfo(weapon, "m_nViewModelIndex")); +} diff --git a/scripting/include/smlib/world.inc b/scripting/include/smlib/world.inc new file mode 100644 index 0000000..d438b41 --- /dev/null +++ b/scripting/include/smlib/world.inc @@ -0,0 +1,16 @@ +#if defined _smlib_world_included + #endinput +#endif +#define _smlib_world_included + +#include + +/* + * Gets the world's max size + * + * @param vec Vector buffer + */ +stock void World_GetMaxs(float vec[3]) { + + GetEntPropVector(0, Prop_Data, "m_WorldMaxs", vec); +} diff --git a/scripting/include/socket.inc b/scripting/include/socket.inc new file mode 100644 index 0000000..7bd636a --- /dev/null +++ b/scripting/include/socket.inc @@ -0,0 +1,482 @@ +// socket extension include file + +#if defined _socket_included + #endinput +#endif +#define _socket_included +#include + +enum SocketType { + SOCKET_TCP = 1, + SOCKET_UDP, + SOCKET_RAW +} + +#define EMPTY_HOST 1 +#define NO_HOST 2 +#define CONNECT_ERROR 3 +#define SEND_ERROR 4 +#define BIND_ERROR 5 +#define RECV_ERROR 6 +#define LISTEN_ERROR 7 + + +/*************************************************************************************************/ +/******************************************** options ********************************************/ +/*************************************************************************************************/ + + +/** + * Options available for SocketSetOption() + * + * @note modifying these options is not required for normal operation, you can skip the whole + * section in most cases. + */ +enum SocketOption { +/** + * If this option is set the socket extension will try to concatenate SocketReceive callbacks. + * + * This will possibly lower the amount of callbacks passed to SourceMod plugins and improve the + * performance. The socket extension will preserve the packet order. + * + * @note this doesn't prevent multiple callbacks, it only reduces them for high load. + * @note this will not truncate packets below 4096 bytes, setting it lower will be ignored + * @note set this option if you expect lots of data in a short timeframe + * @note don't forget to set your buffer sizes at least to the value passed to this function, but + * always at least to 4096 + * + * @param cell_t 0(=default) to disable or max. chunk size including \0 terminator in bytes + * @return bool true on success + */ + ConcatenateCallbacks = 1, +/** + * If this option is set the socket extension will enforce a mutex lock in the GameFrame() hook. + * + * This will ensure that callbacks will be processed every gameframe as fast as possible with the + * drawback of potentially creating lag. It's not recommended to set this option for most cases. + * If this option is not set the gameframe will be skipped if quietly obtaining a lock fails. + * + * @note combine this with CallbacksPerFrame for best performance + * @note this option will affect all sockets from all plugins, use it with caution! + * + * @param bool whether to force locking or not + * @return bool true on success + */ + ForceFrameLock, +/** + * This will specify the maximum amount of callbacks processed in every gameframe. + * + * The default value for this option is 1, setting it higher will possibly increase networking + * performance but may cause lag if it's set too high. + * The amount of callbacks actually being processed is limited by not being able to quietly obtain + * a lock (see ForceFrameLock) and the amount of callbacks in the queue. + * + * @note this option will affect all sockets from all plugins, use it with caution! + * + * @param cell_t maximum amount of callbacks per gameframe + * @return bool true on success + */ + CallbacksPerFrame, +/** + * If this option is set the socket will be allowed to send broadcast messages in case the protocol + * supports it. This is a wrapper for setting SO_BROADCAST. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketBroadcast, +/** + * If this option is set SocketBind() will allow reusing local adresses in case the protocol + * supports it. This is a wrapper for setting SO_REUSEADDR. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketReuseAddr, +/** + * If this option is set the socket will try to keep the connection alive by periodically sending + * messages if the protocol supports it. This is a wrapper for setting SO_KEEPALIVE. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketKeepAlive, +/** + * This option specifies how long a socket will wait if it's being closed and its send buffer is + * still filled. This is a wrapper for setting SO_LINGER. + * + * @param cell_t 0 (=default) to disable or time in s + * @return bool true on success + */ + SocketLinger, +/** + * If this option is set out-of-band data will be inlined into the normal receive stream. This is a + * wrapper for setting SO_OOBINLINE. + * + * @param bool whether to inline out-of-band data or not + * @return bool true on success + */ + SocketOOBInline, +/** + * This option specifies how large the send buffer will be. This is a wrapper for setting + * SO_SNDBUF. + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketSendBuffer, +/** + * This option specifies how large the receive buffer will be. This is a wrapper for setting + * SO_RCVBUF. + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketReceiveBuffer, +/** + * If this option is set outgoing messages will ignore the default routing facilities if the + * protocol implementation supports it. The remote site should be directly connected to the sender. + * This is a wrapper for setting SO_DONTROUTE. + * + * @param bool whether to skip default routing or not + * @return bool true on success + */ + SocketDontRoute, +/** + * This option specifies the minimum amount of data to receive before processing it. This is a + * wrapper for setting SO_RCVLOWAT. + * + * @note this can probably block the extension, use it with caution! + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketReceiveLowWatermark, +/** + * This option specifies how long a socket will try to receive data before it times out and + * processes the data. This is a wrapper for setting SO_RCVTIMEO. + * + * @param cell_t 0 (=default) to disable or time in ms + * @return bool true on success + */ + SocketReceiveTimeout, +/** + * This option specifies the minimum amount of data required in the send buffer before starting to + * send it. This is a wrapper for setting SO_SNDLOWAT. + * + * @note this can probably block the extension, use it with caution! + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketSendLowWatermark, +/** + * This option specifies how long a socket will try to send data before it times out and + * retries it later. This is a wrapper for setting SO_SNDTIMEO. + * + * @param cell_t 0 (=default) to disable or time in ms + * @return bool true on success + */ + SocketSendTimeout, +/** + * If this option is set the socket extension will display debugging messages in the server console/logs. + * + * @param bool whether to enable debugging or not + * @return bool true on success + */ + DebugMode +} + + +/*************************************************************************************************/ +/******************************************* callbacks *******************************************/ +/*************************************************************************************************/ + + +/** + * triggered if a normal sockets finished connecting and is ready to be used + * + * @param socket The socket handle pointing to the calling socket + * @param arg The argument set by SocketSetArg() + * @noreturn + */ +funcenum SocketConnectCB +{ + public(Handle:socket, any:arg) +}; + +/** + * triggered if a listening socket received an incoming connection and is ready to be used + * + * @note The child-socket won't work until receive-, disconnect-, and errorcallback for it are set. + * + * @param Handle socket The socket handle pointing to the calling listen-socket + * @param Handle newSocket The socket handle to the newly spawned child socket + * @param String remoteIP The remote IP + * @param any arg The argument set by SocketSetArg() for the listen-socket + * @noreturn + */ +funcenum SocketIncomingCB +{ + public(Handle:socket, Handle:newSocket, const String:remoteIP[], remotePort, any:arg) +}; + +/** + * triggered if a socket receives data + * + * @note This is binary safe if you always use dataSize for operations on receiveData[] + * @note packets may be split up into multiple chunks -> multiple calls to the receive callback + * @note if not set otherwise by SocketSetOption(..., ConcatenateCallbacks, ...) receiveData will + * never be longer than 4096 characters including \0 terminator + * + * @param Handle socket The socket handle pointing to the calling socket + * @param String receiveData The data which arrived, 0-terminated at receiveData[dataSize] + * @param cell_t dataSize The length of the arrived data excluding the 0-termination + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketReceiveCB +{ + public(Handle:socket, const String:receiveData[], const dataSize, any:arg) +}; + +/** + * called after a socket sent all items in its send queue successfully + * + * @param Handle socket The socket handle pointing to the calling socket + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketSendqueueEmptyCB +{ + public(Handle:socket, any:arg) +}; + +/** + * called if a socket has been properly disconnected by the remote side + * + * @note You should call CloseHandle(socket) or reuse the socket before this function ends + * + * @param Handle socket The socket handle pointing to the calling socket + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketDisconnectCB +{ + public(Handle:socket, any:arg) +}; + +/** + * called if an unrecoverable error occured, close the socket without an additional call to a disconnect callback + * + * @note You should call CloseHandle(socket) or reuse the socket before this function ends + * + * @param Handle socket The socket handle pointing to the calling socket + * @param cell_t errorType The error type, see defines above + * @param cell_t errorNum The errno, see errno.h for details + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketErrorCB +{ + public(Handle:socket, const errorType, const errorNum, any:arg) +}; + + +/*************************************************************************************************/ +/******************************************** natives ********************************************/ +/*************************************************************************************************/ + + +/** + * Returns whether a socket is connected or not. + * + * @param socket Socket handle to check + * @return bool The connection status + */ +native bool:SocketIsConnected(Handle:socket); + + +/** + * Creates a new socket. + * + * @note this function may be relatively expensive, reuse sockets if possible + * + * @param SocketType protocol The protocol to use, SOCKET_TCP is default + * @param SocketErrorCB efunc The error callback + * @return Handle The socket handle. Returns INVALID_HANDLE on failure + */ +native Handle:SocketCreate(SocketType:protocol=SOCKET_TCP, SocketErrorCB:efunc); + +/** + * Binds the socket to a local address + * + * @param Handle socket The handle of the socket to be used. * @param String hostname The hostname (or IP) to bind the socket to. + * @param cell_t port The port to bind the socket to. + * @return bool true on success + */ +native bool:SocketBind(Handle:socket, const String:hostname[], port); + +/** + * Connects a socket + * + * @note this native is threaded, it may be still running after it executed, use the connect callback + * @note invokes the SocketError callback with errorType = CONNECT_ERROR or EMPTY_HOST if it fails + * @note invokes the SocketConnect callback if it succeeds + * + * @param Handle socket The handle of the socket to be used. + * @param SocketConnectCB cfunc The connect callback + * @param SocketReceiveCB rfunc The receive callback + * @param SocketDisconnectCB dfunc The disconnect callback * @param String hostname The hostname (or IP) to connect to. + * @param cell_t port The port to connect to. + * @noreturn + */ +native SocketConnect(Handle:socket, SocketConnectCB:cfunc, SocketReceiveCB:rfunc, SocketDisconnectCB:dfunc, const String:hostname[], port); + +/** + * Disconnects a socket + * + * @note this will not close the handle, the socket will be reset to a state similar to after SocketCreate() + * @note this won't trigger any disconnect/error callbacks + * + * @noreturn + */ +native bool:SocketDisconnect(Handle:socket); + +/** + * Makes a socket listen for incoming connections + * + * @param Handle socket The handle of the socket to be used. + * @param SocketIncomingCB ifunc The callback for incoming connections + * @return bool true on success + */ +native bool:SocketListen(Handle:socket, SocketIncomingCB:ifunc); + +/** + * Sends data through the socket. + * + * @note specify size for binary safe operation + * @note if size is not specified the \0 terminator will not be included + * @note This native is threaded, it may be still running after it executed (not atomic). + * @note Use the SendqueueEmpty callback to determine when all data has been successfully sent. + * @note The socket extension will ensure that the data will be send in the correct order and split + * the data if required. + * + * @param Handle socket The handle of the socket to be used. + * @param String data The data to send. + * @noreturn */ +native SocketSend(Handle:socket, const String:data[], size=-1); + +/** * Sends UDP data through the socket to a specific destination. + * + * @note specify size for binary safe operation + * @note if size is not specified the \0 terminator will not be included + * @note This native is threaded, it may be still running after it executed (not atomic). + * @note Use the SendqueueEmpty callback to determine when all data has been successfully sent. + * @note The socket extension will ensure that the data will be send in the correct order and split + * the data if required. + * + * @param Handle socket The handle of the socket to be used. + * @param String data The data to send. + * @param String hostname The hostname (or IP) to send to. + * @param cell_t port The port to send to. + * @noreturn */ +native SocketSendTo(Handle:socket, const String:data[], size=-1, const String:hostname[], port); + +/** + * Set a socket option. + * + * @param Handle socket The handle of the socket to be used. May be INVALID_HANDLE if not essential. + * @param SocketOption option The option to modify (see enum SocketOption for details). + * @param cellt_ value The value to set the option to. + * @return cell_t 1 on success. */ +native SocketSetOption(Handle:socket, SocketOption:option, value); + + +/** + * Defines the callback function for when the socket receives data + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketConnect()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketReceiveCB rfunc The receive callback + * @noreturn + */ +native SocketSetReceiveCallback(Handle:socket, SocketReceiveCB:rfunc); + +/** + * Defines the callback function for when the socket sent all items in its send queue + * + * @note this must be called AFTER sending (queueing) the data + * @note if no send-data is queued this will fire the callback itself + * @note the callback is guaranteed to fire + * + * @param Handle socket The handle of the socket to be used. + * @param SocketDisconnectCB dfunc The disconnect callback + * @noreturn + */ +native SocketSetSendqueueEmptyCallback(Handle:socket, SocketSendqueueEmptyCB:sfunc); + +/** + * Defines the callback function for when the socket was properly disconnected by the remote side + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketConnect()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketDisconnectCB dfunc The disconnect callback + * @noreturn + */ +native SocketSetDisconnectCallback(Handle:socket, SocketDisconnectCB:dfunc); + +/** + * Defines the callback function for when the socket triggered an error + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketCreate()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketErrorCB efunc The error callback + * @noreturn + */ +native SocketSetErrorCallback(Handle:socket, SocketErrorCB:efunc); + + +/** + * Sets the argument being passed to callbacks + * + * @param Handle socket The handle of the socket to be used. + * @param any arg The argument to set + * @noreturn + */ +native SocketSetArg(Handle:socket, any:arg); + +/** + * Retrieve the local system's hostname as the command "hostname" does. + * + * @param dest Destination string buffer to copy to. + * @param destLen Destination buffer length (includes null terminator). + * + * @return 1 on success + */ +native SocketGetHostName(String:dest[], destLen); + +/** + * _________________Do not edit below this line!_______________________ + */ +public Extension:__ext_smsock = +{ + name = "Socket", + file = "socket.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; diff --git a/scripting/include/system2.inc b/scripting/include/system2.inc new file mode 100644 index 0000000..91d03e1 --- /dev/null +++ b/scripting/include/system2.inc @@ -0,0 +1,462 @@ +/** + * ----------------------------------------------------- + * File system2.inc + * Authors David Ordnung + * License GPLv3 + * Web http://dordnung.de + * ----------------------------------------------------- + * + * Copyright (C) 2013-2020 David Ordnung + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + */ + +#if defined _system2_included + #endinput +#endif + +#define _system2_included + +// Include request stuff +#include + + +/** + * Max length of a command when using formatted natives. + */ +#define CMD_MAX_LENGTH 2048 + + +/** + * A list of possible compression levels for the System2_Compress native. + */ +enum CompressLevel +{ + LEVEL_1, // Weekest + LEVEL_3, + LEVEL_5, + LEVEL_7, + LEVEL_9 // Strongest +} + + +/** + * A list of possible archive formats for the System2_Compress native. + */ +enum CompressArchive +{ + ARCHIVE_ZIP, + ARCHIVE_7Z, + ARCHIVE_GZIP, + ARCHIVE_BZIP2, + ARCHIVE_TAR +} + + +/** + * A list of possible operating systems for the System2_GetOS native. + */ +enum OS +{ + OS_UNKNOWN, // OS couldn't be determined + OS_WINDOWS, // Windows + OS_UNIX, // Linux / Unix + OS_MAC // MAC +} + + + +/** + * Called when finished with the System2_CopyFile native. + * + * @param success Whether copying was successful (will fail if couldn't open 'from' or 'to' file). + * @param from Path to file that was copied. + * @param to Path to the new copied file. + * @param data Data passed to the copy native. + * + * @noreturn + */ +typeset System2CopyCallback +{ + function void (bool success, const char[] from, const char[] to, any data); + function void (bool success, const char[] from, const char[] to); +}; + + +/** + * Called when finished with System2_ExecuteThreaded or System2_ExecuteFormattedThreaded native. + * The output will only be valid in the callback and will be destroyed afterwards. + * + * @param success Whether the execution was successful or not. + * This not means that the command itself was successful! + * Check the ExitStatus of the output for this. + * @param command The executed command. + * @param output Output of the execution. Is null if success is false. + * Can't be deleted, as it will be destroyed after the callback! + * @param data Data passed to the execution native. + * + * @noreturn + */ +typeset System2ExecuteCallback +{ + function void (bool success, const char[] command, System2ExecuteOutput output, any data); + function void (bool success, const char[] command, System2ExecuteOutput output); +}; + + + +/** + * Methodmap for the output of an execution. + */ +methodmap System2ExecuteOutput < Handle { + /** + * Retrieves the output of the command execution. + * + * @param output Buffer to store the output in. + * @param maxlength Maxlength of the output buffer. + * @param start Start byte to start reading from. + * You can use this to retrieve the output step by step. + * @param delimiter Delimiter until which the content should be retrieved. + * @param include Whether the delimiter should be included or not. + * + * @return Number of read bytes. + * @error Invalid Output. + */ + public native int GetOutput(char[] output, int maxlength, int start = 0, const char[] delimiter = "", bool include = true); + + property int Length { + /** + * Returns the length of the complete output. + * + * @return Length of the output. + * @error Invalid Output. + */ + public native get(); + } + + property int ExitStatus { + /** + * Returns the exit status of the execution. + * + * @return The exit status. + * @error Invalid Output. + */ + public native get(); + } +} + + + +/** + * Copies a file to another location. + * + * @param callback Callback function when finished with copying. + * @param from Path to the file to copy. + * @param to Path to the file to copy to (including filename). File will be replaced if it exists. + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +native void System2_CopyFile(System2CopyCallback callback, const char[] from, const char[] to, any data = 0); + + +/** + * Checks whether 7-ZIP was found and is executable. + * + * @param execPath Buffer which will store the path to the 7-ZIP executable. + * Can be used for example when showing an error message. + * @param maxlength Maxlength of the buffer. + * @param force32Bit Whether to force using the 32 bit version of 7-ZIP, otherwise the appropriate version will be used. + * + * @return True if 7-ZIP executable could be found and is executable, otherwise false. + */ +native bool System2_Check7ZIP(char[] execPath, int maxlength, bool force32Bit = false); + +/** + * Compresses a file or folder to an archive. + * + * @param callback Callback function when finished with compressing. + * @param path Path to the file / folder to compress. + * @param archive Path to the archive file to compress to (including filename). + * @param archiveType Archive type to use. + * @param level Compress level to use. + * @param data Additional data to pass to the callback. + * @param force32Bit Whether to force using the 32 bit version of 7-ZIP, otherwise the appropriate version will be used. + * + * @return True if compress command could be fired, false when 7-ZIP executable couldn't be found or is not executable. + */ +native bool System2_Compress(System2ExecuteCallback callback, const char[] path, const char[] archive, CompressArchive archiveType = ARCHIVE_ZIP, CompressLevel level = LEVEL_9, any data = 0, bool force32Bit = false); + +/** + * Extracts a lot of archive types with 7zip. + * + * @param callback Callback function when finished with extracting. + * @param archive Path to the archive file to extract. + * @param extractDir Path to the directory to extract to. + * @param data Additional data to pass to the callback. + * @param force32Bit Whether to force using the 32 bit version of 7-ZIP, otherwise the appropriate version will be used. + * + * @return True if extract command could be fired, false when 7-ZIP executable couldn't be found or is not executable. + */ +native bool System2_Extract(System2ExecuteCallback callback, const char[] archive, const char[] extractDir, any data = 0, bool force32Bit = false); + + + +/** + * Executes a threaded system command. + * Hint: Append 2>&1 to your command to retrieve also output to stderr. + * + * @param callback Callback function when command was executed. + * @param command Command to execute. + * @param data Data to pass to the callback. + * + * @noreturn + */ +native void System2_ExecuteThreaded(System2ExecuteCallback callback, const char[] command, any data = 0); + +/** + * Executes a threaded system command with support for a formatted command. + * Note that the maxlength of the command is CMD_MAX_LENGTH, use System2_ExecuteThreaded if you need more. + * Hint: Append 2>&1 to your command to retrieve also output to stderr. + * + * @param callback Callback function when command was executed. + * @param data Data to pass to the callback. + * @param command Command string format. + * @param ... Command string arguments. + * + * @noreturn + */ +native void System2_ExecuteFormattedThreaded(System2ExecuteCallback callback, any data, const char[] command, any ...); + +/** + * Executes a non threaded system command. + * Hint: Append 2>&1 to your command to retrieve also output to stderr. + * + * @param output Buffer to store the output in. + * @param maxlength Maxlength of the output buffer. + * @param command Command to execute. + * + * @return True on success, otherwise false. + */ +native bool System2_Execute(char[] output, int maxlength, const char[] command); + +/** + * Executes a non threaded system command with support for a formatted command. + * Note that the maxlength of the command is CMD_MAX_LENGTH, use System2_Execute if you need more. + * Hint: Append 2>&1 to your command to retrieve also output to stderr. + * + * @param output Buffer to store the output in. + * @param maxlength Maxlength of the output buffer. + * @param command Command string format. + * @param ... Command string arguments. + * + * @return True on success, otherwise false. + */ +native bool System2_ExecuteFormatted(char[] output, int maxlength, const char[] command, any ...); + + + +/** + * Retrieves the absolute path to the gamedir of the current running game (e.g. /home/.../.../cstrike). + * You may need this when executing system commands. + * + * @param gamedir Buffer to store gamedir in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + */ +native void System2_GetGameDir(char[] gamedir, int maxlength); + +/** + * Returns the server's operating system. + * + * @return OS_UNKNOWN, OS_WINDOWS, OS_UNIX, OS_MAC. + */ +native OS System2_GetOS(); + + + +/** + * Retrieves the MD5 hex hash of a string. + * + * @param string String to retrieve the MD5 hash of. + * @param buffer Buffer to store MD5 hash in. + * @param maxlength Maxlength of the buffer. Should be greater or equal to 33 (32 MD5 + 1 terminator). + * + * @noreturn + */ +native void System2_GetStringMD5(const char[] str, char[] buffer, int maxlength); + +/** + * Retrieves the MD5 hex hash of a files content. + * + * @param file The path to the file. + * @param buffer Buffer to store MD5 hash in. + * @param maxlength Maxlength of the buffer. Should be greater or equal to 33 (32 MD5 + 1 terminator). + * + * @return True on success, false when file couldn't be opened. + */ +native bool System2_GetFileMD5(const char[] file, char[] buffer, int maxlength); + +/** + * Retrieves the CRC32 hex hash of a string. + * + * @param string The string to retrieve the CRC32 hash of. + * @param buffer Buffer to store CRC32 hash in. + * @param maxlength Maxlength of the buffer. Should be greater or equal to 9 (8 CRC32 + 1 terminator). + * + * @noreturn + */ +native void System2_GetStringCRC32(const char[] str, char[] buffer, int maxlength); + +/** + * Retrieves the CRC32 hex hash of a files content. + * + * @param file The path to the file. + * @param buffer Buffer to store CRC32 hash in. + * @param maxlength Maxlength of the buffer. Should be greater or equal to 9 (8 CRC32 + 1 terminator). + * + * @return True on success, false when file couldn't be opened. + */ +native bool System2_GetFileCRC32(const char[] file, char[] buffer, int maxlength); + + +// Include legacy stuff +#include + + +public Extension __ext_system2 = +{ + name = "System2", + file = "system2.ext", + + #if defined AUTOLOAD_EXTENSIONS + autoload = 1, + #else + autoload = 0, + #endif + + #if defined REQUIRE_EXTENSIONS + required = 1, + #else + required = 0, + #endif +}; + + +#if !defined REQUIRE_EXTENSIONS + public void __ext_system2_SetNTVOptional() + { + MarkNativeAsOptional("System2Request.SetURL"); + MarkNativeAsOptional("System2Request.GetURL"); + MarkNativeAsOptional("System2Request.SetPort"); + MarkNativeAsOptional("System2Request.GetPort"); + MarkNativeAsOptional("System2Request.SetOutputFile"); + MarkNativeAsOptional("System2Request.GetOutputFile"); + MarkNativeAsOptional("System2Request.SetVerifySSL"); + MarkNativeAsOptional("System2Request.GetVerifySSL"); + MarkNativeAsOptional("System2Request.SetProxy"); + MarkNativeAsOptional("System2Request.SetProxyAuthentication"); + MarkNativeAsOptional("System2Request.Timeout.get"); + MarkNativeAsOptional("System2Request.Timeout.set"); + MarkNativeAsOptional("System2Request.Any.get"); + MarkNativeAsOptional("System2Request.Any.set"); + + MarkNativeAsOptional("System2HTTPRequest.System2HTTPRequest"); + MarkNativeAsOptional("System2HTTPRequest.SetProgressCallback"); + MarkNativeAsOptional("System2HTTPRequest.SetData"); + MarkNativeAsOptional("System2HTTPRequest.GetData"); + MarkNativeAsOptional("System2HTTPRequest.SetHeader"); + MarkNativeAsOptional("System2HTTPRequest.GetHeader"); + MarkNativeAsOptional("System2HTTPRequest.GetHeaderName"); + MarkNativeAsOptional("System2HTTPRequest.SetUserAgent"); + MarkNativeAsOptional("System2HTTPRequest.SetBasicAuthentication"); + MarkNativeAsOptional("System2HTTPRequest.GET"); + MarkNativeAsOptional("System2HTTPRequest.POST"); + MarkNativeAsOptional("System2HTTPRequest.PUT"); + MarkNativeAsOptional("System2HTTPRequest.PATCH"); + MarkNativeAsOptional("System2HTTPRequest.DELETE"); + MarkNativeAsOptional("System2HTTPRequest.HEAD"); + MarkNativeAsOptional("System2HTTPRequest.FollowRedirects.get"); + MarkNativeAsOptional("System2HTTPRequest.FollowRedirects.set"); + MarkNativeAsOptional("System2HTTPRequest.Headers.get"); + + MarkNativeAsOptional("System2FTPRequest.System2FTPRequest"); + MarkNativeAsOptional("System2FTPRequest.SetProgressCallback"); + MarkNativeAsOptional("System2FTPRequest.SetAuthentication"); + MarkNativeAsOptional("System2FTPRequest.SetInputFile"); + MarkNativeAsOptional("System2FTPRequest.GetInputFile"); + MarkNativeAsOptional("System2FTPRequest.StartRequest"); + MarkNativeAsOptional("System2FTPRequest.AppendToFile.get"); + MarkNativeAsOptional("System2FTPRequest.AppendToFile.set"); + MarkNativeAsOptional("System2FTPRequest.CreateMissingDirs.get"); + MarkNativeAsOptional("System2FTPRequest.CreateMissingDirs.set"); + MarkNativeAsOptional("System2FTPRequest.ListFilenamesOnly.get"); + MarkNativeAsOptional("System2FTPRequest.ListFilenamesOnly.set"); + + MarkNativeAsOptional("System2Response.GetLastURL"); + MarkNativeAsOptional("System2Response.GetContent"); + MarkNativeAsOptional("System2Response.ContentLength.get"); + MarkNativeAsOptional("System2Response.StatusCode.get"); + MarkNativeAsOptional("System2Response.TotalTime.get"); + MarkNativeAsOptional("System2Response.DownloadSize.get"); + MarkNativeAsOptional("System2Response.UploadSize.get"); + MarkNativeAsOptional("System2Response.DownloadSpeed.get"); + MarkNativeAsOptional("System2Response.UploadSpeed.get"); + + MarkNativeAsOptional("System2HTTPResponse.GetContentType"); + MarkNativeAsOptional("System2HTTPResponse.GetHeader"); + MarkNativeAsOptional("System2HTTPResponse.GetHeaderName"); + MarkNativeAsOptional("System2HTTPResponse.GetHeadersCount"); + MarkNativeAsOptional("System2HTTPResponse.HTTPVersion.get"); + MarkNativeAsOptional("System2HTTPResponse.Headers.get"); + + MarkNativeAsOptional("System2_URLEncode"); + MarkNativeAsOptional("System2_URLDecode"); + + MarkNativeAsOptional("System2_CopyFile"); + + MarkNativeAsOptional("System2_Check7ZIP"); + MarkNativeAsOptional("System2_Compress"); + MarkNativeAsOptional("System2_Extract"); + + MarkNativeAsOptional("System2_ExecuteThreaded"); + MarkNativeAsOptional("System2_ExecuteFormattedThreaded"); + MarkNativeAsOptional("System2ExecuteOutput.GetOutput"); + MarkNativeAsOptional("System2ExecuteOutput.Length.get"); + MarkNativeAsOptional("System2ExecuteOutput.ExitStatus.get"); + + MarkNativeAsOptional("System2_Execute"); + MarkNativeAsOptional("System2_ExecuteFormatted"); + + MarkNativeAsOptional("System2_GetGameDir"); + MarkNativeAsOptional("System2_GetOS"); + + MarkNativeAsOptional("System2_GetStringMD5"); + MarkNativeAsOptional("System2_GetFileMD5"); + MarkNativeAsOptional("System2_GetStringCRC32"); + MarkNativeAsOptional("System2_GetFileCRC32"); + + // Deprecated v2 stuff + MarkNativeAsOptional("System2_GetPage"); + MarkNativeAsOptional("System2_DownloadFile"); + MarkNativeAsOptional("System2_DownloadFTPFile"); + MarkNativeAsOptional("System2_UploadFTPFile"); + MarkNativeAsOptional("System2_CompressFile"); + MarkNativeAsOptional("System2_ExtractArchive"); + MarkNativeAsOptional("System2_RunThreadCommand"); + MarkNativeAsOptional("System2_RunThreadCommandWithData"); + MarkNativeAsOptional("System2_RunCommand"); + } +#endif \ No newline at end of file diff --git a/scripting/include/system2/legacy.inc b/scripting/include/system2/legacy.inc new file mode 100644 index 0000000..7827853 --- /dev/null +++ b/scripting/include/system2/legacy.inc @@ -0,0 +1,284 @@ +/** + * ----------------------------------------------------- + * File legacy.inc + * Authors David Ordnung + * License GPLv3 + * Web http://dordnung.de + * ----------------------------------------------------- + * + * Copyright (C) 2013-2020 David Ordnung + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + */ + +#if defined _system2_legacy_included + #endinput +#endif + +#define _system2_legacy_included + + +/** + * + * DEPRECATED v2 STUFF, do not use that anymore! + * + */ + +/** + * Max Size of the command or page output in CmdCallback. + */ +#define CMD_MAX_RETURN 4096 + + +/** + * A list of possible command return states + */ +enum CMDReturn +{ + CMD_SUCCESS, // Fully finished + CMD_EMPTY, // Result is empty (only System2_RunThreadCommand) + CMD_ERROR, // An error appeared + CMD_PROGRESS // Not finished yet -> Wait for other state +} + + +/** + * Called when finished with a command or when retrieving the content of a page. + * Maybe called more than once, if output is greater than 4096 bytes. + * Use status variable to check if it's the last call or not. + * + * @param output Output of the command / page. + * @param size Size of output string. + * @param status CMDReturn status. + * @param data Data passed. + * @param command The command that was executed. Will be empty with PageGet. + */ +typeset CmdCallback +{ + function void (const char[] output, const int size, CMDReturn status, any data, const char[] command); + function void (const char[] output, const int size, CMDReturn status, any data); + function void (const char[] output, const int size, CMDReturn status); +}; + + +/** + * Called on every update when downloading / uploading a file. + * + * @param finished Is downloading / uploading finished? + * @param error Error when finished. If no error string is empty. + * @param dltotal Total downloaded size in bytes. + * @param dlnow Current downloaded size in bytes. + * @param ultotal Total uploaded size in bytes. + * @param ulnow Current uploaded size in bytes. + * @param data Data passed. + */ +typeset TransferUpdated +{ + function void (bool finished, const char[] error, float dltotal, float dlnow, float ultotal, float ulnow, any data); + function void (bool finished, const char[] error, float dltotal, float dlnow, float ultotal, float ulnow); +}; + + +/** + * Gets the content of a page. + * + * @param callback Callback function when finished. Check callback.status to check if process is finished. + * @param url The URL of the page to load. Attach GET parameters here and leave post parameter empty to perform a GET request. + * @param post POST parameters (use like this: "name=test&pw=test2"). Leave empty to perform a GET request. + * @param userAgent Useragent to use. Leave empty for default one. + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2HTTPRequest instead. +native void System2_GetPage(CmdCallback callback, const char[] url, const char[] post = "", const char[] userAgent = "", any data = INVALID_HANDLE); + + +/** + * Downloads a file from an URL. + * + * @param updateFunction Function to call on update. Check updateFunction.finished to check if downloading is finished. + * @param url File URL to download from. + * @param localFile Local file to save to. + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2HTTPRequest instead. +native void System2_DownloadFile(TransferUpdated updateFunction, const char[] url, const char[] localFile, any data = INVALID_HANDLE); + + +/** + * Downloads a file from a FTP server. + * + * @param updateFunction Function to call on update. Check updateFunction.finished to check if downloading is finished. + * @param remoteFile Path to the file on the FTP server. + * @param localFile Local file to save to. + * @param host The FTP host. + * @param user The FTP username. + * @param pass The FTP password. + * @param port The FTP port (Default: 21). + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2FTPRequest instead. +native void System2_DownloadFTPFile(TransferUpdated updateFunction, const char[] remoteFile, const char[] localFile, const char[] host, const char[] user = "", const char[] pass = "", int port = 21, any data = INVALID_HANDLE); + + +/** + * Uploads a file to a FTP server. + * + * @param updateFunction Function to call on update. Check updateFunction.finished to check if uploading is finished. + * @param localFile Local file to upload. + * @param remoteFile Path to the file on the FTP server. + * @param host The FTP host. + * @param user The FTP username. + * @param pass The FTP password. + * @param port The FTP port (Default: 21). + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2FTPRequest instead. +native void System2_UploadFTPFile(TransferUpdated updateFunction, const char[] localFile, const char[] remoteFile, const char[] host, const char[] user = "", const char[] pass = "", int port = 21, any data = INVALID_HANDLE); + + +/** + * Compresses a file to an archive. + * + * @param callback Callback function when finished with compressing. Check callback.status to check if process is finished. + * @param pathToFile Path to the file / folder to compress. + * @param pathToCompress Path to save archive file to (including filename). + * @param archive Archive type to use. + * @param level Archive compress level to use. + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2_Compress instead. +native void System2_CompressFile(CmdCallback callback, const char[] pathToFile, const char[] pathToArchive, CompressArchive archive = ARCHIVE_ZIP, CompressLevel level = LEVEL_9, any data = INVALID_HANDLE); + + +/** + * Extracts a lot of archive types with 7zip. + * + * @param callback Callback function when finished with extracting. Check callback.status to check if process is finished. + * @param pathToArchive Path to the archive file. + * @param pathToExtract Path to extract to. + * @param data Additional data to pass to the callback. + * + * @noreturn + */ +#pragma deprecated Use System2_Extract instead. +native void System2_ExtractArchive(CmdCallback callback, const char[] pathToArchive, const char[] pathToExtract, any data = INVALID_HANDLE); + + +/** + * Executes a threaded system command. + * + * @param callback Callback function when command was executed. Check callback.status to check if process is finished. + * @param command Command string format. + * @param ... Command string arguments. + * + * @noreturn + */ +#pragma deprecated Use System2_ExecuteThreaded instead. +native void System2_RunThreadCommand(CmdCallback callback, const char[] command, any ...); + + +/** + * Executes a threaded system command and allows to pass additional data. + * + * @param callback Callback function when command was executed. Check callback.status to check if process is finished. + * @param data Data to pass to the callback. + * @param command Command string format. + * @param ... Command string arguments. + * + * @noreturn + */ +#pragma deprecated Use System2_ExecuteThreaded instead. +native void System2_RunThreadCommandWithData(CmdCallback callback, any data, const char[] command, any ...); + + +/** + * Executes a non threaded system command. + * + * @param output Variable to store the command output. + * @param size Size of the output variable. + * @param command Command string format. + * @param ... Command string arguments. + * + * @return CMDReturn status. + */ +#pragma deprecated Use System2_Execute instead. +native CMDReturn System2_RunCommand(char[] output, int size, const char[] command, any ...); + + +/** + * Encodes a string for safe url transfer. + * Written by Peace-Maker (i guess), formatted for better readability. + * + * @param stringToEncode The string to encode. + * @param maxlength The maxlength of the string. + * @param safe Adding additional safe strings. + * @param format Is the string formatted. + */ +#pragma deprecated Use System2_URLEncode instead. +stock void URLEncode(char[] stringToEncode, int maxlength, char[] safe = "/", bool format = false) +{ + char sAlwaysSafe[256]; + Format(sAlwaysSafe, sizeof(sAlwaysSafe), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-%s", safe); + + // Need 2 '%' since sp's Format parses one as a parameter to replace + // http://wiki.alliedmods.net/Format_Class_Functions_%28SourceMod_Scripting%29 + if (format) + { + ReplaceString(stringToEncode, maxlength, "%", "%%25"); + } + else + { + ReplaceString(stringToEncode, maxlength, "%", "%25"); + } + + + char sChar[8]; + char sReplaceChar[8]; + + for (new int i = 1; i < 256; i++) + { + // Skip the '%' double replace ftw.. + if (i == 37) + { + continue; + } + + + Format(sChar, sizeof(sChar), "%c", i); + + if (StrContains(sAlwaysSafe, sChar) == -1 && StrContains(stringToEncode, sChar) != -1) + { + if (format) + { + Format(sReplaceChar, sizeof(sReplaceChar), "%%%%%02X", i); + } + else + { + Format(sReplaceChar, sizeof(sReplaceChar), "%%%02X", i); + } + + ReplaceString(stringToEncode, maxlength, sChar, sReplaceChar); + } + } +} \ No newline at end of file diff --git a/scripting/include/system2/request.inc b/scripting/include/system2/request.inc new file mode 100644 index 0000000..611a6d5 --- /dev/null +++ b/scripting/include/system2/request.inc @@ -0,0 +1,944 @@ +/** + * ----------------------------------------------------- + * File request.inc + * Authors David Ordnung + * License GPLv3 + * Web http://dordnung.de + * ----------------------------------------------------- + * + * Copyright (C) 2013-2020 David Ordnung + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + */ + +#if defined _system2_request_included + #endinput +#endif + +#define _system2_request_included + + +/** + * + * API for making HTTP and FTP requests. + * + */ + + +/** + * A list of possible HTTP request methods. + */ +enum HTTPRequestMethod +{ + METHOD_GET, + METHOD_POST, + METHOD_PUT, + METHOD_PATCH, + METHOD_DELETE, + METHOD_HEAD +} + +/** + * A list of possible HTTP versions. + */ +enum HTTPVersion +{ + VERSION_NONE, + VERSION_1_0, + VERSION_1_1, + VERSION_2_0 +} + + +/** + * Called when a HTTP request was finished. + * + * The response will only be valid in the callback and will be destroyed afterwards. + * The request is a copy of the original request and will be destroyed afterwards. + * The request can be modified and made again. + * + * @param success Whether the request could made. + * This not means that the request itself was successful, check the StatusCode of the response for that! + * @param error If success is false this will contain the error message. + * @param request A copy of the made HTTP request. + * Can't be deleted, as it will be destroyed after the callback! + * @param response HTTP response of the request. Is null if success is false. + * Can't be deleted, as it will be destroyed after the callback! + * @param method The HTTP request method that was made. + * + * @noreturn + */ +typeset System2HTTPResponseCallback +{ + function void (bool success, const char[] error, System2HTTPRequest request, System2HTTPResponse response, HTTPRequestMethod method); +}; + +/** + * Called when a FTP request was finished. + * + * The response will only be valid in the callback and will be destroyed afterwards. + * The request is a copy of the original request and will be destroyed afterwards. + * The request can be modified and made again. + * + * @param success Whether the request could made. + * This not means that the request itself was successful, check the StatusCode of the response for that! + * @param error If success is false this will contain the error message. + * @param request A copy of the made FTP request. + * Can't be deleted, as it will be destroyed after the callback! + * @param response FTP response of the request. Is null if success is false. + * Can't be deleted, as it will be destroyed after the callback! + * + * @noreturn + */ +typeset System2FTPResponseCallback +{ + function void (bool success, const char[] error, System2FTPRequest request, System2FTPResponse response); +}; + + +/** + * Called on a frequent interval while data of a HTTP request is being transferred. + * The request is a copy of the original request and will be destroyed afterwards. + * + * @param request A copy of the made HTTP request. + * Can't be deleted, as it will be destroyed after the callback! + * @param dlTotal Total expected download size in bytes. + * @param dlNow Downloaded bytes so far. + * @param ulTotal Total expected upload size in bytes. + * @param ulNow Uploaded bytes so far. + * + * @noreturn + */ +typeset System2HTTPProgressCallback +{ + function void (System2HTTPRequest request, int dlTotal, int dlNow, int ulTotal, int ulNow); +}; + +/** + * Called on a frequent interval while data of a FTP request is being transferred. + * The request is a copy of the original request and will be destroyed afterwards. + * + * @param request A copy of the made FTP request. + * Can't be deleted, as it will be destroyed after the callback! + * @param dlTotal Total expected download size in bytes. + * @param dlNow Downloaded bytes so far. + * @param ulTotal Total expected upload size in bytes. + * @param ulNow Uploaded bytes so far. + * + * @noreturn + */ +typeset System2FTPProgressCallback +{ + function void (System2FTPRequest request, int dlTotal, int dlNow, int ulTotal, int ulNow); +}; + + + +/** + * Basic methodmap for a request. + * Use System2HTTPRequest or System2FTPRequest to actually create a request. + */ +methodmap System2Request < Handle { + /** + * Sets the URL of the request. + * Query parameters have to be given directly in the URL. + * + * Must be URL-encoded (use System2_URLEncode) in the following format: + * scheme://host:port/path + * + * Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets]. + * + * If the given URL is missing a scheme name (such as "http://" or "ftp://" etc) + * then system2 will make a guess based on the host. + * + * @param url URL to use for the request. + * @param ... URL format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetURL(const char[] url, any ...); + + /** + * Retrieves the URL of the request. + * + * @param url Buffer to store URL in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + * @error Invalid request. + */ + public native void GetURL(char[] url, int maxlength); + + /** + * Sets the remote port number to connect to, + * instead of the one specified in the URL or the default port for the used protocol + * + * @param port Port to use for the request. + * + * @noreturn + * @error Invalid request. + * @error Invalid port number. + */ + public native void SetPort(int port); + + /** + * Returns the port of the request. + * + * @return The port of the request or 0 if none set. + * @error Invalid request. + */ + public native int GetPort(); + + /** + * Sets the path to the file to which the output of the request will be written to. + * Use this to download the output of a response to a file. + * + * @param file File to write the output to. + * @param ... File format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetOutputFile(const char[] file, any ...); + + /** + * Retrieves the path to the file to which the output of the request will be written to. + * + * @param file Buffer to store file in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + * @error Invalid request. + */ + public native void GetOutputFile(char[] file, int maxlength); + + /** + * Sets whether to verify authenticity of the peer's certificate and server cert is for the server it is known as. + * Only disable this, when you know what you do! + * + * @param verify True to verify SSL certificates, otherwise false. + * + * @noreturn + * @error Invalid request. + */ + public native void SetVerifySSL(bool verify); + + /** + * Returns whether SSL certificates will be verified. + * + * @return True if SSL certificates will be verified, otherwise false. + * @error Invalid request. + */ + public native bool GetVerifySSL(); + + /** + * Sets proxy for the request. + * + * @param proxy Hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets]. + * To specify port number in this string, append :[port] to the end of the host name (default: 1080). + * The proxy string may be prefixed with [scheme]:// to specify which kind of proxy is used. + * http:// + * HTTP Proxy. Default when no scheme is specified. + * https:// + * HTTPS Proxy. + * socks4:// + * SOCKS4 Proxy. + * socks4a:// + * SOCKS4a Proxy. Proxy resolves URL hostname. + * socks5:// + * SOCKS5 Proxy. + * socks5h:// + * SOCKS5 Proxy. Proxy resolves URL hostname. + * @param useHttpTunnel Tunnel all operations through the HTTP proxy (use http or https)- + * Tunneling means that an HTTP CONNECT request is sent to the proxy, asking it to connect to a remote host + * on a specific port number and then the traffic is just passed through the proxy. Proxies tend to white-list + * specific port numbers it allows CONNECT requests to and often only port 80 and 443 are allowed. + * + * @noreturn + * @error Invalid request. + */ + public native void SetProxy(const char[] proxy, bool useHttpTunnel = false); + + /** + * Sets the username and password to be used in protocol authentication with the proxy. + * + * @param username Username to use for proxy authentication. + * @param password Password to use for proxy authentication. + * + * @noreturn + * @error Invalid request. + */ + public native void SetProxyAuthentication(const char[] username, const char[] password); + + + property int Timeout { + /** + * Returns the timeout for the request. + * By default, there is no timeout. + * + * @return The timeout of the request in seconds or -1 if none set. + * @error Invalid request. + */ + public native get(); + + /** + * Sets the timeout for the request in seconds. + * By default, there is no timeout. + * + * @param seconds The timeout for the request in seconds. 0 to disable. + * + * @noreturn + * @error Invalid request. + * @error Invalid timeout. + */ + public native set(int seconds); + } + + property any Any { + /** + * Returns the any data that was bound to this request. + * + * @return The any data that was bound or 0 if none set. + * @error Invalid request. + */ + public native get(); + + /** + * Sets any data to bind to the request (which you can then use in callbacks). + * + * @param Any The any data to bind. + * + * @noreturn + * @error Invalid request. + */ + public native set(any Any); + } +} + + +/** + * Methodmap to create a HTTP request. + */ +methodmap System2HTTPRequest < System2Request { + /** + * Creates a new HTTP Request. + * + * @param callback Response callback to call when the request is finished. + * @param url URL to use for the request. + * Query parameters have to be given directly in the URL. + * + * Must be URL-encoded (use System2_URLEncode) in the following format: + * scheme://host:port/path + * + * Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets]. + * If no scheme is given, HTTP will be used. + * @param ... URL format arguments. + * + * @noreturn + * @error Couldn't create request. + */ + public native System2HTTPRequest(System2HTTPResponseCallback callback, const char[] url, any ...); + + /** + * Sets the progress callback for the transfer of the request. + * This will be called frequently while data is being transferred. + * This is useful when downloading or uploading stuff. + * + * @param callback Progress callback to call for the transfer. + * + * @noreturn + * @error Invalid request. + */ + public native void SetProgressCallback(System2HTTPProgressCallback callback); + + + /** + * Sets the body data to send with the request. + * You must make sure that the data is formatted the way you want the server to receive it. + * Use System2_URLEncode to encode the data. + * + * For example: parameter=value¶meter2=value2 + * Or with JSON: {"parameter": "value", "parameter2": "value2"} + * + * @param data Body data to send with the request. + * @param ... Data format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetData(const char[] data, any ...); + + /** + * Retrieves the body data of the request. + * + * @param url Buffer to store data in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + * @error Invalid request. + */ + public native void GetData(char[] data, int maxlength); + + + /** + * Sets a HTTP request header. + * Use System2_URLEncode to encode the header. + * + * @param name Name of the header. + * @param value Value to set the header to. + * @param ... Value format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetHeader(const char[] header, const char[] value, any ...); + + /** + * Retrieves a HTTP request header. + * + * @param name Name of the header to retrieve. + * @param value Buffer to store value in. + * @param maxlength Maxlength of the buffer. + * + * @return True if header was set, otherwise false. + * @error Invalid request. + */ + public native bool GetHeader(const char[] header, char[] value, int maxlength); + + /** + * Retrieves the name of a header at a given index. + * Use Headers property to retrieve the maximum index. + * + * @param index Index of the header name. + * @param name Buffer to store name in. + * @param maxlength Maxlength of the buffer. + * + * @return True if header was found, otherwise false. + * @error Invalid request. + */ + public native bool GetHeaderName(int index, char[] name, int maxlength); + + property int Headers { + /** + * Returns the number of set headers. + * + * @return The number of set headers. + * @error Invalid response. + */ + public native get(); + } + + /** + * Returns all set header names of the request as ArrayList. + * Attention: ArrayList has to be deleted after use! + + * @param maxlength Maxlength of a header. + * + * @return ArrayList with all set request header names. Must be deleted afterwards! + * @error Invalid request. + */ + public ArrayList GetHeaders(int maxlength = 256) { + ArrayList headers = new ArrayList(maxlength); + + char[] headerName = new char[maxlength]; + for (int i=0; i < this.Headers; i++) { + this.GetHeaderName(i, headerName, maxlength); + headers.PushString(headerName); + } + + return headers; + } + + + /** + * Sets the user agent for the request. + * This will set the User-Agent header to the given value. + * + * @param userAgent User agent to use. + * @param ... User agent format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetUserAgent(const char[] userAgent, any ...); + + /** + * Sets basic authentication username and passowrd for the request. + * This will set the Authorization header to the given values. + * + * @param username Username to use for basic authentication. + * @param password Password to use for basic authentication. + * + * @noreturn + * @error Invalid request. + */ + public native void SetBasicAuthentication(const char[] username, const char[] password); + + /** + * Sends the request with the HTTP GET method. + * + * @noreturn + * @error Invalid request. + */ + public native void GET(); + + /** + * Sends the request with the HTTP POST method. + * + * @noreturn + * @error Invalid request. + */ + public native void POST(); + + /** + * Sends the request with the HTTP PUT method. + * + * @noreturn + * @error Invalid request. + */ + public native void PUT(); + + /** + * Sends the request with the HTTP PATCH method. + * + * @noreturn + * @error Invalid request. + */ + public native void PATCH(); + + /** + * Sends the request with the HTTP DELETE method. + * + * @noreturn + * @error Invalid request. + */ + public native void DELETE(); + + /** + * Sends the request with the HTTP HEAD method. + * + * @noreturn + * @error Invalid request. + */ + public native void HEAD(); + + + property bool FollowRedirects { + /** + * Returns whether the request follow redirects or not. + * By default, redirects will be followed. + * + * @return True if it follow redirects, otherwise false. + * @error Invalid request. + */ + public native get(); + + /** + * Sets to follow any Location: header that the server sends as part of an HTTP header in a 3xx response. + * For 301, 302 and 303 responses system2 will switch method to GET. All other 3xx codes will make system2 send the same method again. + * By default, redirects will be followed. + * + * @param follow True to follow redirects, otherwise false. + * + * @noreturn + * @error Invalid request. + */ + public native set(bool follow); + } +} + + +/** + * Methodmap to create a FTP request. + */ +methodmap System2FTPRequest < System2Request { + /** + * Creates a new FTP Request. + * + * @param callback Response callback to call when the request is finished. + * @param url URL to use for the request. + * + * Must be URL-encoded (use System2_URLEncode) in the following format: + * scheme://host:port/path + * + * Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets]. + * If no scheme is given, FTP will be used. + * @param ... URL format arguments. + * + * @noreturn + * @error Couldn't create request. + */ + public native System2FTPRequest(System2FTPResponseCallback callback, const char[] url, any ...); + + /** + * Sets the progress callback for the transfer of the request. + * This will be called frequently while data is being transferred. + * + * @param callback Progress callback to call for the transfer. + * + * @noreturn + * @error Invalid request. + */ + public native void SetProgressCallback(System2FTPProgressCallback callback); + + + /** + * Sets authentication needed to access the FTP server. + * + * @param username Username to use for authentication. + * @param password Password to use for authentication. + * + * @noreturn + * @error Invalid request. + */ + public native void SetAuthentication(const char[] username, const char[] password); + + + /** + * Sets the path to the file which should be uploaded. + * If this is set, an upload approach will be used. + * + * @param file File to upload. + * @param ... File format arguments. + * + * @noreturn + * @error Invalid request. + */ + public native void SetInputFile(const char[] file, any ...); + + /** + * Retrieves the path to the file which should be uploaded. + * + * @param file Buffer to store file in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + * @error Invalid request. + */ + public native void GetInputFile(char[] file, int maxlength); + + + /** + * Starts the request. + * + * If a input file is set the request will upload this file. + * Otherwise it may result in a directory listing or a file download. + * + * @noreturn + * @error Invalid request. + */ + public native void StartRequest(); + + + property bool AppendToFile { + /** + * Returns whether the request appends to the FTP file or replaces it when uploading a file. + * By default, the file will be replaced. + * + * @return True if it appends to the file, false if the file will be replaced. + * @error Invalid request. + */ + public native get(); + + /** + * Sets whether to append to the FTP file or to replace it when uploading a file. + * By default, the file will be replaced. + * + * @param append True to append to file, false to replace it. + * + * @noreturn + * @error Invalid request. + */ + public native set(bool append); + } + + property bool CreateMissingDirs { + /** + * Returns whether the request creates missing dirs when uploading a file. + * By default, missing dirs will be created. + * + * @return True if it creates missing dirs, otherwise false. + * @error Invalid request. + */ + public native get(); + + /** + * Sets whether to create any remote directory that it fails to "move" into. + * By default, missing dirs will be created. + * + * @param create True to create missing dirs, otherwise false. + * + * @noreturn + * @error Invalid request. + */ + public native set(bool create); + } + + property bool ListFilenamesOnly { + /** + * Returns whether only file names should be fetched for directory listing. + * By default, all information will be fetched. + * + * @return True if only file names should be fetched, false for full directory listing. + * @error Invalid request. + */ + public native get(); + + /** + * Sets whether to list the names of files in a directory, + * rather than performing a full directory listing that would normally include file sizes, dates etc. + * By default, all information will be fetched. + * + * @param append True if only file names should be fetched, false for full directory listing. + * + * @noreturn + * @error Invalid request. + */ + public native set(bool append); + } +} + + + +/** + * Basic methodmap for a response of a request. + */ +methodmap System2Response < Handle { + /** + * Retrieves the last used effective URL. + * This may differ from the request URL, if a redirect was followed. + * + * @param url Buffer to store last URL in. + * @param maxlength Maxlength of the URL buffer. + * + * @noreturn + * @error Invalid response. + */ + public native void GetLastURL(char[] url, int maxlength); + + /** + * Retrieves the content of the response. + * This shouldn't be used when retrieved binary stuff. + * + * @param content Buffer to store the content in. + * @param maxlength Maxlength of the content buffer. + * @param start Start byte to start reading from. + * You can use this to retrieve the content step by step. + * @param delimiter Delimiter until which the content should be retrieved. + * @param include Whether the delimiter should be included or not. + * + * @return Number of read bytes. + * @error Invalid response. + */ + public native int GetContent(char[] content, int maxlength, int start = 0, const char[] delimiter = "", bool include = true); + + + property int ContentLength { + /** + * Returns the length of the complete response content. + * + * @return Length of the content. + * @error Invalid response. + */ + public native get(); + } + + property int StatusCode { + /** + * Returns the status code of the response. + * + * @return The status code. + * @error Invalid response. + */ + public native get(); + } + + property float TotalTime { + /** + * Returns the total time from the request until the response in seconds. + * Includs name resolving, TCP connect etc. + * + * @return Total time from the request until the response in seconds. + * @error Invalid response. + */ + public native get(); + } + + property int DownloadSize { + /** + * Returns the total amount of bytes that were downloaded. + * This counts actual payload data, what's also commonly called body. + * All meta and header data are excluded and will not be counted in this number. + * + * @return Total amount of bytes that were downloaded. + * @error Invalid response. + */ + public native get(); + } + + property int UploadSize { + /** + * Returns the total amount of bytes that were uploaded. + * + * @return Total amount of bytes that were uploaded. + * @error Invalid response. + */ + public native get(); + } + + property int DownloadSpeed { + /** + * Returns the average download speed measured for the complete download in bytes per second. + * + * @return Average download speed in bytes per second. + * @error Invalid response. + */ + public native get(); + } + + property int UploadSpeed { + /** + * Returns the average upload speed measured for the complete upload in bytes per second. + * + * @return Average upload speed in bytes per second. + * @error Invalid response. + */ + public native get(); + } +} + + +/** + * Methodmap for a response of a HTTP request. + */ +methodmap System2HTTPResponse < System2Response { + /** + * Retrieves the content type of the response. + * This is the value read from the Content-Type header. + * + * @param type Buffer to store content type in. + * @param maxlength Maxlength of the buffer. + * + * @noreturn + * @error Invalid response. + */ + public native void GetContentType(const char[] type, int maxlength); + + /** + * Retrieves a HTTP response header + * + * @param name Name of the header to retrieve. + * @param value Buffer to store value in. + * @param maxlength Maxlength of the buffer. + * + * @return True if header was set, otherwise false. + * @error Invalid response. + */ + public native bool GetHeader(const char[] name, char[] value, int maxlength); + + /** + * Retrieves the name of a header at a given index. + * Use Headers property to retrieve the maximum index. + * + * @param index Index of the header name. + * @param name Buffer to store name in. + * @param maxlength Maxlength of the buffer. + * + * @return True if header was found, otherwise false. + * @error Invalid response. + */ + public native bool GetHeaderName(int index, char[] name, int maxlength); + + property int Headers { + /** + * Returns the number of set headers in the response. + * + * @return The number of set headers. + * @error Invalid response. + */ + public native get(); + } + + /** + * Returns all header set names of the response as ArrayList. + * Attention: ArrayList has to be deleted after use! + + * @param maxlength Maxlength of a header. + * + * @return ArrayList with all set response header names. Must be deleted! + * @error Invalid request. + */ + public ArrayList GetHeaders(int maxlength = 256) { + ArrayList headers = new ArrayList(maxlength); + + char[] headerName = new char[maxlength]; + for (int i=0; i < this.Headers; i++) { + this.GetHeaderName(i, headerName, maxlength); + headers.PushString(headerName); + } + + return headers; + } + + + property HTTPVersion HTTPVersion { + /** + * Returns the HTTP version of the response. + * + * @return The HTTP version. + * @error Invalid response. + */ + public native get(); + } +} + + +/** + * Methodmap for a response of a FTP request. + * Currently there are no special methods for that. + */ +methodmap System2FTPResponse < System2Response { +} + + + +/** + * Converts a plain string to an URL encoded string. + * All input characters that are not a-z, A-Z, 0-9, '-', '.', '_' or '~' + * are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number). + * + * Be aware that the output string may be larger then the input string. + * + * @param output Buffer to store encoded string in. May point to the input string (will replace the input string). + * @param maxlength Maxlength of the output buffer. + * @param input String to encode. + * @param ... Input string format arguments + * + * @return True on success, false otherwise. + */ +native bool System2_URLEncode(char[] output, int maxlength, const char[] input, any ...); + +/** + * Converts an URL encoded string to a plain string. + * All input characters that are URL encoded (%XX where XX is a two-digit hexadecimal number) are converted to their binary versions. + * + * @param output Buffer to store decoded string in. May point to the input string (will replace the input string). + * @param maxlength Maxlength of the output buffer. + * @param input String to decode. + * @param ... Input string format arguments + * + * @return True on success, false otherwise. + */ +native bool System2_URLDecode(char[] output, int maxlength, const char[] input, any ...); \ No newline at end of file diff --git a/scripting/include/tentdev.inc b/scripting/include/tentdev.inc new file mode 100644 index 0000000..1c9d1bf --- /dev/null +++ b/scripting/include/tentdev.inc @@ -0,0 +1,95 @@ +#if defined _ted_included_ + #endinput +#endif +#define _ted_included_ + +#define VERSION "0.1.1" + + +/** + * Sets the value of a netprop. + * + * @param client Client with a selected entity. + * @param sNetprop Netprop name. + * @param sValue Value to set the netprop to. + * @return True on success. + */ +native TED_SetNetprop(client, const String:sNetprop[], const String:sValue[]); + +/** + * Sets the selected entity for a client. + * + * @param client Client to select the entity + * @param sNetprop Entity index + * @return True on success. + */ +native TED_SelectEntity(client, entity); + +/** + * Adds a netprop to the ignore list of a specific client. + * The client is being notified through TED_OnNetpropHint(). + * + * @param client This clients ignore list will be changed. + * @param sNetprop Name of the netprop to be ignored, e.g. m_iHealth + * @return True on success. + */ +native TED_IgnoreNetprop(client, const String:sNetprop[]); + +/** + * Removes a netprop from the ignore list of a specific client + * The client is being notified through TED_OnNetpropHint(). + * + * @param client This clients ignore list will be changed. + * @param sNetprop Name of the netprop to be removed from the list + * @return True on success. + */ +native TED_UnignoreNetprop(client, const String:sNetprop[]); + +/** + * Shows all netprops and their values for the selected entity + * This will feed all information through TED_OnShow(). + * + * @param client The client issuing the action. He will see the output. + * @return True on success. + */ +native TED_ShowNetprops(client); + +/** + * Repeatedly shows all changed netprops for the selected entity + * This will feed all information through TED_OnCompare(). + * + * @param client The client issuing the action. He will see the output. + * @return True on success. + */ +native TED_WatchNetprops(client); + +/** + * Stops watching a entity + * + * @param client The client issuing the action. He will see the output. + * @return True on success. + */ +native TED_StopWatchNetprops(client); + +/** + * Saves the current state of netprops for later manual comparison. + * + * @param client The client issuing the action. + * @return True on success. + */ +native TED_SaveNetprops(client); + +/** + * Compares the current state of netprops with the saved state and outputs any differences. + * This will feed all information through TED_OnCompare(). + * + * @param client The client issuing the action. He will see the output. + * @return True on success. + */ +native TED_CompareNetprops(client); + + +forward TED_OnCompare(client, const String:sNetprop[], const String:sOld[], const String:sNow[], iOffset); +forward TED_OnNetpropHint(client, const String:sText[], const String:sNetprop[]); +forward TED_OnShow(client, const String:sNetprop[], const String:sValue[], iOffset); +forward TED_OnInfo(client, const String:sText[]); \ No newline at end of file diff --git a/scripting/include/tkstopper.inc b/scripting/include/tkstopper.inc new file mode 100644 index 0000000..8cf58ac --- /dev/null +++ b/scripting/include/tkstopper.inc @@ -0,0 +1,13 @@ +#if defined _tkstopper_included_ + #endinput +#endif +#define _tkstopper_included_ + +enum TKImmunityType { + TKImmune_Teamkill = 1, + TKImmune_ReverseFriendlyFire = 2 +} + +native void SetImmunity(int target, TKImmunityType type, bool value); + +native bool IsImmunity(int target, TKImmunityType type); \ No newline at end of file diff --git a/scripting/l4d2-info-cmd.sp b/scripting/l4d2-info-cmd.sp new file mode 100644 index 0000000..1d36488 --- /dev/null +++ b/scripting/l4d2-info-cmd.sp @@ -0,0 +1,322 @@ +#pragma semicolon 1 + +#define debug false + +#define PLUGIN_NAME "L4D2 Game Info" +#define PLUGIN_DESCRIPTION "" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.1" + +#include +#include +#include + +char g_icDifficulty[16] = "Normal"; +char g_icGamemode[16] = "coop"; +char g_icCurrentMap[32]; + +int g_icPlayerManager; //entid -> typically 25 (MaxClients+1) + +static bool b_isTransitioning[MAXPLAYERS+1]; +bool g_icHealing[MAXPLAYERS+1]; //state +bool g_icBeingHealed[MAXPLAYERS+1]; //state + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + + +// Socket infoSocket; +//TODO: Transition state + +public OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + //hook events & cmds + RegConsoleCmd("sm_gameinfo", PrintGameInfo, "Show the director main menu"); + HookEvent("difficulty_changed", Event_DifficultyChanged); + HookEvent("heal_begin", Event_HealStart); + //HookEvent("heal_end", Event_HealStop); + HookEvent("heal_success", Event_HealStop); + HookEvent("heal_interrupted", Event_HealStop); + //For transitioning: + HookEvent("map_transition", Event_MapTransition); + HookEvent("player_spawn", Event_PlayerSpawn); + + //hook cvars, game info states + FindConVar("z_difficulty").GetString(g_icDifficulty, sizeof(g_icDifficulty)); + ConVar ic_gamemode = FindConVar("mp_gamemode"); + ic_gamemode.GetString(g_icGamemode, sizeof(g_icGamemode)); + ic_gamemode.AddChangeHook(Event_GamemodeChange); + GetCurrentMap(g_icCurrentMap, sizeof(g_icCurrentMap)); + + //setup advertisement + CreateConVar("l4d2_gameinfo_version", PLUGIN_VERSION, "plugin version", FCVAR_SPONLY | FCVAR_DONTRECORD); +} +// print info +public Action PrintGameInfo(int client, int args) { + //print server info + ReplyToCommand(client, ">map,diff,mode,tempoState,totalSeconds,hastank"); + int missionDuration = GetEntProp(g_icPlayerManager, Prop_Send, "m_missionDuration", 1); + int tempoState = GetEntProp(g_icPlayerManager, Prop_Send, "m_tempoState", 1); + bool hasTank = false; + ReplyToCommand(client, "%s,%s,%s,%d,%d,%b",g_icCurrentMap,g_icDifficulty,g_icGamemode,tempoState,missionDuration,hasTank); + //print client info + ReplyToCommand(client,">id,transitioning,name,bot,health,status,throwSlot,kitSlot,pillSlot,survivorType,velocity,primaryWpn,secondaryWpn"); + char status[9]; + char name[32]; + char pillItem[32]; + char kitItem[32]; + char throwItem[32]; + char character[9]; + char primaryWeapon[32], secondaryWeapon[32]; + for (int i = 1; i <= MaxClients; i++) { + if(!IsClientConnected(i)) continue; + if(!IsClientInGame(i)) { + if(b_isTransitioning[i]) + ReplyToCommand(client,"%d,1", i); + else continue; + } + if (GetClientTeam(i) != 2) continue; + int hp = GetClientRealHealth(i); + int bot = IsFakeClient(i); + bool crouched = GetEntProp(i, Prop_Send, "m_bDucked", 1) == 1; + bool incap = GetEntProp(i, Prop_Send, "m_isIncapacitated", 1) == 1; + bool blackandwhite = GetEntProp(i, Prop_Send, "m_bIsOnThirdStrike", 1) == 1; + int velocity = RoundFloat(GetPlayerSpeed(i)); + + if(hp < 0) { + status = "dead"; + }else if(incap) { + status = "incap"; + }else if(blackandwhite) { + status = "neardead"; + }else if(g_icHealing[i]) { + status = "healing"; + }else if(g_icBeingHealed[i]) { + status = "bheal"; + }else if(crouched) { + status = "crouched"; + }else{ + status = "alive"; + } + primaryWeapon[0] = '\0'; + throwItem[0] = '\0'; + kitItem[0] = '\0'; + pillItem[0] = '\0'; + //TODO: Move all string-based stats to events + GetItemSlotClassName(i, 0, primaryWeapon, sizeof(primaryWeapon), true); + GetItemSlotClassName(i, 1, secondaryWeapon, sizeof(secondaryWeapon), true); + GetItemSlotClassName(i, 2, throwItem, sizeof(throwItem), true); + GetItemSlotClassName(i, 3, kitItem, sizeof(kitItem), true); + GetItemSlotClassName(i, 4, pillItem, sizeof(pillItem), true); + + /*if(StrEqual(secondaryWeapon, "melee", true)) { + GetMeleeWeaponName() + }*/ + + GetClientName(i, name, sizeof(name)); + GetModelName(i, character, sizeof(character)); + + ReplyToCommand(client,"%d,0,%s,%d,%d,%s,%s,%s,%s,%s,%d,%s,%s", i, name, bot, hp, status, throwItem, kitItem, pillItem, character, velocity, primaryWeapon, secondaryWeapon); + } + return Plugin_Handled; +} +// EVENTS // +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(g_icGamemode, sizeof(g_icGamemode)); +} +public void Event_MapTransition(Event event, const char[] name, bool dontBroadcast) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) + b_isTransitioning[i] = true; + } +} +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && b_isTransitioning[client]) { + b_isTransitioning[client] = false; + } +} +public void OnMapStart() { + //TODO: turn off when over threshold, OR fancier logic (per player) + GetCurrentMap(g_icCurrentMap, sizeof(g_icCurrentMap)); + //grab the player_manager + //int playerManager; + for (int i = MaxClients + 1; i < GetMaxEntities(); i++) { + if(Entity_ClassNameMatches(i, "_player_manager", true)) { + g_icPlayerManager = i; + break; + } + } + if(g_icPlayerManager == -1) { + SetFailState("Unable to find \"*_player_manager\" entity"); + } + #if debug + SDKHook(g_icPlayerManager, SDKHook_ThinkPost, PlayerManager_OnThinkPost); + #endif +} +public void Event_DifficultyChanged(Event event, const char[] name, bool dontBroadcast) { + event.GetString("newDifficulty",g_icDifficulty,sizeof(g_icDifficulty)); +} +public void Event_HealStart(Event event, const char[] name, bool dontBroadcast) { + int healer = GetClientOfUserId(event.GetInt("userid")); + int healing = GetClientOfUserId(event.GetInt("subject")); + g_icHealing[healer] = true; + g_icBeingHealed[healing] = true; +} +public void Event_HealStop(Event event, const char[] name, bool dontBroadcast) { + int healer = GetClientOfUserId(event.GetInt("userid")); + int healing = GetClientOfUserId(event.GetInt("subject")); + g_icHealing[healer] = false; + g_icBeingHealed[healing] = false; +} +#if debug +int g_ichuddelay = 0; +public PlayerManager_OnThinkPost(int playerManager) { + if(g_ichuddelay == 0) { + int missionDuration = GetEntProp(playerManager, Prop_Send, "m_missionDuration", 1); + int tempoState = GetEntProp(playerManager, Prop_Send, "m_tempoState", 1); + PrintHintTextToAll("temp: %d | duration: %d", tempoState, missionDuration); + } + if (++g_ichuddelay >= 10) g_ichuddelay = 0; +} +#endif +// METHODS // +stock float GetPlayerSpeed(int client) { + int iVelocity = FindSendPropInfo("CTerrorPlayer", "m_vecVelocity[0]"); + float velocity[3]; + GetEntDataVector(client, iVelocity, velocity); + return GetVectorLength(velocity, false); + /*float x = GetEntPropFloat(client, Prop_Send, "m_vecVelocity[0]", 0); + float y = GetEntPropFloat(client, Prop_Send, "m_vecVelocity", 1); + float z = GetEntPropFloat(client, Prop_Send, "m_vecVelocity", 2); + + return SquareRoot(x * x + y * y + z * z); + //eturn GetVectorLength(vector, false);*/ +} +stock void GetModelName(int client, char[] buffer, int length) { + char modelName[38]; + GetClientModel(client, modelName, sizeof(modelName)); + if(StrContains(modelName,"biker",false) > -1) { + strcopy(buffer, length, "Francis"); + }else if(StrContains(modelName,"teenangst",false) > -1) { + strcopy(buffer, length, "Zoey"); + }else if(StrContains(modelName,"namvet",false) > -1) { + strcopy(buffer, length, "Bill"); + }else if(StrContains(modelName,"manager",false) > -1) { + strcopy(buffer, length, "Louis"); + }else if(StrContains(modelName,"coach",false) > -1) { + strcopy(buffer, length, "Coach"); + }else if(StrContains(modelName,"producer",false) > -1) { + strcopy(buffer, length, "Rochelle"); + }else if(StrContains(modelName,"gambler",false) > -1) { + strcopy(buffer, length, "Nick"); + }else if(StrContains(modelName,"mechanic",false) > -1) { + strcopy(buffer, length, "Ellis"); + } +} +stock bool Entity_ClassNameMatches(entity, const char[] className, partialMatch=false) +{ + char entity_className[64]; + Entity_GetClassName(entity, entity_className, sizeof(entity_className)); + + if (partialMatch) { + return (StrContains(entity_className, className) != -1); + } + + return StrEqual(entity_className, className); +} +stock Entity_GetClassName(entity, char[] buffer, size) +{ + return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); +} + +stock GetClientRealHealth(client) +{ + //First filter -> Must be a valid client, successfully in-game and not an spectator (The dont have health). + if(!client + || !IsValidEntity(client) + || !IsClientInGame(client) + || !IsPlayerAlive(client) + || IsClientObserver(client)) + { + return -1; + } + + //If the client is not on the survivors team, then just return the normal client health. + if(GetClientTeam(client) != 2) + { + return GetClientHealth(client); + } + + //First, we get the amount of temporal health the client has + float buffer = GetEntPropFloat(client, Prop_Send, "m_healthBuffer"); + + //We declare the permanent and temporal health variables + float TempHealth; + int PermHealth = GetClientHealth(client); + + //In case the buffer is 0 or less, we set the temporal health as 0, because the client has not used any pills or adrenaline yet + if(buffer <= 0.0) + { + TempHealth = 0.0; + } + + //In case it is higher than 0, we proceed to calculate the temporl health + else + { + //This is the difference between the time we used the temporal item, and the current time + float difference = GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime"); + + //We get the decay rate from this convar (Note: Adrenaline uses this value) + float decay = GetConVarFloat(FindConVar("pain_pills_decay_rate")); + + //This is a constant we create to determine the amount of health. This is the amount of time it has to pass + //before 1 Temporal HP is consumed. + float constant = 1.0/decay; + + //Then we do the calcs + TempHealth = buffer - (difference / constant); + } + + //If the temporal health resulted less than 0, then it is just 0. + if(TempHealth < 0.0) + { + TempHealth = 0.0; + } + + //Return the value + return RoundToFloor(PermHealth + TempHealth); +} +/** +* Get the classname of an item in a slot +* +* @param client The client to check inventory from +* @param slot The item slot index +* @param buffer The char[] buffer to set text to +* @param bufferSize The size of the buffer +* @return True if item, false if no item +*/ +stock bool GetItemSlotClassName(int client, int slot, char[] buffer, int bufferSize, bool excludeWpnPrefix = false) { + int item = GetPlayerWeaponSlot(client, slot); + if(item > -1) { + GetEdictClassname(item, buffer, bufferSize); + if(excludeWpnPrefix) { + ReplaceString(buffer, bufferSize, "weapon_", ""); + } + return true; + }else{ + return false; + } +} \ No newline at end of file diff --git a/scripting/l4d2-manual-director.sp b/scripting/l4d2-manual-director.sp new file mode 100644 index 0000000..31c49ac --- /dev/null +++ b/scripting/l4d2-manual-director.sp @@ -0,0 +1,294 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG + +#define PLUGIN_NAME "L4D2 Manual Director" +#define PLUGIN_DESCRIPTION "Tell the director to spawn specials manually, even bypassing limits" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.2" + +#include +#include + +ConVar g_cMdEnableTank, g_cMdEnableWitch, g_cMdEnableMob, g_cMdAnnounceLevel; +bool g_bMdIsL4D2 = false; +char g_cmd[16]; + +char SPECIAL_IDS[6][] = { + "jockey", + "smoker", + "boomer", + "hunter", + "charger", + "spitter" +}; + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + EngineVersion test = GetEngineVersion(); + if (test != Engine_Left4Dead2 && test != Engine_Left4Dead) + { + strcopy(error, err_max, "Plugin only supports Left 4 Dead [2]."); + return APLRes_SilentFailure; + } + if (test == Engine_Left4Dead2) { + g_bMdIsL4D2 = true; + g_cmd = "z_spawn_old"; + } else { + g_cmd = "z_spawn"; + } + return APLRes_Success; +} + +public void OnPluginStart() +{ + CreateConVar("manual_director_version", PLUGIN_VERSION, "Manual Director Version", FCVAR_SPONLY | FCVAR_DONTRECORD); + CreateConVar("mandirector_version", PLUGIN_VERSION, "Manual Director Version", FCVAR_SPONLY | FCVAR_DONTRECORD); + + g_cMdAnnounceLevel = CreateConVar("mandirector_announce_level", "0", "Announcement types. 0 - None, 1 - Only bosses, 2 - Only specials+, 3 - Everything", FCVAR_NONE, true, 0.0, true, 3.0); + g_cMdEnableTank = CreateConVar("mandirector_enable_tank", "1", "Should tanks be allowed to be spawned?", FCVAR_NONE, true, 0.0, true, 1.0); + g_cMdEnableWitch = CreateConVar("mandirector_enable_witch", "1", "Should witches be allowed to be spawned?", FCVAR_NONE, true, 0.0, true, 1.0); + g_cMdEnableMob = CreateConVar("mandirector_enable_mob", "1", "Should mobs be allowed to be spawned?", FCVAR_NONE, true, 0.0, true, 1.0); + + + RegAdminCmd("sm_spawnspecial", Command_SpawnSpecial, ADMFLAG_CHEATS, "Spawn a special via director"); + RegAdminCmd("sm_forcespecial", Command_SpawnSpecialForce, ADMFLAG_CHEATS, "Force spawn a special via director, bypassing spawn limits"); + RegAdminCmd("sm_forcecursor", Command_SpawnSpecialForceLocal, ADMFLAG_CHEATS, "Force spawn a special at cursor, bypassing spawn limits"); + RegAdminCmd("sm_cursormenu", ShowLocalSpecialMenu, ADMFLAG_CHEATS, "Show the spawn menu for cursor spawning"); + RegAdminCmd("sm_specialmenu", ShowSpecialMenu, ADMFLAG_CHEATS, "Show the spawn menu for director spawning"); + RegAdminCmd("sm_directormenu", ShowSpecialMenu, ADMFLAG_CHEATS, "Show the director main menu"); + PrintToServer("Manual Director V"...PLUGIN_VERSION..." is now loaded."); + AutoExecConfig(true, "l4d2_manual_director"); +} + +Action Command_SpawnSpecial(int client, int args) { + char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + int amount = StringToInt(arg2); + if(amount == 0) amount = 1; + int executioner = GetAnyValidClient(); + if (args < 1) { + ReplyToCommand(client, "[SM] Usage: sm_spawnspecial [amount] - Requests a special to spawn via director", arg1); + } else { + if(amount <= 0 || amount > MaxClients && !StrEqual(arg1, "common")) { + ReplyToCommand(client, "[SM] Amount specified is out of range of 1 to %d", MaxClients); + }else if (executioner <= 0) { + ReplyToCommand(client, "[SM] Cannot spawn a %s as there are no players online.", arg1); + } else { + if (StrEqual(arg1, "mob", false) && !g_cMdEnableMob.BoolValue) { + ReplyToCommand(client, "[SM] Spawning mobs has been disabled."); + } else if (StrEqual(arg1, "witch", false) && !g_cMdEnableWitch.BoolValue) { + ReplyToCommand(client, "[SM] Spawning witches has been disabled."); + } else if (StrEqual(arg1, "tank", false) && !g_cMdEnableTank.BoolValue) { + ReplyToCommand(client, "[SM] Spawning tanks has been disabled."); + } else { + SpawnX(executioner, arg1, amount, "auto"); + AnnounceSpawn(arg1); + LogAction(client, -1, "\"%L\" spawned %dx \"%s\"", client, amount, arg1); + ShowActivity(client, "spawned %dx \"%s\"", amount, arg1); + } + } + } + return Plugin_Handled; +} +Action Command_SpawnSpecialForceLocal(int client, int args) { + if(client == 0) { + ReplyToCommand(client, "[SM] This command can only be used as a player."); + return Plugin_Handled; + } + char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + int amount = StringToInt(arg2); + if(amount == 0) amount = 1; + if (args < 1) { + ReplyToCommand(client, "[SM] Usage: sm_forcecursor [amount] - Requests a special to spawn at cursor", arg1); + } else if(amount <= 0 || amount > MaxClients && !StrEqual(arg1, "common")) { + ReplyToCommand(client, "[SM] Amount specified is out of range of 1 to %d", MaxClients); + }else { + SpawnX(client, arg1, amount); + AnnounceSpawn(arg1); + LogAction(client, -1, "\"%L\" spawned %dx \"%s\" at cursor", client, amount, arg1); + ShowActivity(client, "spawned %dx \"%s\" at cursor", amount, arg1); + } + return Plugin_Continue; +} + +Action Command_SpawnSpecialForce(int client, int args) { + char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + int amount = StringToInt(arg2); + if(amount == 0) amount = 1; + int executioner = GetAnyValidClient(); + if (args < 1) { + ReplyToCommand(client, "[SM] Usage: sm_forcespecial - Requests a special to spawn via director", arg1); + } else if (executioner <= 0) { + ReplyToCommand(client, "[SM] Cannot spawn a %s as there are no players online.", arg1); + } else if(amount <= 0 || amount > MaxClients && !StrEqual(arg1, "common")) { + ReplyToCommand(client, "[SM] Amount specified is out of range of 1 to %d", MaxClients); + }else { + SpawnX(executioner, arg1, amount, "auto"); + AnnounceSpawn(arg1); + LogAction(client, -1, "\"%L\" force spawned %dx \"%s\"", client, amount, arg1); + ShowActivity(client, "force spawned %dx \"%s\"", amount, arg1); + } + return Plugin_Handled; +} +Action ShowSpecialMenu(int client, int args) { + + Menu menu = new Menu(Handle_SpawnMenu); + menu.SetTitle("Manual Director - Auto"); + menu.AddItem("random", "Random Special"); + if (g_bMdIsL4D2) { + menu.AddItem("jockey", "Jockey"); + menu.AddItem("charger", "Charger"); + menu.AddItem("spitter", "Spitter"); + } + menu.AddItem("hunter", "Hunter"); + menu.AddItem("smoker", "Smoker"); + menu.AddItem("boomer", "Boomer"); + if (g_cMdEnableWitch.BoolValue)menu.AddItem("witch", "Witch"); + if (g_cMdEnableTank.BoolValue)menu.AddItem("tank", "Tank"); + if (g_cMdEnableMob.BoolValue)menu.AddItem("mob", "Mob"); + menu.ExitButton = true; + menu.Display(client, 0); + return Plugin_Handled; +} +Action ShowLocalSpecialMenu(int client, int args) { + Menu menu = new Menu(Handle_LocalSpawnMenu); + menu.SetTitle("Manual Director - Cursor"); + menu.AddItem("random", "Random Special"); + menu.AddItem("common", "Single Common"); + + if (g_bMdIsL4D2) { + menu.AddItem("jockey", "Jockey"); + menu.AddItem("charger", "Charger"); + menu.AddItem("spitter", "Spitter"); + } + + menu.AddItem("hunter", "Hunter"); + menu.AddItem("smoker", "Smoker"); + menu.AddItem("boomer", "Boomer"); + if (g_cMdEnableWitch.BoolValue) menu.AddItem("witch", "Witch"); + if (g_cMdEnableTank.BoolValue) menu.AddItem("tank", "Tank"); + if (g_cMdEnableMob.BoolValue) menu.AddItem("mob", "Mob"); + menu.ExitButton = true; + menu.Display(client, 0); + return Plugin_Handled; +} + +public int Handle_SpawnMenu(Menu menu, MenuAction action, int client, int index) +{ + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) + { + char info[32]; + menu.GetItem(index, info, sizeof(info)); + FakeClientCommand(client, "sm_forcespecial %s", info); + ShowSpecialMenu(client, 0); + //PrintToConsole(param1, "You selected item: %d (found? %d info: %s)", index, found, info); + } + /* If the menu has ended, destroy it */ + else if (action == MenuAction_End) + { + delete menu; + } + return 0; +} +public int Handle_LocalSpawnMenu(Menu menu, MenuAction action, int client, int index) +{ + if (action == MenuAction_Select) + { + char info[32]; + menu.GetItem(index, info, sizeof(info)); + FakeClientCommand(client, "sm_forcecursor %s", info); + ShowLocalSpecialMenu(client, 0); + } + else if (action == MenuAction_End) + { + delete menu; + } + return 0; +} + +stock Action kickbot(Handle timer, int client) { + if (IsClientInGame(client) && (!IsClientInKickQueue(client))) + { + if (IsFakeClient(client))KickClient(client); + } + return Plugin_Handled; +} + +stock int GetAnyValidClient() { + for (int i = 1; i <= MaxClients; i++) { + if (IsClientInGame(i) && !IsFakeClient(i)) { + return i; + } + } + return -1; +} + +stock void CheatCommand(int client, const char[] command, const char[] argument1, const char[] argument2) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s %s", command, argument1, argument2); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} + +void SpawnX(int executioner, char[] spawn, int amount, char[] arg = "") { + if(StrEqual(spawn, "panic")) { + CheatCommand(executioner, "director_force_panic_event", "", ""); + return; + } + bool isCommon = StrEqual(spawn, "common", false); + bool isRandom = StrEqual(spawn, "random", false); + + int userFlags = GetUserFlagBits(executioner); + SetUserFlagBits(executioner, ADMFLAG_ROOT); + int flags = GetCommandFlags(g_cmd); + SetCommandFlags(g_cmd, flags & ~FCVAR_CHEAT); + for(int i = 0; i < amount; i++) { + if(!isCommon && !isRandom) { + int bot = CreateFakeClient("ManualDirectorBot"); + if (bot != 0) { + ChangeClientTeam(bot, 3); + CreateTimer(0.1, kickbot, bot); + } + } else if(isRandom) { + int index = GetRandomInt(0, g_bMdIsL4D2 ? 5 : 2); + strcopy(spawn, 16, SPECIAL_IDS[index]); + } + FakeClientCommand(executioner, "%s %s %s", g_cmd, spawn, arg); + } + SetCommandFlags(g_cmd, flags); + SetUserFlagBits(executioner, userFlags); +} + +void AnnounceSpawn(const char[] type) { + switch(g_cMdAnnounceLevel.IntValue) { + case 1: + if(StrEqual(type,"tank") || StrEqual(type,"witch")) { + PrintToChatAll("A %s has spawned!", type); + } + case 2: + if(!StrEqual(type,"mob") && !StrEqual(type,"common") && !StrEqual(type,"panic")) { + PrintToChatAll("A %s has spawned!", type); + } + case 3: + PrintToChatAll("A %s has spawned!", type); + } +} \ No newline at end of file diff --git a/scripting/l4d2_TKStopper.sp b/scripting/l4d2_TKStopper.sp new file mode 100644 index 0000000..72b9ed6 --- /dev/null +++ b/scripting/l4d2_TKStopper.sp @@ -0,0 +1,709 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +#include +#include +#include + +enum { + Immune_None, + Immune_TK = 1, + Immune_RFF = 2 +} + +bool lateLoaded, isFinaleEnding; + +enum struct PlayerData { + int joinTime; + int idleStartTime; + int lastFFTime; + int jumpAttempts; + + int ffCount; + int totalFFCount; + float TKDamageBuffer; + float totalDamageFF; + float autoRFFScaleFactor; + + bool isTroll; + bool underAttack; + + int immunityFlags; + + bool pendingAction; + + bool joined; +} + +PlayerData pData[MAXPLAYERS+1]; + +ConVar hForgivenessTime, hBanTime, hThreshold, hJoinTime, hTKAction, hSuicideAction, hSuicideLimit, hFFAutoScaleAmount, hFFAutoScaleForgivenessAmount, hFFAutoScaleMaxRatio, hFFAutoScaleActivateTypes; + +enum RffActTypes { + RffActType_None, + RffActType_AdminDamage = 1, + RffActType_BlastDamage = 2, + RffActType_MolotovDamage = 4, + RffActType_BlackAndWhiteDamage = 8 +} +char gamemode[64]; +bool isEnabled = true; + +public Plugin myinfo = { + name = "TK Stopper", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + CreateNative("SetImmunity", Native_SetImmunity); + CreateNative("GetImmunity", Native_GetImmunity); + if(late) { + lateLoaded = true; + } + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + hForgivenessTime = CreateConVar("l4d2_tk_forgiveness_time", "15", "The minimum amount of time to pass (in seconds) where a player's previous accumulated teamkiller-detection FF is forgiven", FCVAR_NONE, true, 0.0); + hBanTime = CreateConVar("l4d2_tk_bantime", "60", "How long in minutes should a player be banned for? 0 for permanently", FCVAR_NONE, true, 0.0); + hThreshold = CreateConVar("l4d2_tk_ban_ff_threshold", "75.0", "How much damage does a player need to do before being instantly banned", FCVAR_NONE, true, 0.0); + hJoinTime = CreateConVar("l4d2_tk_ban_join_time", "2", "Upto how many minutes should any new player's ff be disabled? Used for jump attempts detection. also", FCVAR_NONE, true, 0.0); + hTKAction = CreateConVar("l4d2_tk_action", "3", "How should the TK be punished?\n0 = No action (No message), 1 = Kick, 2 = Instant Ban, 3 = Ban on disconnect", FCVAR_NONE, true, 0.0, true, 3.0); + hSuicideAction = CreateConVar("l4d2_suicide_action", "3", "How should a suicider be punished?\n0 = No action (No message), 1 = Kick, 2 = Instant Ban, 3 = Ban on disconnect", FCVAR_NONE, true, 0.0, true, 3.0); + hSuicideLimit = CreateConVar("l4d2_suicide_limit", "1", "How many attempts does a new joined player have until action is taken for suiciding?", FCVAR_NONE, true, 0.0); + // Reverse FF Auto Scale + hFFAutoScaleAmount = CreateConVar("l4d2_tk_auto_ff_rate", "0.02", "The rate at which auto reverse-ff is scaled by.", FCVAR_NONE, true, 0.0); + hFFAutoScaleMaxRatio = CreateConVar("l4d2_tk_auto_ff_max_ratio", "5.0", "The maximum amount that the reverse ff can go. 0.0 for unlimited", FCVAR_NONE, true, 0.0); + hFFAutoScaleForgivenessAmount = CreateConVar("l4d2_tk_auto_ff_forgive_rate", "0.05", "This amount times amount of minutes since last ff is removed from ff rate", FCVAR_NONE, true, 0.0); + hFFAutoScaleActivateTypes = CreateConVar("l4d2_tk_auto_ff_activate_types", "6", "The types of damages to ignore. Add bits together.\n0 = Just direct fire\n1 = Damage from admins\n2 = Blast damage (pipes, grenade launchers)\n4 = Molotov/gascan/firework damage\n8 = Killing black and white players", FCVAR_NONE, true, 0.0, true, 15.0); + + ConVar hGamemode = FindConVar("mp_gamemode"); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, gamemode, gamemode); + + AutoExecConfig(true, "l4d2_tkstopper"); + + HookEvent("finale_vehicle_ready", Event_FinaleVehicleReady); + HookEvent("finale_start", Event_FinaleStart); + HookEvent("player_team", Event_PlayerDisconnect); + + HookEvent("charger_carry_start", Event_ChargerCarry); + HookEvent("charger_carry_end", Event_ChargerCarry); + + HookEvent("lunge_pounce", Event_HunterPounce); + HookEvent("pounce_end", Event_HunterPounce); + HookEvent("pounce_stopped", Event_HunterPounce); + + HookEvent("choke_start", Event_SmokerChoke); + HookEvent("choke_end", Event_SmokerChoke); + HookEvent("choke_stopped", Event_SmokerChoke); + + HookEvent("jockey_ride", Event_JockeyRide); + HookEvent("jockey_ride_end", Event_JockeyRide); + + HookEvent("player_bot_replace", Event_PlayerToBot); + HookEvent("bot_player_replace", Event_BotToPlayer); + + + RegAdminCmd("sm_ignore", Command_IgnorePlayer, ADMFLAG_KICK, "Makes a player immune for any anti trolling detection or reverse-ff for a session"); + RegAdminCmd("sm_tkinfo", Command_TKInfo, ADMFLAG_KICK, "Debug info for TKSTopper"); + RegAdminCmd("sm_review", Command_TKInfo, ADMFLAG_KICK, "Review FF info for a player"); + + if(lateLoaded) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + SDKHook(i, SDKHook_OnTakeDamage, Event_OnTakeDamage); + } + } + } + LoadTranslations("common.phrases"); +} +void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); + if(StrEqual(gamemode, "coop")) { + isEnabled = true; + } else { + isEnabled = false; + } +} +/////////////////////////////////////////////////////////////////////////////// +// Special Infected Events +/////////////////////////////////////////////////////////////////////////////// +Action Event_ChargerCarry(Event event, const char[] name, bool dontBroadcast) { + return SetUnderAttack(event, name, "charger_carry_start"); +} +Action Event_HunterPounce(Event event, const char[] name, bool dontBroadcast) { + return SetUnderAttack(event, name, "lunge_pounce"); +} +Action Event_SmokerChoke(Event event, const char[] name, bool dontBroadcast) { + return SetUnderAttack(event, name, "choke_start"); +} +Action Event_JockeyRide(Event event, const char[] name, bool dontBroadcast) { + return SetUnderAttack(event, name, "jockey_ride"); +} + +Action Timer_StopSpecialAttackImmunity(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0) { + pData[client].underAttack = false; + } + return Plugin_Continue; +} + +Action SetUnderAttack(Event event, const char[] name, const char[] checkString) { + int userid = event.GetInt("victim"); + int victim = GetClientOfUserId(userid); + if(victim) { + if(StrEqual(name, checkString)) { + pData[victim].underAttack = true; + } else { + CreateTimer(1.0, Timer_StopSpecialAttackImmunity, userid); + } + } + return Plugin_Continue; +} +/////////////////////////////////////////////////////////////////////////////// +// IDLE +/////////////////////////////////////////////////////////////////////////////// +public Action Event_BotToPlayer(Event event, const char[] name, bool dontBroadcast) { + int player = GetClientOfUserId(event.GetInt("player")); + + // ignore fake players (side product of creating bots) + if (!IsValidClient(player) || (GetClientTeam(player) != 2 && GetClientTeam(player) != 3) || IsFakeClient(player)) return Plugin_Continue; + + // If a player has been idle for over 600s (10 min), reset to them "just joined" + // Purpose: Some trolls idle till end and then attack @ escape, or "gain trust" + if(GetTime() - pData[player].idleStartTime >= 600) { + pData[player].joinTime = GetTime(); + } + return Plugin_Continue; +} +public Action Event_PlayerToBot(Event event, char[] name, bool dontBroadcast) { + int player = GetClientOfUserId(event.GetInt("player")); + pData[player].idleStartTime = GetTime(); + return Plugin_Continue; +} +/////////////////////////////////////////////////////////////////////////////// +// Misc events +/////////////////////////////////////////////////////////////////////////////// +void Event_FinaleVehicleReady(Event event, const char[] name, bool dontBroadcast) { + isFinaleEnding = true; + WarnStillMarked(); + PrintToServer("[TKStopper] Escape vehicle active, 2x rff in effect"); +} +void Event_FinaleStart(Event event, const char[] name, bool dontBroadcast) { + WarnStillMarked(); +} +public void OnMapEnd() { + isFinaleEnding = false; +} + +public void OnClientPutInServer(int client) { + pData[client].joinTime = pData[client].idleStartTime = GetTime(); + SDKHook(client, SDKHook_OnTakeDamage, Event_OnTakeDamage); +} + +public void OnClientPostAdminCheck(int client) { + if(GetUserAdmin(client) != INVALID_ADMIN_ID && !pData[client].joined) { + pData[client].joined = true; + pData[client].immunityFlags = Immune_TK; + // If no admins can do ff and they + if(~hFFAutoScaleActivateTypes.IntValue & view_as(RffActType_AdminDamage)) { + pData[client].immunityFlags |= Immune_RFF; + } + } +} + +// Called on map changes, so only reset some variables: +public void OnClientDisconnect(int client) { + pData[client].TKDamageBuffer = 0.0; + pData[client].jumpAttempts = 0; + pData[client].underAttack = false; + pData[client].ffCount = 0; +} + +// Only clear things when they fully left on their own accord: +void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + if(!event.GetBool("disconnect") || !isEnabled) return; + + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && event.GetInt("team") <= 2) { + if (pData[client].isTroll && !IsFakeClient(client)) { + BanClient(client, hBanTime.IntValue, BANFLAG_AUTO | BANFLAG_AUTHID, "Excessive FF (Auto)", "Excessive Friendly Fire", "TKStopper"); + if(hBanTime.IntValue > 0) + CPrintChatToAdmins("{olive}%N{default} has been banned for %d minutes (marked as troll). If this was a mistake, you can discard their ban from the admin panel at {yellow}https://admin.jackz.me", client, hBanTime.IntValue); + else + CPrintChatToAdmins("{olive}%N{default} has been permanently banned (marked as troll). If this was a mistake, you can discard their ban from the admin panel at {yellow}https://admin.jackz.me", client); + pData[client].isTroll = false; + } + + if(!IsFakeClient(client)) { + float minutesSinceiLastFFTime = GetLastFFMinutes(client); + float activeRate = GetActiveRate(client); + PrintToConsoleAll("[TKStopper] FF Summary for %N:", client); + PrintToConsoleAll("\t%.2f TK-FF buffer (%.2f total ff, %d freq.) | %.3f (buf %f) rFF rate | lastff %.1f min ago | %d suicide jumps", + pData[client].TKDamageBuffer, + pData[client].totalDamageFF, + pData[client].totalFFCount, + activeRate, + pData[client].autoRFFScaleFactor, + minutesSinceiLastFFTime, + pData[client].jumpAttempts + ); + } + + pData[client].autoRFFScaleFactor = 0.0; + pData[client].totalDamageFF = 0.0; + pData[client].ffCount = 0; + pData[client].immunityFlags = 0; + pData[client].totalFFCount = 0; + pData[client].joined = false; + } +} + +Action Event_OnTakeDamage(int victim, int& attacker, int& inflictor, float& damage, int& damagetype, int& weapon, float damageForce[3], float damagePosition[3]) { + if(isEnabled && damage > 0.0 && victim <= MaxClients && attacker <= MaxClients && attacker > 0 && victim > 0) { + if(GetClientTeam(attacker) != 2 || GetClientTeam(victim) != 2 || attacker == victim) + return Plugin_Continue; + else if(IsFakeClient(attacker) && attacker != victim) { + // Ignore damage from fire/explosives caused by bots (players who left after causing fire) + if(damagetype & DMG_BURN && hFFAutoScaleActivateTypes.IntValue & view_as(RffActType_MolotovDamage)) { + damage = 0.0; + return Plugin_Changed; + } else if((damagetype & DMG_BLAST || damagetype & DMG_BLAST_SURFACE) && hFFAutoScaleActivateTypes.IntValue & view_as(RffActType_BlastDamage)) { + damage = 0.0; + return Plugin_Changed; + } + } + bool isAdmin = GetUserAdmin(attacker) != INVALID_ADMIN_ID; + int time = GetTime(); + // If is a fall within first 2 minutes, do appropiate action + if(damagetype & DMG_FALL && attacker == victim && damage > 0.0 && time - pData[victim].joinTime <= hJoinTime.IntValue * 60) { + pData[victim].jumpAttempts++; + float pos[3]; + GetNearestPlayerPosition(victim, pos); + PrintToConsoleAdmins("%N within join time (%d min), attempted to fall"); + TeleportEntity(victim, pos, NULL_VECTOR, NULL_VECTOR); + damage = 0.0; + if(pData[victim].jumpAttempts > hSuicideLimit.IntValue) { + if(hSuicideAction.IntValue == 1) { + LogMessage("[NOTICE] Kicking %N for suicide attempts", victim, hBanTime.IntValue); + PrintChatToAdmins("[Notice] Kicking %N for suicide attempts", victim, hBanTime.IntValue); + KickClient(victim, "Troll"); + } else if(hSuicideAction.IntValue == 2) { + LogMessage("[NOTICE] Banning %N for suicide attempts for %d minutes.", victim, hBanTime.IntValue); + PrintChatToAdmins("[Notice] Banning %N for suicide attempts for %d minutes.", victim, hBanTime.IntValue); + BanClient(victim, hBanTime.IntValue, BANFLAG_AUTO | BANFLAG_AUTHID, "Suicide fall attempts", "Troll", "TKStopper"); + } else if(hSuicideAction.IntValue == 3) { + LogMessage("[NOTICE] %N will be banned for suicide attempts for %d minutes. ", victim, hBanTime.IntValue); + PrintChatToAdmins("[Notice] %N will be banned for suicide attempts for %d minutes. Use \"/ignore tk\" to make them immune.", victim, hBanTime.IntValue); + pData[victim].isTroll = true; + } + } + return Plugin_Stop; + } + // Disregard any self inflicted damage from here: + else if(attacker == victim) return Plugin_Continue; + + // Stop all damage early if already marked as troll + else if(pData[attacker].isTroll) { + SDKHooks_TakeDamage(attacker, attacker, attacker, pData[attacker].autoRFFScaleFactor * damage); + return Plugin_Stop; + } + // Otherwise if attacker is immune, is a bot, or victim is a bot, let it continue + else if(pData[attacker].immunityFlags & Immune_RFF || IsFakeClient(attacker) || IsFakeClient(victim)) return Plugin_Continue; + // If victim is black and white and rff damage isnt turned on for it, allow it: + else if(GetEntProp(victim, Prop_Send, "m_isGoingToDie") && ~hFFAutoScaleActivateTypes.IntValue & view_as(RffActType_BlackAndWhiteDamage)) { + return Plugin_Continue; + } + + //Allow friendly firing BOTS that aren't idle players: + //if(IsFakeClient(victim) && !HasEntProp(attacker, Prop_Send, "m_humanSpectatorUserID") || GetEntProp(attacker, Prop_Send, "m_humanSpectatorUserID") == 0) return Plugin_Continue; + + // Allow vanilla-damage if being attacked by special (example, charger carry) + // We don't want to track someone accidently ffing them when theres a window where you can + else if(pData[victim].underAttack) return Plugin_Continue; + + // Is damage not caused by fire or pipebombs? + bool isDamageDirect = (~damagetype & DMG_BURN) != 0; + + // Forgive player teamkill based on threshold, resetting accumlated damage + if(time - pData[attacker].lastFFTime > hForgivenessTime.IntValue) { + pData[attacker].TKDamageBuffer = 0.0; + } + + pData[attacker].TKDamageBuffer += damage; + pData[attacker].totalDamageFF += damage; + pData[attacker].totalFFCount++; + pData[attacker].ffCount++; + + // Auto reverse ff logic + if(isDamageDirect) { + // Decrease the RFF scale based on how long since their last FF and an amount + float minutesSinceiLastFFTime = (time - pData[attacker].lastFFTime) / 60.0; + pData[attacker].autoRFFScaleFactor -= minutesSinceiLastFFTime * hFFAutoScaleForgivenessAmount.FloatValue; + if(pData[attacker].autoRFFScaleFactor < 0.0) { + pData[attacker].autoRFFScaleFactor = 0.0; + } + + // Decrement any accumlated ff 'counts' + int ffCountMinutes = RoundFloat(minutesSinceiLastFFTime / 10.0); + pData[attacker].ffCount -= (ffCountMinutes * 2); + if(pData[attacker].ffCount < 0) { + pData[attacker].ffCount = 0; + } + + // Calculate a new reverse ff ratio based on scale threshold + damage dealt + # of recent friendly fires events + pData[attacker].autoRFFScaleFactor += hFFAutoScaleAmount.FloatValue * damage * (pData[attacker].ffCount*0.25); + if(pData[attacker].isTroll) { + pData[attacker].autoRFFScaleFactor *= 2; + } else if(hFFAutoScaleMaxRatio.FloatValue > 0.0 && pData[attacker].autoRFFScaleFactor > hFFAutoScaleMaxRatio.FloatValue) { + // Cap it to the max - if they aren't marked as troll + pData[attacker].autoRFFScaleFactor = hFFAutoScaleMaxRatio.FloatValue; + } + + } + + int prevFFTime = pData[attacker].lastFFTime; + pData[attacker].lastFFTime = time; + + // Check for excessive friendly fire damage in short timespan + // If not immune to TK, if over TK threshold, not when escaping, and direct damage + if(~pData[attacker].immunityFlags & Immune_TK + && pData[attacker].TKDamageBuffer > hThreshold.IntValue + && !isFinaleEnding + && isDamageDirect + && !IsFakeClient(victim) // Don't increment on bot-ff for now + ) { + float diffJoinMin = (float(GetTime()) - float(pData[attacker].joinTime)) / 60.0; + float lastFFMin = (float(GetTime()) - float(prevFFTime)) / 60.0; + LogAction(-1, attacker, "Excessive FF (%.2f HP/%.2f total) (%.2f RFF Rate) (joined %.1fm ago) (%.1fmin last FF)", + pData[attacker].TKDamageBuffer, + pData[attacker].totalDamageFF, + pData[attacker].autoRFFScaleFactor, + diffJoinMin, + lastFFMin + ); + if(!pData[attacker].pendingAction) { + if(hTKAction.IntValue == 1) { + LogMessage("[TKStopper] Kicking %N for excessive FF (%.2f HP)", attacker, pData[attacker].TKDamageBuffer); + PrintChatToAdmins("[Notice] Kicking %N for excessive FF (%.2f HP)", attacker, pData[attacker].TKDamageBuffer); + KickClient(attacker, "Excessive FF"); + } else if(hTKAction.IntValue == 2) { + LogMessage("[TKStopper] Banning %N for excessive FF (%.2f HP) for %d minutes.", attacker, pData[attacker].TKDamageBuffer, hBanTime.IntValue); + PrintChatToAdmins("[Notice] Banning %N for excessive FF (%.2f HP) for %d minutes.", attacker, pData[attacker].TKDamageBuffer, hBanTime.IntValue); + BanClient(attacker, hBanTime.IntValue, BANFLAG_AUTO | BANFLAG_AUTHID, "Excessive FF (Auto)", "Excessive Friendly Fire (Automatic)", "TKStopper"); + } else if(hTKAction.IntValue == 3) { + LogMessage("[TKStopper] %N will be banned for FF on disconnect (%.2f HP) for %d minutes. ", attacker, pData[attacker].TKDamageBuffer, hBanTime.IntValue); + CPrintChatToAdmins("[Notice] %N will be banned for %d minutes for attempted teamkilling (%.2f HP) when they disconnect. Use {olive}/ignore tk{default} to make them immune.", attacker, hBanTime.IntValue, pData[attacker].TKDamageBuffer); + pData[attacker].isTroll = true; + } + pData[attacker].pendingAction = true; + } + damage = 0.0; + return Plugin_Handled; + } + + // Modify damages based on criteria + if(pData[victim].jumpAttempts > 0 // If they've attempted suicide, we just incase, disable their ff damage + || L4D_IsInFirstCheckpoint(victim) || L4D_IsInLastCheckpoint(victim) // No FF damage in saferooms + || time - pData[attacker].joinTime <= hJoinTime.IntValue * 60 // No FF damage within first X minutes + ) { + /* + If the amount of seconds since they joined is <= the minimum join time cvar (min) threshold + or if the player is in a saferoom + or if the player tried to suicide jump + Then cancel all damage: + */ + damage = 0.0; + return Plugin_Handled; + }else if(isFinaleEnding) { + // Keep admins immune if escape vehicle out, or if victim is a bot + if(isAdmin || IsFakeClient(victim)) return Plugin_Continue; + // We ignore FF for fire/molotovs, can be accidental / non-issue + if(isDamageDirect) + SDKHooks_TakeDamage(attacker, attacker, attacker, damage * 2.0); + damage = 0.0; + return Plugin_Changed; + }else if(isDamageDirect && pData[attacker].autoRFFScaleFactor > 0.18) { // 0.18 buffer to ignore fire and propane damage, mistakes can happen + // Apply their reverse ff damage, and have victim take a decreasing amount + if(pData[attacker].isTroll) return Plugin_Stop; + + SDKHooks_TakeDamage(attacker, attacker, attacker, pData[attacker].autoRFFScaleFactor * damage); + if(pData[attacker].autoRFFScaleFactor > 1.0) + damage = 0.0; + else + damage /= 2.0; + return Plugin_Changed; + } + } + return Plugin_Continue; +} + +/// COMMANDS + +Action Command_TKInfo(int client, int args) { + int time = GetTime(); + if(!isEnabled) { + ReplyToCommand(client, "Warn: Plugin is disabled in current gamemode (%s)", gamemode); + } + if(args > 0) { + static char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + + static char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + || target_count == 0) { + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + int target = target_list[0]; + CReplyToCommand(client, "- FF Review for {olive}%N -", target); + if(pData[target].isTroll) { + CReplyToCommand(client, "{olive}- will be banned on disconnect for TK -", target); + } + if(pData[target].immunityFlags == Immune_TK) { + CReplyToCommand(client, "Immunity: {yellow}Teamkiller Detection", target); + } else if(pData[target].immunityFlags == Immune_RFF) { + CReplyToCommand(client, "Immunity: {yellow}Auto reverse-ff", target); + } else if(view_as(pData[target].immunityFlags) > 0) { + CReplyToCommand(client, "Immunity: {yellow}Teamkiller Detection, Auto reverse-ff", target); + } else { + CReplyToCommand(client, "Immunity: {yellow}None", target); + CReplyToCommand(client, "\tUse {olive}/ignore [immunity type]{default} to toggle"); + } + float minutesSinceiLastFFTime = GetLastFFMinutes(target); + float activeRate = GetActiveRate(target); + CReplyToCommand(client, "FF Frequency: {yellow}%d {default}(recent: %d, %d forgiven)", pData[target].totalFFCount, pData[target].ffCount, (pData[target].totalFFCount - pData[target].ffCount)); + if(pData[client].lastFFTime == 0) + CReplyToCommand(client, "Total FF Damage: {yellow}%.1f HP{default} (last ff Never)", pData[target].totalDamageFF); + else + CReplyToCommand(client, "Total FF Damage: {yellow}%.1f HP{default} (last ff %.1f min ago)", pData[target].totalDamageFF, minutesSinceiLastFFTime); + if(~pData[target].immunityFlags & Immune_TK) + CReplyToCommand(client, "Recent FF (TKDetectBuffer): {yellow}%.1f", pData[target].TKDamageBuffer); + if(~pData[target].immunityFlags & Immune_RFF) + CReplyToCommand(client, "Auto Reverse-FF: {yellow}%.1fx rate", activeRate); + CReplyToCommand(client, "Attempted suicide jumps: {yellow}%d", pData[target].jumpAttempts); + } else { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i)) { + float minutesSinceiLastFFTime = (time - pData[i].lastFFTime) / 60.0; + float activeRate = pData[i].autoRFFScaleFactor - (minutesSinceiLastFFTime * hFFAutoScaleForgivenessAmount.FloatValue); + if(activeRate < 0.0) { + activeRate = 0.0; + } + PrintToConsoleAll("%20N: %.1f TK-FF buf / %.2f total ff / %d freq. (intrl %d) | %.3f (buf %f) rFF rate | lastff %.1f min ago | %d suicide jumps", + i, + pData[i].TKDamageBuffer, + pData[i].totalDamageFF, + pData[i].totalFFCount, + pData[i].ffCount, + activeRate, + pData[i].autoRFFScaleFactor, + minutesSinceiLastFFTime, + pData[i].jumpAttempts + ); + } + } + } + return Plugin_Handled; +} + + +Action Command_IgnorePlayer(int client, int args) { + char arg1[32], arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + if(args < 2) { + CReplyToCommand(client, "Usage: {yellow}sm_ignore "); + return Plugin_Handled; + } + + int flags = 0; + if(StrEqual(arg2, "tk") || StrEqual(arg2, "teamkill")) { + flags = Immune_TK; + } else if(arg2[0] == 'a') { + flags = Immune_TK | Immune_RFF; + } else if(StrEqual(arg2, "reverseff") || StrEqual(arg2, "rff")) { + flags = Immune_RFF; + } else { + CReplyToCommand(client, "Usage: {yellow}sm_ignore "); + return Plugin_Handled; + } + + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS+1], target_count; + bool tn_is_ml; + + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MaxClients, + COMMAND_FILTER_NO_IMMUNITY | COMMAND_FILTER_NO_BOTS, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + /*if (GetUserAdmin(target) != INVALID_ADMIN_ID) { + ReplyToCommand(client, "%N is an admin and is already immune.", target); + return Plugin_Handled; + }*/ + + if (flags & Immune_TK) { + if (pData[target].immunityFlags & Immune_TK) { + LogAction(client, target, "\"%L\" re-enabled teamkiller detection for \"%L\"", client, target); + CShowActivity2(client, "[FTT] ", "{yellow}%N{default} has re-enabled teamkiller detection for {olive}%N", client, target); + } else { + LogAction(client, target, "\"%L\" ignored teamkiller detection for \"%L\"", client, target); + CShowActivity2(client, "[FTT] ", "{yellow}%N{default} has ignored teamkiller detection for {olive}%N", client, target); + } + pData[target].immunityFlags ^= Immune_TK; + } + + if (flags & Immune_RFF) { + if (pData[target].immunityFlags & Immune_RFF) { + LogAction(client, target, "\"%L\" re-enabled auto reverse friendly-fire for \"%L\"", client, target); + CShowActivity2(client, "[FTT] ", "{yellow}%N{default} has enabled auto reverse friendly-fire for {olive}%N", client, target); + } else { + LogAction(client, target, "\"%L\" disabled auto reverse friendly-fire for \"%L\"", client, target); + CShowActivity2(client, "[FTT] ", "{yellow}%N{default} has disabled auto reverse friendly-fire for {olive}%N", client, target); + pData[target].autoRFFScaleFactor = 0.0; + } + pData[target].immunityFlags ^= Immune_RFF; + } + + pData[target].isTroll = false; + } + return Plugin_Handled; +} + +public int Native_SetImmunity(Handle plugin, int numParams) { + int target = GetNativeCell(1); + int flag = GetNativeCell(2); + _CheckNative(target, flag); + bool value = GetNativeCell(3); + char flagName[32]; + GetImmunityFlagName(flag, flagName, sizeof(flagName)); + if(value) { + // Remove immunity + pData[target].immunityFlags &= ~flag; + LogAction(0, target, "removed immunity flag \"%s\" from \"%L\"", flagName, target); + } else { + // Add immunity + pData[target].immunityFlags |= flag; + LogAction(0, target, "added immunity flag \"%s\" to \"%L\"", flagName, target); + } + return 0; +} + +void GetImmunityFlagName(int flag, char[] buffer, int bufferLength) { + if(flag == Immune_RFF) { + strcopy(buffer, bufferLength, "Reverse Friendly-Fire"); + } else if(flag == Immune_TK) { + strcopy(buffer, bufferLength, "Teamkiller Detection"); + } else { + strcopy(buffer, bufferLength, "-error: unknown flag-"); + } +} + +public int Native_GetImmunity(Handle plugin, int numParams) { + int target = GetNativeCell(1); + int flag = GetNativeCell(2); + _CheckNative(target, flag); + return pData[target].immunityFlags & flag; +} + +void _CheckNative(int target, int flag) { + if(target <= 0 || target >= MaxClients) { + ThrowNativeError(SP_ERROR_NATIVE, "Target is out of range (1 to MaxClients)"); + } else if(flag <= 0) { + ThrowNativeError(SP_ERROR_NATIVE, "Flag is invalid"); + } +} +void WarnStillMarked() { + for(int i = 1; i <= MaxClients; i++) { + if(pData[i].isTroll && IsClientConnected(i) && IsClientInGame(i)) { + CPrintChatToAdmins("Note: {yellow}%N is still marked as troll and will be banned after this game. Use {olive}/ignore tk{default} to ignore them.", i); + } + } +} +/// STOCKS + +float GetLastFFMinutes(int client) { + return (GetTime() - pData[client].lastFFTime) / 60.0; +} + +float GetActiveRate(int client) { + float activeRate = pData[client].autoRFFScaleFactor - (GetLastFFMinutes(client) * hFFAutoScaleForgivenessAmount.FloatValue); + if(activeRate < 0.0) activeRate = 0.0; + return activeRate; +} + +stock bool GetNearestPlayerPosition(int client, float pos[3]) { + static float targetPos[3], lowestDist; + int lowestID = -1; + GetClientAbsOrigin(client, targetPos); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2 && i != client) { + GetClientAbsOrigin(i, pos); + float distance = GetVectorDistance(pos, targetPos); + if(lowestID == -1 || distance < lowestDist) { + lowestID = i; + lowestDist = distance; + } + } + } + GetClientAbsOrigin(lowestID, pos); + return lowestID > 0; +} + + +stock void PrintToConsoleAdmins(const char[] format, any ...) { + char buffer[254]; + + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToConsole(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} diff --git a/scripting/l4d2_ai_minigun.sp b/scripting/l4d2_ai_minigun.sp new file mode 100644 index 0000000..b0a47bd --- /dev/null +++ b/scripting/l4d2_ai_minigun.sp @@ -0,0 +1,307 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_NAME "l4d2 ai minigun" +#define PLUGIN_DESCRIPTION "" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +#include "jutils.inc" +#include +//#include + + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + +int g_iSurvivors[MAXPLAYERS+1], g_iLastSpawnClient, g_iAvoidChar[MAXPLAYERS+1] = {-1,...}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + + RegAdminCmd("sm_ai_holdout", Command_SpawnHoldoutBot, ADMFLAG_ROOT); + RegAdminCmd("sm_ai_minigun", Command_SpawnMinigunBot, ADMFLAG_ROOT); + RegAdminCmd("sm_ai_remove_far", Command_RemoveFar, ADMFLAG_ROOT); +} + +public void OnMapStart() { + PrecacheModel(MODEL_MINIGUN); + PrecacheModel(MODEL_LOUIS); + PrecacheModel(MODEL_ZOEY); + PrecacheModel(MODEL_BILL); + PrecacheModel(MODEL_FRANCIS); +} + +public void OnClientPutInServer(int client) { + if( g_iLastSpawnClient == -1) + { + g_iSurvivors[client] = GetClientUserId(client); + g_iLastSpawnClient = GetClientUserId(client); + } +} + +public Action Command_RemoveFar(int client, int args) { + for(int bot = 1; bot < MaxClients; bot++) { + if(IsClientConnected(bot) && IsClientInGame(bot) && GetClientTeam(bot) == 4 && IsFakeClient(bot)) { + char name[64]; + GetClientName(bot, name, sizeof(name)); + //Only work on Bot's + if(StrContains(name, "HoldoutBot", true) || StrContains(name, "MinigunBot", true)) { + float botPos[3]; + GetClientAbsOrigin(bot, botPos); + bool isClose = false; + //Loop all players, if distance is less than 750, break out of loop + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && !IsFakeClient(i)) { + float playerPos[3]; + GetClientAbsOrigin(i, playerPos); + + float distance = GetVectorDistance(playerPos, botPos); + if(distance <= 750) { + isClose = true; + break; + } + } + } + if(!isClose) { + KickClient(bot); + ReplyToCommand(client, "Removed %N", bot); + } + } + } + } +} + +public Action Command_SpawnMinigunBot(int client, int args) { + char arg1[16]; + if(args > 0) { + GetCmdArg(1, arg1, sizeof(arg1)); + char model[64]; + if(!FindSurvivorModel(arg1, model, sizeof(model))) { + LogError("Could not find a survivor model."); + ReplyToCommand(client, "Could not find that survivor."); + return Plugin_Handled; + } + + //get ground: + float vPos[3], vAng[3]; + if(!GetGround(client, vPos, vAng)) { + LogError("Failed to find ground for survivor"); + ReplyToCommand(client, "Could not find a suitable ground location to spawn survivor."); + return Plugin_Handled; + } + //make sure spawns a little above + vPos[2] += 1.0; + + int survivor = SpawnSurvivor(vPos, vAng, model, true); + if(survivor > 0) { + GiveClientWeaponLasers(survivor, "rifle_ak47"); + }else{ + ReplyToCommand(client, "Failed to spawn survivor."); + } + }else{ + ReplyToCommand(client, "Usage: sm_spawn_minigun_bot <4=Bill, 5=Zoey, 6=Francis, 7=Louis>"); + } + return Plugin_Handled; +} + +public Action Command_SpawnHoldoutBot(int client, int args) { + char arg1[16]; + if(args > 0) { + GetCmdArg(1, arg1, sizeof(arg1)); + char model[64]; + int survivorId = GetSurvivorId(arg1); + if(survivorId == -1) { + ReplyToCommand(client, "That is not a valid survivor."); + return Plugin_Handled; + } + if(!GetSurvivorModel(survivorId, model, sizeof(model))) { + LogError("Could not find a survivor model."); + ReplyToCommand(client, "Could not find that survivor."); + return Plugin_Handled; + } + //get ground: + float vPos[3], vAng[3]; + if(!GetGround(client, vPos, vAng)) { + LogError("Failed to find ground for survivor"); + ReplyToCommand(client, "Could not find a suitable ground location to spawn survivor."); + return Plugin_Handled; + } + //make sure spawns a little above + vPos[2] += 1.0; + + char wpn[64]; + if(args > 1) { + GetCmdArg(2, wpn, sizeof(wpn)); + }else { + wpn = "rifle_ak47"; + } + + int survivor = SpawnSurvivor(vPos, vAng, model, false); + if(survivor > 0) { + GiveClientWeaponLasers(survivor, wpn); + SetEntProp(survivor, Prop_Send, "m_survivorCharacter", survivorId); + }else{ + ReplyToCommand(client, "Failed to spawn survivor."); + } + }else{ + ReplyToCommand(client, "Usage: sm_spawn_minigun_bot <4=Bill, 5=Zoey, 6=Francis, 7=Louis> [weapon]"); + } + return Plugin_Handled; +} + +/////////////////////////////////////////// +// +//STOCKS +// +/////////////////////////////////////////// + +//Taken from https://forums.alliedmods.net/showthread.php?p=1741099 and modified slightly (and documented) +stock int SpawnSurvivor(const float vPos[3], const float vAng[3], const char[] model, bool spawn_minigun) { + int entity = CreateEntityByName("info_l4d1_survivor_spawn"); + if( entity == -1 ) { + LogError("Failed to create \"info_l4d1_survivor_spawn\""); + return -1; + } + //on spawn, to kill spawner + //AcceptEntityInput(entity, "AddOutput"); + DispatchKeyValue(entity, "character", "7"); + AcceptEntityInput(entity, "Kill"); + + //teleport spawner to valid spot & spawn it + TeleportEntity(entity, vPos, vAng, NULL_VECTOR); + DispatchSpawn(entity); + + //Tell spawner to spawn survivor + g_iLastSpawnClient = -1; + AvoidCharacter(7, true); + AcceptEntityInput(entity, "SpawnSurvivor"); + AvoidCharacter(7, false); + + + //remove reference to last spawn id + int bot_user_id = g_iLastSpawnClient, bot_client_id; + g_iLastSpawnClient = -1; + if( bot_user_id <= 0 || (bot_client_id = GetClientOfUserId(bot_user_id)) <= 0 ) + { + LogError("Failed to match survivor, did they not spawn? [%d/%d]", bot_user_id, bot_client_id); + return -1; + } + if(spawn_minigun && !SpawnMinigun(vPos, vAng)) { + LogError("Failed to spawn minigun for client #%d", bot_client_id); + KickClient(bot_client_id, "AIMinigun:MinigunSpawnFailure"); + return -1; + } + SetClientName(bot_client_id, spawn_minigun ? "MinigunBot" : "HoldoutBot"); + ChangeClientTeam(bot_client_id, 4); + + CreateTimer(0.1, Timer_Move, bot_user_id); + TeleportEntity(bot_client_id, vPos, NULL_VECTOR, NULL_VECTOR); + + SetEntityModel(bot_client_id, model); //set entity model to custom survivor model + CreateTimer(6.0, spawn_minigun ? Timer_MoveMinigun : Timer_Move, bot_user_id); + return bot_client_id; +} +//Taken from https://forums.alliedmods.net/showthread.php?p=1741099 +stock bool SpawnMinigun(const float vPos[3], const float vAng[3]) { + float vDir[3], newPos[3]; + GetAngleVectors(vAng, vDir, NULL_VECTOR, NULL_VECTOR); + vDir[0] = vPos[0] + (vDir[0] * 50); + vDir[1] = vPos[1] + (vDir[1] * 50); + vDir[2] = vPos[2] + 20.0; + newPos = vDir; + newPos[2] -= 40.0; + + Handle trace = TR_TraceRayFilterEx(vDir, newPos, MASK_SHOT, RayType_EndPoint, TraceFilter); + if(TR_DidHit(trace)) { + TR_GetEndPosition(vDir, trace); + + int minigun = CreateEntityByName("prop_mounted_machine_gun"); + minigun = EntIndexToEntRef(minigun); + SetEntityModel(minigun, MODEL_MINIGUN); + DispatchKeyValue(minigun, "targetname", "louis_holdout"); + DispatchKeyValueFloat(minigun, "MaxPitch", 360.00); + DispatchKeyValueFloat(minigun, "MinPitch", -360.00); + DispatchKeyValueFloat(minigun, "MaxYaw", 90.00); + newPos[2] += 0.1; + TeleportEntity(minigun, vDir, vAng, NULL_VECTOR); + DispatchSpawn(minigun); + delete trace; + return true; + }else{ + LogError("Spawn minigun trace failure"); + delete trace; + return false; + } +} +void AvoidCharacter(int type, bool avoid) { + for( int i = 1; i <= MaxClients; i++ ) + { + if( IsClientInGame(i) && (GetClientTeam(i) == 2 || GetClientTeam(i) == 4) ) + { + if( avoid ) + { + // Save character type + g_iAvoidChar[i] = GetEntProp(i, Prop_Send, "m_survivorCharacter"); + int set; + switch( type ) + { + case 4: set = 3; // Bill + case 5: set = 2; // Zoey + case 6: set = 1; // Francis + case 7: set = 0; // Louis + default: return; + } + SetEntProp(i, Prop_Send, "m_survivorCharacter", set); + } else { + // Restore player type + if( g_iAvoidChar[i] != -1 ) + { + SetEntProp(i, Prop_Send, "m_survivorCharacter", g_iAvoidChar[i]); + g_iAvoidChar[i] = -1; + } + } + } + } + + if(!avoid) { + for( int i = 1; i <= MAXPLAYERS; i++ ) + g_iAvoidChar[i] = -1; + } +} + +Action Timer_Move(Handle timer, any client) { + if((client = GetClientOfUserId(client))) { + //PrintToServer("client %d %N",client,client); + L4D2_SetPlayerSurvivorGlowState(client, false); + L4D2_RemoveEntityGlow(client); + // SetEntityMoveType(client, MOVETYPE_NONE); + SetEntProp(client, Prop_Send, "m_fFlags", GetEntProp(client, Prop_Send, "m_fFlags") & ~FL_FROZEN); + TeleportEntity(client, NULL_VECTOR, NULL_VECTOR, view_as({ 0.0, 0.0, 0.0 })); + } +} + +Action Timer_MoveMinigun(Handle timer, any client) { + if((client = GetClientOfUserId(client))) { + L4D2_RemoveEntityGlow(client); + L4D2_SetPlayerSurvivorGlowState(client, false); + SetEntityMoveType(client, MOVETYPE_NONE); + // SetEntProp(client, Prop_Send, "m_fFlags", GetEntProp(client, Prop_Send, "m_fFlags") & ~FL_FROZEN); + TeleportEntity(client, NULL_VECTOR, NULL_VECTOR, view_as({ 0.0, 0.0, 0.0 })); + } +} + diff --git a/scripting/l4d2_ai_tweaks.sp b/scripting/l4d2_ai_tweaks.sp new file mode 100644 index 0000000..4ad885d --- /dev/null +++ b/scripting/l4d2_ai_tweaks.sp @@ -0,0 +1,80 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define ALLOW_HEALING_MIN_IDLE_TIME 180 +#define MIN_IGNORE_IDLE_TIME 5 +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +//#include + +int lastIdleTimeStart[MAXPLAYERS+1]; +int idleTimeStart[MAXPLAYERS+1]; + +public Plugin myinfo = { + name = "L4D2 AI Tweaks", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + HookEvent("player_bot_replace", Event_PlayerOutOfIdle ); + HookEvent("bot_player_replace", Event_PlayerToIdle); +} + +void Event_PlayerToIdle(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + lastIdleTimeStart[client] = idleTimeStart[client]; + idleTimeStart[client] = GetTime(); + } +} +void Event_PlayerOutOfIdle(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + // After saferooms, idle players get resumed then immediately idle - so ignore that + if(GetTime() - idleTimeStart[client] < MIN_IGNORE_IDLE_TIME) { + idleTimeStart[client] = lastIdleTimeStart[client]; + } + } +} + +public void OnActionCreated( BehaviorAction action, int actor, const char[] name ) { + /* Hooking friend healing action (when bot wants to heal someone) */ + if ( strcmp(name, "SurvivorHealFriend") == 0 ) { + action.OnStartPost = OnFriendAction; + } +} + + +public Action OnFriendAction( BehaviorAction action, int actor, BehaviorAction priorAction, ActionResult result ) { + // Do not allow idle bots to heal another player, unless they are black and white. + // Do not let idle bots heal non-idle bots + int target = action.Get(0x34) & 0xFFF; + int realPlayer = GetClientOfUserId(GetEntProp(actor, Prop_Send, "m_humanSpectatorUserID")); + if(realPlayer > 0) { // If idle bot + if(IsFakeClient(target)) { + // If target is a bot, not idle player, ignore + if(GetEntProp(target, Prop_Send, "m_humanSpectatorUserID") == 0) { + result.type = DONE; + return Plugin_Handled; + } + } + // If they are not black and white, also stop + if(!GetEntProp(target, Prop_Send, "m_bIsOnThirdStrike") && idleTimeStart[realPlayer] < ALLOW_HEALING_MIN_IDLE_TIME) { //If real player and not black and white, stop + result.type = DONE; + return Plugin_Handled; + } + } + return Plugin_Continue; +} \ No newline at end of file diff --git a/scripting/l4d2_autobotcrown.sp b/scripting/l4d2_autobotcrown.sp new file mode 100644 index 0000000..f30ed5f --- /dev/null +++ b/scripting/l4d2_autobotcrown.sp @@ -0,0 +1,343 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define PLUGIN_VERSION "1.0" + +//#define DEBUG 0 + +#define SCAN_INTERVAL 4.0 +#define SCAN_RANGE 570.0 +#define ACTIVE_INTERVAL 0.4 + +#include +#include +#include +#include "jutils.inc" + +public Plugin myinfo = +{ + name = "L4D2 Auto Bot Witch Crown", + author = "jackzmc", + description = "Makes bots automatically crown a witch in cases where a witch is blocking the way", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +//TODO: convars for allowed gamemodes / difficulties + + +static ArrayList WitchList; +static Handle timer = INVALID_HANDLE; +static bool lateLoaded = false, AutoCrownInPosition = false; +static int AutoCrownBot = -1, AutoCrownTarget, currentDifficulty, PathfindTries = 0; +static float CrownPos[3], CrownAng[3]; +static ConVar hValidDifficulties, hAllowedGamemodes; + +float TRACE_MIN_SIZE[3] = {0.0, 0.0, 0.0}, TRACE_MAX_SIZE[3] = {1.0, 1.0, 1.0}; + + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + if(late) lateLoaded = true; +} + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + WitchList = new ArrayList(1, 0); + if(lateLoaded) { + char classname[8]; + for(int i = MaxClients; i < 2048; i++) { + if(IsValidEntity(i)) { + GetEntityClassname(i, classname, sizeof(classname)); + if(StrEqual(classname, "witch", false)) { + if(HasEntProp(i, Prop_Send, "m_rage")) { + WitchList.Push(EntIndexToEntRef(i)); + #if defined DEBUG + PrintToServer("Found pre-existing witch %d", i); + #endif + } + + } + } + } + if(timer == INVALID_HANDLE && WitchList.Length > 0) { + timer = CreateTimer(SCAN_INTERVAL, Timer_Scan, _, TIMER_REPEAT); + } + } + + hValidDifficulties = CreateConVar("l4d2_autocrown_allowed_difficulty", "7", "The difficulties the plugin is active on. 1=Easy, 2=Normal 4=Advanced 8=Expert. Add numbers together.", FCVAR_NONE); + hAllowedGamemodes = CreateConVar("l4d2_autocrown_modes_tog", "1", "Turn on the plugin in these game modes. 0=All, 1=Coop, 2=Survival, 4=Versus, 8=Scavenge, 16=Other. Add numbers together.", FCVAR_NONE); + + char diff[16]; + FindConVar("z_difficulty").GetString(diff, sizeof(diff)); + currentDifficulty = GetDifficultyInt(diff); + + FindConVar("mp_gamemode").AddChangeHook(Change_Gamemode); + + AutoExecConfig(true, "l4d2_autobotcrown"); + + HookEvent("witch_spawn", Event_WitchSpawn); + HookEvent("witch_killed", Event_WitchKilled); + HookEvent("difficulty_changed", Event_DifficultyChanged); + + RegAdminCmd("sm_ws", Cmd_Status, ADMFLAG_ROOT); + + #if defined DEBUG + CreateTimer(0.6, Timer_Debug, _, TIMER_REPEAT); + #endif +} + +#if defined DEBUG +public Action Timer_Debug(Handle timer) { + PrintHintTextToAll("Scan Timer: %b | Active: %b | In Position %b | Witches %d | Bot %N", timer != INVALID_HANDLE, AutoCrownBot > -1, AutoCrownInPosition, WitchList.Length, GetClientOfUserId(AutoCrownBot)); + return Plugin_Continue; +} +#endif + + +public Action Cmd_Status(int client, int args) { + ReplyToCommand(client, "Scan Timer: %b | Active: %b | In Position %b | Witches %d | Bot %N", timer != INVALID_HANDLE, AutoCrownBot > -1, AutoCrownInPosition, WitchList.Length, GetClientOfUserId(AutoCrownBot)); + return Plugin_Handled; +} +public void Event_DifficultyChanged(Event event, const char[] name, bool dontBroadcast) { + char diff[16]; + event.GetString("newDifficulty", diff, sizeof(diff)); + currentDifficulty = GetDifficultyInt(diff); + if(hValidDifficulties.IntValue & currentDifficulty > 0) { + if(timer == INVALID_HANDLE && AutoCrownBot == -1) { + timer = CreateTimer(SCAN_INTERVAL, Timer_Scan, _, TIMER_REPEAT); + } + }else{ + delete timer; + } +} +public void Change_Gamemode(ConVar convar, const char[] oldValue, const char[] newValue) { + int c0 = CharToLower(newValue[0]); + int c1 = CharToLower(newValue[1]); + bool enable = false; + if(c0 == 'c' && hAllowedGamemodes.IntValue & 1) { //co-op + enable = true; + } else if(c0 == 's' && c1 == 'u' && hAllowedGamemodes.IntValue & 2) { //survival + enable = true; + } else if(c0 == 'v' && hAllowedGamemodes.IntValue & 4) { //versus + enable = true; + } else if(c0 == 's' && c1 == 'c' && hAllowedGamemodes.IntValue & 8) { //scavenge + enable = true; + } else if(hAllowedGamemodes.IntValue & 16) + enable = true; + + if(enable) { + if(timer == INVALID_HANDLE && AutoCrownBot == -1) { + timer = CreateTimer(SCAN_INTERVAL, Timer_Scan, _, TIMER_REPEAT); + } + } else delete timer; + +} + +public void Event_WitchSpawn(Event event, const char[] name, bool dontBroadcast) { + int witchID = event.GetInt("witchid"); + if(HasEntProp(witchID, Prop_Send, "m_rage")) { + WitchList.Push(EntIndexToEntRef(witchID)); + #if defined DEBUG + PrintToServer("Witch spawned: %d", witchID); + #endif + //If not currently scanning, begin scanning ONLY if not active + if(timer == INVALID_HANDLE && AutoCrownBot == -1) { + timer = CreateTimer(SCAN_INTERVAL, Timer_Scan, _, TIMER_REPEAT); + } + } +} + +public void Event_WitchKilled(Event event, const char[] name, bool dontBroadcast) { + int witchRef = EntIndexToEntRef(event.GetInt("witchid")); + int index = WitchList.FindValue(witchRef); + if(index > -1) { + WitchList.Erase(index); + } + //If witch that was killed, terminate active loop + if(AutoCrownTarget == witchRef) { + ResetAutoCrown(); + #if defined DEBUG + PrintToServer("AutoCrownTarget has died"); + #endif + } +} +public Action Timer_Active(Handle hdl) { + float botPosition[3], witchPos[3]; + if(WitchList.Length == 0) { + #if defined DEBUG + PrintToServer("No witches detected, ending timer"); + #endif + return Plugin_Stop; + } + //TODO: Also check if startled and cancel it immediately. + if(AutoCrownBot == -1) { + timer = CreateTimer(SCAN_INTERVAL, Timer_Scan, _, TIMER_REPEAT); + return Plugin_Stop; + } + + int client = GetClientOfUserId(AutoCrownBot); + int crownTarget = EntRefToEntIndex(AutoCrownTarget); + if(crownTarget == INVALID_ENT_REFERENCE) { + ResetAutoCrown(); + + #if defined DEBUG + PrintToServer("Could not find valid AutoCrownTarget"); + #endif + return Plugin_Stop; + }else if(client <= 0 || !IsPlayerAlive(client)) { + ResetAutoCrown(); + #if defined DEBUG + PrintToServer("Could not find valid AutoCrownBot"); + #endif + return Plugin_Stop; + } + + char wpn[32]; + if(!GetClientWeapon(client, wpn, sizeof(wpn)) || !StrEqual(wpn, "weapon_autoshotgun") && !StrEqual(wpn, "weapon_shotgun_spas")) { + ResetAutoCrown(); + #if defined DEBUG + PrintToServer("AutoCrownBot does not have a valid weapon (%s)", wpn); + #endif + return Plugin_Stop; + } + + GetEntPropVector(crownTarget, Prop_Send, "m_vecOrigin", witchPos); + GetClientAbsOrigin(client, botPosition); + + float distance = GetVectorDistance(botPosition, witchPos, true); + if(distance <= 3600) { + float botAngles[3]; + GetClientAbsAngles(client, botAngles); + botAngles[0] = 60.0; + botAngles[1] = RadToDeg(ArcTangent2(botPosition[1] - witchPos[1], botPosition[0] - witchPos[0])) + 180.0; + //Is In Position + + ClientCommand(client, "slot0"); + TeleportEntity(client, NULL_VECTOR, botAngles, NULL_VECTOR); + AutoCrownInPosition = true; + } else { + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", AutoCrownBot, witchPos[0], witchPos[1], witchPos[2]); + PathfindTries++; + } + + if(PathfindTries > 40) { + ResetAutoCrown(); + int index = WitchList.FindValue(AutoCrownTarget); + if(index > -1) + WitchList.Erase(index); + //remove witch + #if defined DEBUG + PrintToServer("Could not pathfind to witch in time."); + #endif + } + return Plugin_Continue; +} +public Action Timer_Scan(Handle hdl) { + float botPosition[3], witchPos[3]; + if(WitchList.Length == 0) { + #if defined DEBUG + PrintToServer("No witches detected, ending timer"); + #endif + timer = INVALID_HANDLE; + return Plugin_Stop; + } + for(int bot = 1; bot <= MaxClients; bot++) { + if(IsClientConnected(bot) && IsClientInGame(bot) && IsFakeClient(bot) && IsPlayerAlive(bot)) { + //Check if bot has a valid shotgun, with ammo (probably can skip: bot mostly will be full). + if(GetClientHealth(bot) > 40) { + char wpn[32]; + if(GetClientWeapon(bot, wpn, sizeof(wpn)) && (StrEqual(wpn, "weapon_autoshotgun") || StrEqual(wpn, "weapon_shotgun_spas"))) { + GetClientAbsOrigin(bot, botPosition); + + //Loop all witches, find any valid nearby witches: + for(int i = 0; i < WitchList.Length; i++) { + int witchRef = WitchList.Get(i); + int witchID = EntRefToEntIndex(witchRef); + if(witchID == INVALID_ENT_REFERENCE) { + WitchList.Erase(i); + continue; + } + if(GetEntPropFloat(witchID, Prop_Send, "m_rage") <= 0.4) { + GetEntPropVector(witchID, Prop_Send, "m_vecOrigin", witchPos); + if(GetVectorDistance(botPosition, witchPos) <= SCAN_RANGE) { + //GetEntPropVector(witchID, Prop_Send, "m_angRotation", witchAng); + #if defined DEBUG + PrintToServer("Found a valid witch in range of %N: %d", bot, witchID); + PrintToChatAll("Found a valid witch in range of %N: %d", bot, witchID); + #endif + + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", GetClientUserId(bot), witchPos[0], witchPos[1], witchPos[2]); + AutoCrownTarget = witchRef; + AutoCrownBot = GetClientUserId(bot); + AutoCrownInPosition = false; + CreateTimer(ACTIVE_INTERVAL, Timer_Active, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + timer = INVALID_HANDLE; + return Plugin_Stop; + } + } + } + } + } + } + } + return Plugin_Continue; +} + +public Action Timer_StopFiring(Handle hdl) { + ResetAutoCrown(); + return Plugin_Handled; +} + +public Action OnPlayerRunCmd(int client, int& buttons, int& impulse, float vel[3], float angles[3], int& weapon, int& subtype, int& cmdnum, int& tickcount, int& seed, int mouse[2]) { + if(AutoCrownInPosition && GetClientOfUserId(AutoCrownBot) == client && !(buttons & IN_ATTACK)) { + buttons |= IN_ATTACK; + return Plugin_Changed; + } + return Plugin_Continue; +} + +public void ResetAutoCrown() { + AutoCrownTarget = INVALID_ENT_REFERENCE; + AutoCrownInPosition = false; + if(AutoCrownBot > -1) + L4D2_RunScript("CommandABot({cmd=3,bot=GetPlayerFromUserID(%i)})", AutoCrownBot); + AutoCrownBot = -1; + PathfindTries = 0; + if(timer != INVALID_HANDLE) { + CloseHandle(timer); + timer = INVALID_HANDLE; + } +} + +public void OnMapStart() { + WitchList.Clear(); + ResetAutoCrown(); +} +public void OnMapEnd() { + if(timer != INVALID_HANDLE) { + CloseHandle(timer); + timer = INVALID_HANDLE; + } + WitchList.Clear(); +} + +int GetDifficultyInt(const char[] type) { + if(StrEqual(type, "impossible")) { + return 8; + }else if(StrEqual(type, "hard")) { + return 4; + }else if(StrEqual(type, "normal")) { + return 2; + }else{ + return 1; + } +} + +stock bool IsPlayerIncapped(int client) { + return GetEntProp(client, Prop_Send, "m_isIncapacitated") == 1; +} \ No newline at end of file diff --git a/scripting/l4d2_autorestart.sp b/scripting/l4d2_autorestart.sp new file mode 100644 index 0000000..603e011 --- /dev/null +++ b/scripting/l4d2_autorestart.sp @@ -0,0 +1,124 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define MAX_TIME_ONLINE_SECONDS 172800 +//604800 + +#include +#include +//#include +int startupTime, triesBots, triesEmpty; +bool pendingRestart; + +public Plugin myinfo = { + name = "L4D2 Autorestart", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +ConVar cvar_hibernateWhenEmpty; + +public void OnPluginStart() { + startupTime = GetTime(); + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + cvar_hibernateWhenEmpty = FindConVar("sv_hibernate_when_empty"); + + RegAdminCmd("sm_request_restart", Command_RequestRestart, ADMFLAG_GENERIC); + RegAdminCmd("sm_ar_status", Command_Status, ADMFLAG_GENERIC); + + CreateTimer(780.0, Timer_Check, _, TIMER_REPEAT); +} + +Action Command_Status(int client, int args) { + char buffer[100]; + FormatTime(buffer, sizeof(buffer), "%F at %I:%M %p", startupTime); + ReplyToCommand(client, "Started: %s", buffer); + int diff = GetTime() - startupTime; + int exceedRestart = diff - MAX_TIME_ONLINE_SECONDS; + int exceedRestartMin = exceedRestart / 60; + int exceedRestartHour = exceedRestartMin / 60; + ReplyToCommand(client, "Overdue restart time: %d hr / %d min / %d s", exceedRestartHour, exceedRestartMin, exceedRestart); + ReplyToCommand(client, "triesBots = %d\ttriesEmpty = %d / %d", triesBots, triesEmpty, 4); + return Plugin_Handled; +} + +Action Command_RequestRestart(int client, int args) { + if(IsServerEmpty()) { + ReplyToCommand(client, "Restarting..."); + LogAction(client, -1, "requested to restart server if empty."); + ServerCommand("quit"); + } else { + ReplyToCommand(client, "Players are online."); + } + return Plugin_Handled; +} + +public Action Timer_Check(Handle h) { + if(IsServerEmptyWithOnlyBots()) { + if(++triesBots > 0) { + //Server is stuck in non-hibernation with only bots, quit + LogAction(0, -1, "Detected server in hibernation with no players, restarting..."); + ServerCommand("quit"); + } + return Plugin_Continue; + } else if(pendingRestart || GetTime() - startupTime > MAX_TIME_ONLINE_SECONDS) { + LogAction(0, -1, "Server has passed max online time threshold, will restart if remains empty (chk%d)", triesEmpty); + pendingRestart = true; + cvar_hibernateWhenEmpty.BoolValue = false; + if(IsServerEmpty()) { + if(++triesEmpty >= 4) { + LogAction(0, -1, "Server has passed max online time threshold and is empty after %d tries, restarting now", triesEmpty); + ServerCommand("quit"); + } + return Plugin_Continue; + } + // If server is occupied, falls down below and resets: + } + triesBots = 0; + triesEmpty = 0; + return Plugin_Continue; +} + +public void OnConfigsExecuted() { + // Reset no hibernate setting when level changes: + if(pendingRestart) { + cvar_hibernateWhenEmpty.BoolValue = false; + } +} + +// Returns true if server is empty, and there is only bots. No players +bool IsServerEmptyWithOnlyBots() { + bool hasBot; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(IsFakeClient(i)) + //Has a bot, but there could be other players. + hasBot = true; + else + //Is player, not empty. + return false; + + } + } + return hasBot; +} + +//Returns true if there is a bot connected and there is no real players +bool IsServerEmpty() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i)) { + return false; + } + } + return true; +} diff --git a/scripting/l4d2_avoid_minigun.sp b/scripting/l4d2_avoid_minigun.sp new file mode 100644 index 0000000..af02e96 --- /dev/null +++ b/scripting/l4d2_avoid_minigun.sp @@ -0,0 +1,111 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_NAME "L4D2 AI Avoid Minigun" +#define PLUGIN_DESCRIPTION "Makes the ai avoid being infront of a minigun in use" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +#include "jutils.inc" + +//#include + +static bool bIsSurvivorClient[MAXPLAYERS+1]; + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + CreateTimer(5.0, CheckTimer, _, TIMER_REPEAT); + HookEvent("player_team", Event_PlayerTeamSwitch); +} + +public void OnMapStart() { + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + bIsSurvivorClient[i] = true; + } + } +} + +public void OnClientPutInGame(int client) { + if(IsClientInGame(client) && GetClientTeam(client) == 2) { + bIsSurvivorClient[client] = true; + } +} + +public void OnClientDisconnect(int client) { + bIsSurvivorClient[client] = false; +} + +public void Event_PlayerTeamSwitch(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int team = event.GetInt("team"); + if(team == 2) { + bIsSurvivorClient[client] = true; + }else if(bIsSurvivorClient[client]) { + bIsSurvivorClient[client] = false; + } +} + +public Action CheckTimer(Handle timer) { + //Don't do any processing if no one is connected. + //optimization: Only update player-based positions ever 5 loops (5 * 5 = 25 seconds) + static int timer_update_pos; + if(GetClientCount(true) == 0) return Plugin_Continue; + static float pos[3], ang[3], botPos[3], center_distance; + static float finalPos[3], checkPos[3]; + bool usingMinigun, usingMountedWeapon; + + for(int i = 1; i < MaxClients; i++) { + if(bIsSurvivorClient[i] && IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && !IsFakeClient(i)) { + usingMinigun = GetEntProp(i, Prop_Send, "m_usingMountedGun", 1) == 1; + usingMountedWeapon = GetEntProp(i, Prop_Send, "m_usingMountedWeapon", 1) == 1; + + if(usingMinigun || usingMountedWeapon) { + if(timer_update_pos == 0) { + GetClientAbsOrigin(i, pos); + GetClientEyeAngles(i, ang); + GetHorizontalPositionFromOrigin(pos, ang, 40.0, checkPos); //get center point of check radius + GetHorizontalPositionFromOrigin(pos, ang, -120.0, finalPos); //get center point of the bot destination + } + + for(int bot = 1; bot < MaxClients; bot++) { + if(bIsSurvivorClient[bot] && IsClientInGame(bot) && IsFakeClient(bot) && IsPlayerAlive(bot)) { + GetClientAbsOrigin(bot, botPos); + + center_distance = GetVectorDistance(checkPos, botPos, true); + + if(center_distance <= 4900) { + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", GetClientUserId(bot), finalPos[0], finalPos[1], finalPos[2]); + }else{ + L4D2_RunScript("CommandABot({cmd=3,bot=GetPlayerFromUserID(%i)})", GetClientUserId(bot)); + } + } + } + break; + } + } + } + timer_update_pos++; + if(timer_update_pos >= 5) timer_update_pos = 0; + return Plugin_Continue; +} diff --git a/scripting/l4d2_crescendo_control.sp b/scripting/l4d2_crescendo_control.sp new file mode 100644 index 0000000..092938a --- /dev/null +++ b/scripting/l4d2_crescendo_control.sp @@ -0,0 +1,387 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG 0 +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +//#include + +#define PANIC_DETECT_THRESHOLD 50.0 +#define MAX_GROUPS 4 + +enum struct Group { + float pos[3]; + ArrayList members; +} + +enum struct GroupResult { + int groupCount; + int ungroupedCount; + float ungroupedRatio; +} + + +static ConVar hPercent, hRange, hEnabled, hGroupTeamDist; +static char gamemode[32]; +static bool panicStarted; +static float lastButtonPressTime; +static float flowRate[MAXPLAYERS+1]; + +static Group g_groups[MAX_GROUPS]; + +public Plugin myinfo = +{ + name = "L4D2 Crescendo Control", + author = "jackzmc", + description = "Prevents players from starting crescendos early", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D2 only."); + } + + hEnabled = CreateConVar("l4d2_crescendo_control", "1", "Should plugin be active?\n 1 = Enabled normally\n2 = Admins with bypass allowed only", FCVAR_NONE, true, 0.0, true, 1.0); + hPercent = CreateConVar("l4d2_crescendo_percent", "0.5", "The percent of players needed to be in range for crescendo to start", FCVAR_NONE); + hRange = CreateConVar("l4d2_crescendo_range", "250.0", "How many units away something range brain no work", FCVAR_NONE); + hGroupTeamDist = CreateConVar("l4d2_cc_team_maxdist", "320.0", "The maximum distance another player can be away from someone to form a group", FCVAR_NONE, true, 10.0); + + ConVar hGamemode = FindConVar("mp_gamemode"); + hGamemode.GetString(gamemode, sizeof(gamemode)); + hGamemode.AddChangeHook(Event_GamemodeChange); + + AddNormalSoundHook(SoundHook); + + RegAdminCmd("sm_dgroup", Command_DebugGroups, ADMFLAG_GENERIC); + for(int i = 0; i < MAX_GROUPS; i++) { + g_groups[i].members = null; + } +} + +Action Command_DebugGroups(int client, int args) { + PrintDebug("Running manual compute of groups"); + if(client == 0) { + PrintDebug("Ran from server console, using first player on server"); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + client = i; + PrintDebug("User: %N", i); + break; + } + } + } + float activatorFlow = L4D2Direct_GetFlowDistance(client); + GroupResult result; + ComputeGroups(result, activatorFlow); + return Plugin_Handled; +} + +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); +} + + +public void OnMapStart() { + if(StrEqual(gamemode, "coop")) { + HookEntityOutput("func_button", "OnPressed", Event_ButtonPress); + CreateTimer(1.0, Timer_GetFlows, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + } +} + +public void OnMapEnd() { + panicStarted = false; + for(int i = 1; i <= MaxClients; i++) { + flowRate[i] = 0.0; + } +} + +public void OnClientDisconnect(int client) { + flowRate[client] = 0.0; +} + +public Action Timer_GetFlows(Handle h) { + static float flow; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + flow = L4D2Direct_GetFlowDistance(i); + if(flow > flowRate[i]) { + flowRate[i] = flow; + } + } + } + return Plugin_Continue; +} + +public float GetFlowAtPosition(const float pos[3]) { + Address area = L4D_GetNearestNavArea(pos, 50.0, false, false, false, 2); + if(area == Address_Null) return -1.0; + return L4D2Direct_GetTerrorNavAreaFlow(area); +} + +public Action Event_ButtonPress(const char[] output, int entity, int client, float delay) { + if(hEnabled.IntValue > 0 && client > 0 && client <= MaxClients) { + float activatorFlow = L4D2Direct_GetFlowDistance(client); + GroupResult result; + ComputeGroups(result, activatorFlow); + PrintToConsoleAll("[CC] Button Press by %N", client); + + AdminId admin = GetUserAdmin(client); + if(admin != INVALID_ADMIN_ID && admin.HasFlag(Admin_Custom1)) { + lastButtonPressTime = GetGameTime(); + return Plugin_Continue; + } else if(result.groupCount > 0 && result.ungroupedCount > 0) { + lastButtonPressTime = GetGameTime(); + return Plugin_Continue; + } + + if(panicStarted) { + panicStarted = false; + return Plugin_Continue; + } + + + static float pos[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + + + if(hEnabled.IntValue == 2 || !IsActivationAllowed(activatorFlow, 1500.0)) { + ClientCommand(client, "play ui/menu_invalid.wav"); + PrintToChat(client, "Please wait for players to catch up."); + AcceptEntityInput(entity, "Lock"); + RequestFrame(Frame_ResetButton, entity); + return Plugin_Handled; + } + lastButtonPressTime = GetGameTime(); + } + return Plugin_Continue; +} + + +public Action SoundHook(int clients[MAXPLAYERS], int& numClients, char sample[PLATFORM_MAX_PATH], int& entity, int& channel, float& volume, int& level, int& pitch, int& flags, char soundEntry[PLATFORM_MAX_PATH], int& seed) { + if(StrEqual(sample, "npc/mega_mob/mega_mob_incoming.wav") && lastButtonPressTime > 0) { + if(GetGameTime() - lastButtonPressTime < PANIC_DETECT_THRESHOLD) { + panicStarted = true; + } + } + return Plugin_Continue; +} + +public void Frame_ResetButton(int entity) { + AcceptEntityInput(entity, "Unlock"); +} +bool ComputeGroups(GroupResult result, float activateFlow) { + float prevPos[3], pos[3]; + // int prevMember = -1; + // ArrayList groupMembers = new ArrayList(); + int groupIndex = 0; + // ArrayList groups = new ArrayList(); + + // Group group; + // // Create the first group + // group.pos = pos; + // group.members = new ArrayList(); + // PrintToServer("[cc] Creating first group"); + + bool inGroup[MAXPLAYERS+1]; + + ArrayList members = new ArrayList(); + for(int i = 0; i < MAX_GROUPS; i++) { + if(g_groups[i].members != null) { + delete g_groups[i].members; + } + } + + for(int i = 1; i <= MaxClients; i++) { + if(!inGroup[i] && IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + float prevFlow = L4D2Direct_GetFlowDistance(i); + GetClientAbsOrigin(i, prevPos); + + members.Clear(); + + for(int j = 1; j <= MaxClients; j++) { + if(j != i && IsClientConnected(j) && IsClientInGame(j) && IsPlayerAlive(j) && GetClientTeam(j) == 2) { + // TODO: MERGE groups + GetClientAbsOrigin(j, pos); + float flow = L4D2Direct_GetFlowDistance(j); + float dist = FloatAbs(GetVectorDistance(prevPos, pos)); + float flowDiff = FloatAbs(prevFlow - flow); + if(dist <= hGroupTeamDist.FloatValue) { + // Add user as leader to group: + if(members.Length == 0) { + members.Push(GetClientUserId(i)); + inGroup[i] = true; + // PrintDebug("add leader to group %d: %N", groupIndex + 1, i); + } + PrintDebug("add member to group %d: %N (dist = %.4f) (fldiff = %.1f)", groupIndex + 1, j, dist, flowDiff); + inGroup[j] = true; + members.Push(GetClientUserId(j)); + } else { + // PrintDebug("not adding member to group %d: %N (dist = %.4f) (fldiff = %.1f) (l:%N)", groupIndex + 1, j, dist, flowDiff, i); + } + } + } + if(members.Length > 1) { + // Drop the old members: + if(g_groups[groupIndex].members != null) { + delete g_groups[groupIndex].members; + } + g_groups[groupIndex].pos = prevPos; + g_groups[groupIndex].members = members; + members = new ArrayList(); + // PrintDebug("created group #%d with %d members", groupIndex + 1, g_groups[groupIndex].members.Length); + groupIndex++; + if(groupIndex == MAX_GROUPS) { + PrintDebug("maximum amount of groups reached (%d)", MAX_GROUPS); + break; + } + } + } + } + delete members; + + int totalGrouped = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + if(inGroup[i]) + totalGrouped++; + else + result.ungroupedCount++; + } + } + + result.ungroupedRatio = float(result.ungroupedCount) / float(totalGrouped); + + PrintDebug("total grouped: %d | total ungrouped: %d | ratio: %f", totalGrouped, result.ungroupedCount, result.ungroupedRatio); + + PrintDebug("total groups created: %d", groupIndex); + + PrintDebug("===GROUP SUMMARY==="); + for(int i = 0; i < MAX_GROUPS; i++) { + if(g_groups[i].members != null && g_groups[i].members.Length > 0) { + PrintDebug("---Group %d---", i + 1); + PrintDebug("Origin: %.1f %.1f %.1f", g_groups[i].pos[0], g_groups[i].pos[1], g_groups[i].pos[2]); + float groupFlow = GetFlowAtPosition(g_groups[i].pos); + PrintDebug("Flow Diff: %.2f (g:%.1f) (a:%.1f) (gtdist:%.f)", FloatAbs(activateFlow - groupFlow), activateFlow, groupFlow, hGroupTeamDist.FloatValue); + PrintDebug("Leader: %N (uid#%d)", GetClientOfUserId(g_groups[i].members.Get(0)), g_groups[i].members.Get(0)); + for(int j = 1; j < g_groups[i].members.Length; j++) { + int userid = g_groups[i].members.Get(j); + PrintDebug("Member: %N (uid#%d)", GetClientOfUserId(userid), userid); + } + } + } + if(result.ungroupedCount > 0) { + PrintDebug("--UNGROUPED SUMMARY--"); + for(int i = 1; i <= MaxClients; i++) { + if(!inGroup[i] && IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + PrintDebug("User: %N (uid#%d)", i, GetClientUserId(i)); + } + } + PrintDebug("--END UNGROUPED SUMMARY--"); + } + PrintDebug("===END GROUP SUMMARY==="); + // delete groupMembers; + + result.groupCount = groupIndex; + return groupIndex > 0; +} + +public Action L4D2_CGasCan_EventKilled(int gascan, int &inflictor, int &attacker) { + if(hEnabled.IntValue > 0 && attacker > 0 && attacker <= MaxClients) { + float activatorFlow = L4D2Direct_GetFlowDistance(attacker); + GroupResult result; + PrintToConsoleAll("[CC] Gascan Shot by %N", attacker); + // ComputeGroups(result, activatorFlow); + + AdminId admin = GetUserAdmin(attacker); + if(admin != INVALID_ADMIN_ID && admin.HasFlag(Admin_Custom1)) { + lastButtonPressTime = GetGameTime(); + return Plugin_Continue; + } else if(result.groupCount > 0 && result.ungroupedCount > 0) { + lastButtonPressTime = GetGameTime(); + return Plugin_Continue; + } + + if(panicStarted) { + panicStarted = false; + return Plugin_Continue; + } + + + PrintToConsoleAll("[CC] Gascan Light by %N", attacker); + if(hEnabled.IntValue == 2 || !IsActivationAllowed(activatorFlow, 1500.0)) { + ClientCommand(attacker, "play ui/menu_invalid.wav"); + PrintToChat(attacker, "Please wait for players to catch up."); + return Plugin_Handled; + } + lastButtonPressTime = GetGameTime(); + } + return Plugin_Continue; +} + + +// 5 far/8 total +// [Debug] average 4222.518066 - difference 2262.424316 +// [Debug] Percentage of far players: 0.625000% | Average 4222.518066 + +stock bool IsActivationAllowed(float flowmax, float threshold) { + // Broken behavior, just short circuit true + if(flowmax <= 0.01) return true; + + int farSurvivors, totalSurvivors; + float totalFlow; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && !IsFakeClient(i)) { + if(flowRate[i] < flowmax - threshold) { + PrintDebug("Adding %N with flow of %.2f to far survivors average", i, flowRate[i]); + farSurvivors++; + totalFlow += flowRate[i]; + } + totalSurvivors++; + } + } + if(farSurvivors == 0 || totalSurvivors == 1) return true; + float average = totalFlow / farSurvivors; + float percentFar = float(farSurvivors) / float(totalSurvivors); + + PrintDebug("Average Flow %f - Difference %f - Far % %f%% ", average, flowmax - average, percentFar * 100); + //If the average is in the range, allow + if(flowmax - average <= threshold) { + PrintDebug("Activation is allowed (in range)"); + return true; + } + //If not, check the ratio of players + bool isAllowed = percentFar <= 0.40; + PrintDebug("Activation is %s", isAllowed ? "allowed" : "blocked"); + return isAllowed; +} + +stock float GetAverageFlowBehind(float flowmax) { + int survivors; + float totalFlow; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + survivors++; + totalFlow += flowRate[i]; + } + } + return totalFlow / survivors; +} + + +stock void PrintDebug(const char[] format, any ... ) { + #if defined DEBUG + char buffer[256]; + VFormat(buffer, sizeof(buffer), format, 2); + // PrintToServer("[CrescendoControl:Debug] %s", buffer); + PrintToConsoleAll("[CrescendoControl:Debug] %s", buffer); + LogToFile("crescendo_control.log", "%s", buffer); + #endif +} \ No newline at end of file diff --git a/scripting/l4d2_detections.sp b/scripting/l4d2_detections.sp new file mode 100644 index 0000000..1f81b03 --- /dev/null +++ b/scripting/l4d2_detections.sp @@ -0,0 +1,294 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define BILE_NO_HORDE_THRESHOLD 5 +#define DOOR_CLOSE_THRESHOLD 5000.0 + +#include +#include +#include +#include +//#include + +enum KitDetectionState { + KDS_None, + KDS_NoKitEnteringSaferoom, + KDS_PickedUpKit, + KDS_Healed +} + +enum struct PlayerDetections { + int kitPickupsSaferoom; + int saferoomLastOpen; + int saferoomOpenCount; + bool hadKitBeforeHeal; + // Do not reset normally; need to keep track during level transitions + KitDetectionState saferoomKitState; + + // Called on PlayerDisconnect, which includes map changes + void Reset() { + this.kitPickupsSaferoom = 0; + this.saferoomLastOpen = 0; + this.saferoomOpenCount = 0; + } + // Called on normal intentional disconnect, ignoring map changes + void FullReset() { + this.saferoomKitState = KDS_None; + } + +} + +/* +Bile Detections: +1. No commons around entowner or bile +2. Bile already exists +3. Player is currently vomitted on (check time?) +4. Bile on tank (common count near tank) +*/ + +stock bool IsPlayerBoomed(int client) { + return GetEntPropFloat(client, Prop_Send, "m_vomitStart") + 20.1 > GetGameTime(); +} +stock bool IsAnyPlayerBoomed() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerBoomed(i)) { + return true; + } + } + return false; +} + +stock bool AnyRecentBileInPlay(int ignore) { + return false; +} + +stock int GetEntityCountNear(const float srcPos[3], float radius = 50000.0) { + float pos[3]; + int count; + int entity = -1; + while( (entity = FindEntityByClassname(entity, "infected")) != INVALID_ENT_REFERENCE ) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + if(GetEntProp(entity, Prop_Send, "m_clientLookatTarget") != -1 && GetVectorDistance(pos, srcPos) <= radius) { + count++; + } + } + return count; +} +stock int L4D_SpawnCommonInfected2(const float vPos[3], const float vAng[3] = { 0.0, 0.0, 0.0 }) +{ + int entity = CreateEntityByName("infected"); + if( entity != -1 ) + { + DispatchSpawn(entity); + TeleportEntity(entity, vPos, vAng, NULL_VECTOR); + } + + return entity; +} + +PlayerDetections detections[MAXPLAYERS+1]; +bool checkpointReached; + +GlobalForward fwd_PlayerDoubleKit, fwd_NoHordeBileWaste, fwd_DoorFaceCloser, fwd_CheckpointDoorFaceCloser; + +public Plugin myinfo = +{ + name = "L4D2 Detections", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + fwd_PlayerDoubleKit = new GlobalForward("OnDoubleKit", ET_Hook, Param_Cell); + fwd_NoHordeBileWaste = new GlobalForward("OnNoHordeBileWaste", ET_Event, Param_Cell, Param_Cell); + fwd_DoorFaceCloser = new GlobalForward("OnDoorCloseInFace", ET_Hook, Param_Cell); + fwd_CheckpointDoorFaceCloser = new GlobalForward("OnDoorCloseInFaceSaferoom", ET_Hook, Param_Cell, Param_Cell); + + HookEvent("item_pickup", Event_ItemPickup); + HookEvent("door_close", Event_DoorClose); + HookEvent("player_disconnect", Event_PlayerDisconnect); + HookEvent("heal_success", Event_HealSuccess); +} + +public void OnClientPutInServer(int client) { + CreateTimer(20.0, Timer_ClearDoubleKitDetection, GetClientUserId(client)); +} + +// Called on map changes too, we want this: +public void OnClientDisconnect(int client) { + detections[client].Reset(); +} + +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client) { + detections[client].FullReset(); + } +} + +public void OnMapStart() { + checkpointReached = false; + HookEntityOutput("info_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); + HookEntityOutput("trigger_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); +} + +// TODO: Check when player enters saferoom, and has no kit and heals and pickup another +public void Event_ItemPickup(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && L4D_IsInLastCheckpoint(client)) { + static char itmName[32]; + event.GetString("item", itmName, sizeof(itmName)); + if(StrEqual(itmName, "first_aid_kit")) { + if(detections[client].saferoomKitState == KDS_NoKitEnteringSaferoom) { + // Player had no kit entering saferoom and has healed + detections[client].saferoomKitState = KDS_PickedUpKit; + } else if(detections[client].saferoomKitState == KDS_PickedUpKit) { + // Player has healed. Double kit detected + InternalDebugLog("DOUBLE_KIT", client); + Call_StartForward(fwd_PlayerDoubleKit); + Call_PushCell(client); + Call_Finish(); + } + if(++detections[client].kitPickupsSaferoom == 2) { + InternalDebugLog("DOUBLE_KIT_LEGACY", client); + Call_StartForward(fwd_PlayerDoubleKit); + Call_PushCell(client); + Call_Finish(); + } + } + } +} + +public void EntityOutput_OnStartTouchSaferoom(const char[] output, int caller, int client, float time) { + if(!checkpointReached && client > 0 && client <= MaxClients && GetClientTeam(client) == 2) { + checkpointReached = true; + char itemName[32]; + if(GetClientWeaponName(client, 3, itemName, sizeof(itemName))) { + if(StrEqual(itemName, "weapon_first_aid_kit")) { + detections[client].saferoomKitState = KDS_NoKitEnteringSaferoom; + } + } + } +} + +Action Timer_ClearDoubleKitDetection(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client) { + detections[client].saferoomKitState = KDS_None; + } + return Plugin_Continue; +} + +public void Event_HealSuccess(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client) { + int target = GetClientOfUserId(event.GetInt("subject")); + int amount = event.GetInt("health_restored"); + int orgHealth = GetClientHealth(target) - amount; + PrintToConsoleAll("[Debug] %N healed %N (+%d health, was perm. %d)", client, target, amount, orgHealth); + } +} + +public void Event_DoorClose(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(fwd_DoorFaceCloser.FunctionCount > 0 && client) { + bool isCheckpoint = event.GetBool("checkpoint"); + DataPack pack = GetNearestClient(client); + pack.Reset(); + int victim = pack.ReadCell(); + float dist = pack.ReadFloat(); + if(victim) { + if(dist < DOOR_CLOSE_THRESHOLD) { + if(isCheckpoint) { + if(detections[client].saferoomLastOpen > 0 && GetTime() - detections[client].saferoomLastOpen > 30000) { + detections[client].saferoomLastOpen = 0; + detections[client].saferoomOpenCount = 0; + } + Call_StartForward(fwd_CheckpointDoorFaceCloser); + Call_PushCell(client); + Call_PushCell(victim); + Call_PushCell(++detections[client].saferoomOpenCount); + Call_Finish(); + detections[client].saferoomLastOpen = GetTime(); + PrintToServer("[Detections] DOOR_SAFEROOM: %N victim -> %N %d times", client, victim, detections[client].saferoomOpenCount); + //TODO: Find way to reset, timer? + } else { + Call_StartForward(fwd_DoorFaceCloser); + Call_PushCell(client); + Call_PushCell(victim); + Call_Finish(); + PrintToServer("[Detections] DOOR=: %N victim -> %N", client, victim); + } + } + } + } +} + +public void OnEntityDestroyed(int entity) { + static char classname[16]; + if(IsValidEntity(entity) && entity <= 4096) { + GetEntityClassname(entity, classname, sizeof(classname)); + if(StrEqual(classname, "vomitjar_projec")) { //t cut off by classname size + int thrower = GetEntPropEnt(entity, Prop_Send, "m_hThrower"); + if(thrower > 0 && thrower <= MaxClients && IsClientConnected(thrower) && IsClientInGame(thrower)) { + static float src[3]; + float tmp[3]; + GetClientAbsOrigin(thrower, tmp); + // TODO: Get source when lands + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", src); + + int commons = GetEntityCountNear(src, 50000.0); + PrintToConsoleAll("[Debug] Bile Thrown By %N, Commons: %d", thrower, commons); + if(commons < BILE_NO_HORDE_THRESHOLD) { + InternalDebugLog("BILE_NO_HORDE", thrower); + Action result; + Call_StartForward(fwd_NoHordeBileWaste); + Call_PushCell(thrower); + Call_PushCell(commons); + Call_Finish(result); + + if(result == Plugin_Stop) { + AcceptEntityInput(entity, "kill"); + // GiveClientWeapon(thrower, "vomitjar"); + } + } + } + } + } +} + +// TODO: Door close + +void InternalDebugLog(const char[] name, int client) { + PrintToConsoleAll("[Detection] %s: Client %N", name, client); +} + +stock DataPack GetNearestClient(int client) { + int victim; + float pos[3], pos2[3], distance; + GetClientAbsOrigin(client, pos); + for(int i = 1; i <= MaxClients; i++) { + if(i != client && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + GetClientAbsOrigin(i, pos2); + float dist = GetVectorDistance(pos, pos2, false); + if(victim == 0 || dist < distance) { + distance = dist; + victim = i; + } + } + } + DataPack pack = new DataPack(); + pack.WriteCell(victim); + pack.WriteFloat(distance); + return pack; +} \ No newline at end of file diff --git a/scripting/l4d2_drop_secondary.sp b/scripting/l4d2_drop_secondary.sp new file mode 100644 index 0000000..7d56a65 --- /dev/null +++ b/scripting/l4d2_drop_secondary.sp @@ -0,0 +1,233 @@ +#pragma semicolon 1 +#pragma newdecls required //強制1.7以後的新語法 +#include +#include + +#define MODEL_V_FIREAXE "models/weapons/melee/v_fireaxe.mdl" +#define MODEL_V_FRYING_PAN "models/weapons/melee/v_frying_pan.mdl" +#define MODEL_V_MACHETE "models/weapons/melee/v_machete.mdl" +#define MODEL_V_BASEBALL_BAT "models/weapons/melee/v_bat.mdl" +#define MODEL_V_CROWBAR "models/weapons/melee/v_crowbar.mdl" +#define MODEL_V_CRICKET_BAT "models/weapons/melee/v_cricket_bat.mdl" +#define MODEL_V_TONFA "models/weapons/melee/v_tonfa.mdl" +#define MODEL_V_KATANA "models/weapons/melee/v_katana.mdl" +#define MODEL_V_ELECTRIC_GUITAR "models/weapons/melee/v_electric_guitar.mdl" +#define MODEL_V_GOLFCLUB "models/weapons/melee/v_golfclub.mdl" +#define MODEL_V_SHIELD "models/weapons/melee/v_riotshield.mdl" +#define MODEL_V_KNIFE "models/v_models/v_knife_t.mdl" +#define MODEL_V_SHOVEL "models/weapons/melee/v_shovel.mdl" +#define MODEL_V_PITCHFORK "models/weapons/melee/v_pitchfork.mdl" + +static g_PlayerSecondaryWeapons[MAXPLAYERS + 1]; + +public Plugin myinfo = +{ + name = "L4D2 Drop Secondary", + author = "Jahze, Visor, NoBody & HarryPotter", + version = "1.8", + description = "Survivor players will drop their secondary weapon when they die", + url = "https://github.com/Attano/Equilibrium" +}; + +public void OnPluginStart() +{ + HookEvent("round_start", OnRoundStart, EventHookMode_PostNoCopy); + HookEvent("player_use", OnPlayerUse, EventHookMode_Post); + HookEvent("player_bot_replace", player_bot_replace); + HookEvent("bot_player_replace", bot_player_replace); + HookEvent("player_death", OnPlayerDeath, EventHookMode_Pre); + HookEvent("weapon_drop", OnWeaponDrop); + HookEvent("item_pickup", OnItemPickUp); +} + +public void OnRoundStart(Event event, const char[] name, bool dontBroadcast) +{ + for (int i = 0; i <= MAXPLAYERS; i++) + { + g_PlayerSecondaryWeapons[i] = -1; + } +} + +public Action OnPlayerUse(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + + if(client == 0 || !IsClientInGame(client) || GetClientTeam(client) != 2) + { + return; + } + + int weapon = GetPlayerWeaponSlot(client, 1); + + g_PlayerSecondaryWeapons[client] = (weapon == -1 ? weapon : EntIndexToEntRef(weapon)); +} + +public Action bot_player_replace(Event event, const char[] name, bool dontBroadcast) +{ + int bot = GetClientOfUserId(event.GetInt("bot")); + int client = GetClientOfUserId(event.GetInt("player")); + + g_PlayerSecondaryWeapons[client] = g_PlayerSecondaryWeapons[bot]; + g_PlayerSecondaryWeapons[bot] = -1; +} + +public Action player_bot_replace(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("player")); + int bot = GetClientOfUserId(event.GetInt("bot")); + + g_PlayerSecondaryWeapons[bot] = g_PlayerSecondaryWeapons[client]; + g_PlayerSecondaryWeapons[client] = -1; +} + +public Action OnItemPickUp(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if(client == 0 || !IsClientInGame(client) || GetClientTeam(client) != 2) + { + return; + } + int weapon = GetPlayerWeaponSlot(client, 1); + + g_PlayerSecondaryWeapons[client] = (weapon == -1 ? weapon : EntIndexToEntRef(weapon)); +} + +public Action OnWeaponDrop(Event event, const char[] name, bool dontBroadcast) +{ + CreateTimer(0.1, ColdDown, event.GetInt("userid")); +} + +public Action ColdDown(Handle timer, int client) +{ + client = GetClientOfUserId(client); + if(client && IsClientInGame(client) && GetClientTeam(client) == 2) + { + int weapon = GetPlayerWeaponSlot(client, 1); + + g_PlayerSecondaryWeapons[client] = (weapon == -1 ? weapon : EntIndexToEntRef(weapon)); + } +} + +public Action OnPlayerDeath(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + + if(client == 0 || !IsClientInGame(client) || GetClientTeam(client) != 2) + { + return; + } + + int weapon = EntRefToEntIndex(g_PlayerSecondaryWeapons[client]); + + if(weapon == INVALID_ENT_REFERENCE) + { + return; + } + + char sWeapon[32]; + int clip; + GetEdictClassname(weapon, sWeapon, 32); + + int index = CreateEntityByName(sWeapon); + float origin[3]; + float ang[3]; + if (strcmp(sWeapon, "weapon_melee") == 0) + { + char melee[150]; + GetEntPropString(weapon , Prop_Data, "m_ModelName", melee, sizeof(melee)); + if (strcmp(melee, MODEL_V_FIREAXE) == 0) + { + DispatchKeyValue(index, "melee_script_name", "fireaxe"); + } + else if (strcmp(melee, MODEL_V_FRYING_PAN) == 0) + { + DispatchKeyValue(index, "melee_script_name", "frying_pan"); + } + else if (strcmp(melee, MODEL_V_MACHETE) == 0) + { + DispatchKeyValue(index, "melee_script_name", "machete"); + } + else if (strcmp(melee, MODEL_V_BASEBALL_BAT) == 0) + { + DispatchKeyValue(index, "melee_script_name", "baseball_bat"); + } + else if (strcmp(melee, MODEL_V_CROWBAR) == 0) + { + DispatchKeyValue(index, "melee_script_name", "crowbar"); + } + else if (strcmp(melee, MODEL_V_CRICKET_BAT) == 0) + { + DispatchKeyValue(index, "melee_script_name", "cricket_bat"); + } + else if (strcmp(melee, MODEL_V_TONFA) == 0) + { + DispatchKeyValue(index, "melee_script_name", "tonfa"); + } + else if (strcmp(melee, MODEL_V_KATANA) == 0) + { + DispatchKeyValue(index, "melee_script_name", "katana"); + } + else if (strcmp(melee, MODEL_V_ELECTRIC_GUITAR) == 0) + { + DispatchKeyValue(index, "melee_script_name", "electric_guitar"); + } + else if (strcmp(melee, MODEL_V_GOLFCLUB) == 0) + { + DispatchKeyValue(index, "melee_script_name", "golfclub"); + } + else if (strcmp(melee, MODEL_V_SHIELD) == 0) + { + DispatchKeyValue(index, "melee_script_name", "riotshield"); + } + else if (strcmp(melee, MODEL_V_KNIFE) == 0) + { + DispatchKeyValue(index, "melee_script_name", "knife"); + } + else if (strcmp(melee, MODEL_V_SHOVEL) == 0) + { + DispatchKeyValue(index, "melee_script_name", "shovel"); + } + else if (strcmp(melee, MODEL_V_PITCHFORK) == 0) + { + DispatchKeyValue(index, "melee_script_name", "pitchfork"); + } + else return; + } + else if (strcmp(sWeapon, "weapon_chainsaw") == 0) + { + clip = GetEntProp(weapon, Prop_Send, "m_iClip1"); + } + else if (strcmp(sWeapon, "weapon_pistol") == 0 && (GetEntProp(weapon, Prop_Send, "m_isDualWielding") > 0)) + { + int indexC = CreateEntityByName(sWeapon); + GetClientEyePosition(client,origin); + GetClientEyeAngles(client, ang); + GetAngleVectors(ang, ang, NULL_VECTOR,NULL_VECTOR); + NormalizeVector(ang,ang); + ScaleVector(ang, 90.0); + + DispatchSpawn(indexC); + TeleportEntity(indexC, origin, NULL_VECTOR, ang); + } + else if (strcmp(sWeapon, "weapon_pistol_magnum") == 0) + { + clip = GetEntProp(weapon, Prop_Send, "m_iClip1"); + } + + RemovePlayerItem(client, weapon); + RemoveEntity(weapon); + + GetClientEyePosition(client,origin); + GetClientEyeAngles(client, ang); + GetAngleVectors(ang, ang, NULL_VECTOR,NULL_VECTOR); + NormalizeVector(ang,ang); + ScaleVector(ang, 90.0); + + DispatchSpawn(index); + TeleportEntity(index, origin, NULL_VECTOR, ang); + + if (strcmp(sWeapon, "weapon_chainsaw") == 0 || strcmp(sWeapon, "weapon_pistol") == 0 || strcmp(sWeapon, "weapon_pistol_magnum") == 0) + { + SetEntProp(index, Prop_Send, "m_iClip1", clip); + } +} diff --git a/scripting/l4d2_extraplayeritems.sp b/scripting/l4d2_extraplayeritems.sp new file mode 100644 index 0000000..c43e4df --- /dev/null +++ b/scripting/l4d2_extraplayeritems.sp @@ -0,0 +1,2197 @@ +/* + Logic Flow: + + Once a player reaches the saferoom, it will give at a minimum a kit for each extra player over 4. + There is a small chance of bonus kit, and will give bonus depending on average team health + + Kits are provided when a player attempts to pickup a new kit, + or when they load back in after map transition (and don't already have one) + + Once a new map starts, all item spawners are checked and randomly their spawn count will be increased by 1. + Also on map start, cabinets will be populated with extra items dependent on player count + extraitems = (playerCount) * (cabinetAmount/4) - cabinetAmount +*/ + + +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG_INFO 0 +#define DEBUG_GENERIC 1 +#define DEBUG_SPAWNLOGIC 2 +#define DEBUG_ANY 3 + +#define INV_SAVE_TIME 5.0 // How long after a save request do we actually save. Seconds. +#define MIN_JOIN_TIME 30 // The minimum amount of time after player joins where we can start saving + +//Set the debug level +#define DEBUG_LEVEL DEBUG_SPAWNLOGIC +#define EXTRA_PLAYER_HUD_UPDATE_INTERVAL 0.8 +//Sets g_survivorCount to this value if set +// #define DEBUG_FORCE_PLAYERS 7 + +#define FLOW_CUTOFF 500.0 // The cutoff of flow, so that witches / tanks don't spawn in saferooms / starting areas, [0 + FLOW_CUTOFF, MapMaxFlow - FLOW_CUTOFF] + +#define EXTRA_TANK_MIN_SEC 2.0 +#define EXTRA_TANK_MAX_SEC 16.0 +#define DATE_FORMAT "%F at %I:%M %p" + + + +/// DONT CHANGE + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +#include +#include +#include +#include +#include +#undef REQUIRE_PLUGIN +#include + +#define L4D2_WEPUPGFLAG_NONE (0 << 0) +#define L4D2_WEPUPGFLAG_INCENDIARY (1 << 0) +#define L4D2_WEPUPGFLAG_EXPLOSIVE (1 << 1) +#define L4D2_WEPUPGFLAG_LASER (1 << 2) + +#define AMMOPACK_ENTID 0 +#define AMMOPACK_USERS 1 + +#define TANK_CLASS_ID 8 + +// configurable: +#define PLAYER_DROP_TIMEOUT_SECONDS 120000.0 + + +enum struct PlayerItems { + char throwable[2]; + char usable[2]; + char consumable[2]; +} +PlayerItems items[MAXPLAYERS+1]; + +public Plugin myinfo = +{ + name = "L4D2 Extra Player Tools", + author = "jackzmc", + description = "Automatic system for management of 5+ player games. Provides extra kits, items, and more", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +ConVar hExtraItemBasePercentage, hAddExtraKits, hMinPlayers, hUpdateMinPlayers, hMinPlayersSaferoomDoor, hSaferoomDoorWaitSeconds, hSaferoomDoorAutoOpen, hEPIHudState, hExtraFinaleTank, cvDropDisconnectTime, hSplitTankChance, cvFFDecreaseRate, cvZDifficulty, cvEPIHudFlags, cvEPISpecialSpawning, cvEPIGamemodes, hGamemode, cvEPITankHealth, cvEPIEnabledMode; +ConVar g_ffFactorCvar, hExtraTankThreshold; +int g_extraKitsAmount, g_extraKitsStart, g_saferoomDoorEnt, g_prevPlayerCount; +bool g_forcedSurvivorCount; +static int g_currentChapter; +bool g_isCheckpointReached, g_isLateLoaded, g_startCampaignGiven, g_isFailureRound, g_areItemsPopulated; +static ArrayList g_ammoPacks; +static Handle updateHudTimer; +static bool showHudPingMode; +static int hudModeTicks; +static char g_currentGamemode[32]; +static bool g_isGamemodeAllowed; +int g_survivorCount, g_realSurvivorCount; +bool g_isFinaleEnding; +static bool g_epiEnabled; +bool g_isOfficialMap; + +bool g_isSpeaking[MAXPLAYERS+1]; + +enum Difficulty { + Difficulty_Easy, + Difficulty_Normal, + Difficulty_Advanced, + Difficulty_Expert, +} + +Difficulty zDifficulty; + +bool g_extraFinaleTankEnabled; + +enum State { + State_Empty, + State_PendingEmpty, + State_Pending, + State_Active +} +#if defined DEBUG_LEVEL +char StateNames[4][] = { + "Empty", + "PendingEmpty", + "Pending", + "Active" +}; +#endif + +#define HUD_NAME_LENGTH 8 + +stock float SnapTo(const float value, const float degree) { + return float(RoundFloat(value / degree)) * degree; +} +stock int StrLenMB(const char[] str){ + int len = strlen(str); + int count; + for(int i; i < len; i++) { + count += ((str[i] & 0xc0) != 0x80) ? 1 : 0; + } + return count; +} + +enum struct PlayerData { + bool itemGiven; //Is player being given an item (such that the next pickup event is ignored) + bool isUnderAttack; //Is the player under attack (by any special) + State state; // join state + bool hasJoined; + int joinTime; + float returnedIdleTime; + + char nameCache[64]; + int scrollIndex; + int scrollMax; + + void Setup(int client) { + char name[32]; + GetClientName(client, name, sizeof(name)); + this.scrollMax = strlen(name); + for(int i = 0; i < this.scrollMax; i++) { + // if(IsCharMB(name[i])) { + // this.scrollMax--; + // name[i] = '\0'; + // } + } + + Format(this.nameCache, 64, "%s %s", name, name); + this.ResetScroll(); + } + + void ResetScroll() { + this.scrollIndex = 0; + // TOOD: figure out keeping unicode symbols and not scrolling when 7 characters view + // this.scrollMax = strlen(name); + // this.scrollMax = RoundFloat(SnapTo(float(this.scrollMax), float(HUD_NAME_LENGTH))); + if(this.scrollMax >= 32) { + this.scrollMax = 31; + } + } + + void AdvanceScroll() { + if(cvEPIHudFlags.IntValue & 1) { + if(this.scrollMax > HUD_NAME_LENGTH) { + this.scrollIndex += 1; + // TODO: if name is < 8 + if(this.scrollIndex >= this.scrollMax) { + this.scrollIndex = 0; + } + } + } + } +} + +enum struct PlayerInventory { + int timestamp; + bool isAlive; + + WeaponId itemID[6]; + MeleeWeaponId meleeID; // If itemID[1] == WeaponId_Melee, pull from this + bool lasers; + + int primaryHealth; + int tempHealth; + + char model[64]; + int survivorType; + + float location[3]; +} + +PlayerData playerData[MAXPLAYERS+1]; + +static StringMap weaponMaxClipSizes; +static StringMap pInv; +static int g_lastInvSave[MAXPLAYERS+1]; +static Handle g_saveTimer[MAXPLAYERS+1] = { null, ... }; + +static char HUD_SCRIPT_DATA[] = "eph <- { Fields = { players = { slot = g_ModeScript.HUD_RIGHT_BOT, dataval = \"%s\", flags = g_ModeScript.HUD_FLAG_ALIGN_LEFT | g_ModeScript.HUD_FLAG_TEAM_SURVIVORS | g_ModeScript.HUD_FLAG_NOBG } } }\nHUDSetLayout(eph)\nHUDPlace(g_ModeScript.HUD_RIGHT_BOT,0.78,0.77,0.3,0.3)\ng_ModeScript;"; +static char HUD_SCRIPT_CLEAR[] = "g_ModeScript._eph <- { Fields = { players = { slot = g_ModeScript.HUD_RIGHT_BOT, dataval = \"\", flags = g_ModeScript.HUD_FLAG_ALIGN_LEFT|g_ModeScript.HUD_FLAG_TEAM_SURVIVORS|g_ModeScript.HUD_FLAG_NOBG } } };HUDSetLayout( g_ModeScript._eph );g_ModeScript"; +static char HUD_SCRIPT_DEBUG[] = "g_ModeScript._ephdebug <- {Fields = {players = {slot = g_ModeScript.HUD_RIGHT_BOT, dataval = \"DEBUG!!! %s\", flags = g_ModeScript.HUD_FLAG_ALIGN_LEFT|g_ModeScript.HUD_FLAG_TEAM_SURVIVORS|g_ModeScript.HUD_FLAG_NOBG}}};HUDSetLayout(g_ModeScript._ephdebug);HUDPlace(g_ModeScript.HUD_RIGHT_BOT, 0.72,0.78,0.3,0.3);g_ModeScript"; + + +#define CABINET_ITEM_BLOCKS 4 +enum struct Cabinet { + int id; + int items[CABINET_ITEM_BLOCKS]; +} +static Cabinet cabinets[10]; //Store 10 cabinets + +enum FinaleStage { + Stage_Inactive = 0, + Stage_Active = 1, // Finale has started + Stage_FirstTankSpawned = 2, + Stage_SecondTankSpawned = 3, + Stage_ActiveDone = 10 // No more logic to be done +} +FinaleStage g_finaleStage; + +//// Definitions completSe + +#include + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + if(late) g_isLateLoaded = true; + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + + weaponMaxClipSizes = new StringMap(); + pInv = new StringMap(); + g_ammoPacks = new ArrayList(2); // + + HookEvent("player_spawn", Event_PlayerSpawn); + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + //Tracking player items: + HookEvent("item_pickup", Event_ItemPickup); + HookEvent("weapon_drop", Event_ItemPickup); + + HookEvent("round_end", Event_RoundEnd); + HookEvent("map_transition", Event_MapTransition); + HookEvent("game_start", Event_GameStart); + HookEvent("game_end", Event_GameStart); + HookEvent("finale_start", Event_FinaleStart); + + //Special Event Tracking + HookEvent("player_info", Event_PlayerInfo); + HookEvent("player_disconnect", Event_PlayerDisconnect); + HookEvent("player_death", Event_PlayerDeath); + HookEvent("player_incapacitated", Event_PlayerIncapped); + + HookEvent("charger_carry_start", Event_ChargerCarry); + HookEvent("charger_carry_end", Event_ChargerCarry); + + HookEvent("lunge_pounce", Event_HunterPounce); + HookEvent("pounce_end", Event_HunterPounce); + HookEvent("pounce_stopped", Event_HunterPounce); + + HookEvent("choke_start", Event_SmokerChoke); + HookEvent("choke_end", Event_SmokerChoke); + HookEvent("choke_stopped", Event_SmokerChoke); + + HookEvent("jockey_ride", Event_JockeyRide); + HookEvent("jockey_ride_end", Event_JockeyRide); + + HookEvent("witch_spawn", Event_WitchSpawn); + HookEvent("finale_vehicle_incoming", Event_FinaleVehicleIncoming); + HookEvent("player_bot_replace", Event_PlayerToIdle); + HookEvent("bot_player_replace", Event_PlayerFromIdle); + + + + + hExtraItemBasePercentage = CreateConVar("epi_item_chance", "0.056", "The base chance (multiplied by player count) of an extra item being spawned.", FCVAR_NONE, true, 0.0, true, 1.0); + hAddExtraKits = CreateConVar("epi_kitmode", "0", "Decides how extra kits should be added.\n0 -> Overwrites previous extra kits\n1 -> Adds onto previous extra kits", FCVAR_NONE, true, 0.0, true, 1.0); + hUpdateMinPlayers = CreateConVar("epi_updateminplayers", "1", "Should the plugin update abm\'s cvar min_players convar to the player count?\n 0 -> NO\n1 -> YES", FCVAR_NONE, true, 0.0, true, 1.0); + hMinPlayersSaferoomDoor = CreateConVar("epi_doorunlock_percent", "0.75", "The percent of players that need to be loaded in before saferoom door is opened.\n 0 to disable", FCVAR_NONE, true, 0.0, true, 1.0); + hSaferoomDoorWaitSeconds = CreateConVar("epi_doorunlock_wait", "25", "How many seconds after to unlock saferoom door. 0 to disable", FCVAR_NONE, true, 0.0); + hSaferoomDoorAutoOpen = CreateConVar("epi_doorunlock_open", "0", "Controls when the door automatically opens after unlocked. Add bits together.\n0 = Never, 1 = When timer expires, 2 = When all players loaded in", FCVAR_NONE, true, 0.0); + hEPIHudState = CreateConVar("epi_hudstate", "1", "Controls when the hud displays.\n0 -> OFF, 1 = When 5+ players, 2 = ALWAYS", FCVAR_NONE, true, 0.0, true, 3.0); + hExtraFinaleTank = CreateConVar("epi_extra_tanks", "3", "Add bits together. 0 = Normal tank spawning, 1 = 50% tank split on non-finale (half health), 2 = Tank split (full health) on finale ", FCVAR_NONE, true, 0.0, true, 3.0); + hExtraTankThreshold = CreateConVar("epi_extra_tanks_min_players", "6", "The minimum number of players for extra tanks to spawn. When disabled, normal 5+ tank health applies", FCVAR_NONE, true, 0.0); + hSplitTankChance = CreateConVar("epi_splittank_chance", "0.65", "The % chance of a split tank occurring in non-finales", FCVAR_NONE, true, 0.0, true, 1.0); + cvDropDisconnectTime = CreateConVar("epi_disconnect_time", "120.0", "The amount of seconds after a player has actually disconnected, where their character slot will be void. 0 to disable", FCVAR_NONE, true, 0.0); + cvFFDecreaseRate = CreateConVar("epi_ff_decrease_rate", "0.3", "The friendly fire factor is subtracted from the formula (playerCount-4) * this rate. Effectively reduces ff penalty when more players. 0.0 to subtract none", FCVAR_NONE, true, 0.0); + cvEPIHudFlags = CreateConVar("epi_hud_flags", "3", "Add together.\n1 = Scrolling hud, 2 = Show ping", FCVAR_NONE, true, 0.0); + cvEPISpecialSpawning = CreateConVar("epi_sp_spawning", "2", "Determines what specials are spawned. Add bits together.\n1 = Normal specials\n2 = Witches\n4 = Tanks", FCVAR_NONE, true, 0.0); + cvEPITankHealth = CreateConVar("epi_tank_chunkhp", "2500", "The amount of health added to tank, for each extra player", FCVAR_NONE, true, 0.0); + cvEPIGamemodes = CreateConVar("epi_gamemodes", "coop,realism,versus", "Gamemodes where plugin is active. Comma-separated", FCVAR_NONE); + cvEPIEnabledMode = CreateConVar("epi_enabled", "1", "Is EPI enabled?\n0=OFF\n1=Auto (Official Maps Only)(5+)\n2=Auto (Any map) (5+)\n3=Forced on", FCVAR_NONE, true, 0.0, true, 3.0); + // TODO: hook flags, reset name index / ping mode + cvEPIHudFlags.AddChangeHook(Cvar_HudStateChange); + cvEPISpecialSpawning.AddChangeHook(Cvar_SpecialSpawningChange); + + if(hUpdateMinPlayers.BoolValue) { + hMinPlayers = FindConVar("abm_minplayers"); + if(hMinPlayers != null) PrintDebug(DEBUG_INFO, "Found convar abm_minplayers"); + } + + char buffer[16]; + cvZDifficulty = FindConVar("z_difficulty"); + cvZDifficulty.GetString(buffer, sizeof(buffer)); + cvZDifficulty.AddChangeHook(Event_DifficultyChange); + Event_DifficultyChange(cvZDifficulty, buffer, buffer); + + hGamemode = FindConVar("mp_gamemode"); + hGamemode.GetString(g_currentGamemode, sizeof(g_currentGamemode)); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, g_currentGamemode, g_currentGamemode); + + + if(g_isLateLoaded) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(GetClientTeam(i) == 2) { + SaveInventory(i, true); + } + playerData[i].Setup(i); + SDKHook(i, SDKHook_WeaponEquip, Event_Pickup); + } + } + TryStartHud(); + } + + + AutoExecConfig(true, "l4d2_extraplayeritems"); + + RegAdminCmd("sm_epi_sc", Command_SetSurvivorCount, ADMFLAG_KICK); + RegAdminCmd("sm_epi_val", Command_EpiVal, ADMFLAG_GENERIC); + #if defined DEBUG_LEVEL + RegAdminCmd("sm_epi_setkits", Command_SetKitAmount, ADMFLAG_CHEATS, "Sets the amount of extra kits that will be provided"); + RegAdminCmd("sm_epi_lock", Command_ToggleDoorLocks, ADMFLAG_CHEATS, "Toggle all toggle\'s lock state"); + RegAdminCmd("sm_epi_kits", Command_GetKitAmount, ADMFLAG_CHEATS); + RegConsoleCmd("sm_epi_stats", Command_DebugStats); + RegConsoleCmd("sm_epi_debug", Command_Debug); + // RegAdminCmd("sm_epi_val", Command_EPIValue); + RegAdminCmd("sm_epi_trigger", Command_Trigger, ADMFLAG_CHEATS); + #endif + RegAdminCmd("sm_epi_restore", Command_RestoreInventory, ADMFLAG_KICK); + RegAdminCmd("sm_epi_save", Command_SaveInventory, ADMFLAG_KICK); + CreateTimer(DIRECTOR_TIMER_INTERVAL, Timer_Director, _, TIMER_REPEAT); + CreateTimer(30.0, Timer_ForceUpdateInventories, _, TIMER_REPEAT); + +} + +void Event_FinaleVehicleIncoming(Event event, const char[] name, bool dontBroadcast) { + g_isFinaleEnding = true; +} + +Action Timer_ForceUpdateInventories(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + // SaveInventory(i); + } + } + Director_CheckSpawnCounts(); + return Plugin_Continue; +} + +public void OnClientPutInServer(int client) { + Director_OnClientPutInServer(client); + if(!IsFakeClient(client)) { + playerData[client].Setup(client); + + if(GetClientTeam(client) == 2) { + if(g_isGamemodeAllowed) { + // CreateTimer(0.2, Timer_CheckInventory, client); + } + }/* else if(abmExtraCount >= 4 && GetClientTeam(client) == 0) { + // TODO: revert revert + // L4D_TakeOverBot(client); + } */ + } +} + +public void OnClientDisconnect(int client) { + // For when bots disconnect in saferoom transitions, empty: + if(playerData[client].state == State_PendingEmpty) + playerData[client].state = State_Empty; + + if(!IsFakeClient(client) && IsClientInGame(client) && GetClientTeam(client) == 2) + SaveInventory(client, true); + g_isSpeaking[client] = false; +} + +public void OnPluginEnd() { + delete weaponMaxClipSizes; + delete g_ammoPacks; + L4D2_ExecVScriptCode(HUD_SCRIPT_CLEAR); +} + +/////////////////////////////////////////////////////////////////////////////// +// Special Infected Events +/////////////////////////////////////////////////////////////////////////////// +public Action Event_ChargerCarry(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("victim")); + if(victim) { + playerData[victim].isUnderAttack = StrEqual(name, "charger_carry_start"); + } + return Plugin_Continue; +} + +public Action Event_HunterPounce(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("victim")); + if(victim) { + playerData[victim].isUnderAttack = StrEqual(name, "lunge_pounce"); + } + return Plugin_Continue; +} + +public Action Event_SmokerChoke(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("victim")); + if(victim) { + playerData[victim].isUnderAttack = StrEqual(name, "choke_start"); + } + return Plugin_Continue; +} +public Action Event_JockeyRide(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("victim")); + if(victim) { + playerData[victim].isUnderAttack = StrEqual(name, "jockey_ride"); + } + return Plugin_Continue; +} + +/////////////////////////////////////////////////////////////////////////////// +// CVAR HOOKS +/////////////////////////////////////////////////////////////////////////////// +void Cvar_HudStateChange(ConVar convar, const char[] oldValue, const char[] newValue) { + hudModeTicks = 0; + showHudPingMode = false; + for(int i = 0; i <= MaxClients; i++) { + playerData[i].ResetScroll(); + } + if(convar.IntValue == 0) { + if(updateHudTimer != null) { + PrintToServer("[EPI] Stopping timer externally: Cvar changed to 0"); + delete updateHudTimer; + } + } else { + TryStartHud(); + } +} +void TryStartHud() { + int threshold = 0; + // Default to 0 for state == 2 (force) + if(hEPIHudState.IntValue == 1) { + // On L4D1 map start if 5 players, on L4D2 start with 6 + // On L4D1 more chance of duplicate models, so can't see health + threshold = L4D2_GetSurvivorSetMap() == 2 ? 4 : 5; + } + if(g_realSurvivorCount > threshold && updateHudTimer == null) { + PrintToServer("[EPI] Creating new hud timer"); + updateHudTimer = CreateTimer(EXTRA_PLAYER_HUD_UPDATE_INTERVAL, Timer_UpdateHud, _, TIMER_REPEAT); + } +} + +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(g_currentGamemode, sizeof(g_currentGamemode)); + g_isGamemodeAllowed = IsGamemodeAllowed(); +} + +ConVar GetActiveFriendlyFireFactor() { + if(zDifficulty == Difficulty_Easy) { + // Typically is 0 but doesn't matter + return FindConVar("survivor_friendly_fire_factor_easy"); + } else if(zDifficulty == Difficulty_Normal) { + return FindConVar("survivor_friendly_fire_factor_normal"); + } else if(zDifficulty == Difficulty_Advanced) { + return FindConVar("survivor_friendly_fire_factor_hard"); + } else if(zDifficulty == Difficulty_Expert) { + return FindConVar("survivor_friendly_fire_factor_expert"); + } else { + return null; + } +} + +public void Event_DifficultyChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + if(StrEqual(newValue, "easy", false)) { + zDifficulty = Difficulty_Easy; + } else if(StrEqual(newValue, "normal", false)) { + zDifficulty = Difficulty_Normal; + } else if(StrEqual(newValue, "hard", false)) { + zDifficulty = Difficulty_Advanced; + } else if(StrEqual(newValue, "impossible", false)) { + zDifficulty = Difficulty_Expert; + } + g_ffFactorCvar = GetActiveFriendlyFireFactor(); + SetFFFactor(false); +} + +///////////////////////////////////// +/// COMMANDS +//////////////////////////////////// +public void ValBool(int client, const char[] name, bool &value, const char[] input) { + if(input[0] != '\0') { + value = input[0] == '1' || input[0] == 't'; + CReplyToCommand(client, "Set {olive}%s{default} to {yellow}%b", name, value); + } else { + CReplyToCommand(client, "Value of {olive}%s{default}: {yellow}%b", name, value); + } +} +public void ValInt(int client, const char[] name, int &value, const char[] input) { + if(input[0] != '\0') { + value = StringToInt(input); + CReplyToCommand(client, "Set {olive}%s{default} to {yellow}%d", name, value); + } else { + CReplyToCommand(client, "Value of {olive}%s{default}: {yellow}%d", name, value); + } +} +public void ValFloat(int client, const char[] name, float &value, const char[] input) { + if(input[0] != '\0') { + value = StringToFloat(input); + CReplyToCommand(client, "Set {olive}%s{default} to {yellow}%f", name, value); + } else { + CReplyToCommand(client, "Value of {olive}%s{default}: {yellow}%f", name, value); + } +} +Action Command_EpiVal(int client, int args) { + if(args == 0) { + PrintToConsole(client, "epiEnabled = %b", g_epiEnabled); + PrintToConsole(client, "isGamemodeAllowed = %b", g_isGamemodeAllowed); + PrintToConsole(client, "isOfficialMap = %b", g_isOfficialMap); + PrintToConsole(client, "extraKitsAmount = %d", g_extraKitsAmount); + PrintToConsole(client, "extraKitsStart = %d", g_extraKitsStart); + PrintToConsole(client, "currentChapter = %d", g_currentChapter); + PrintToConsole(client, "extraWitchCount = %d", g_extraWitchCount); + PrintToConsole(client, "forcedSurvivorCount = %b", g_forcedSurvivorCount); + PrintToConsole(client, "survivorCount = %d %s", g_survivorCount, g_forcedSurvivorCount ? "(forced)" : ""); + PrintToConsole(client, "realSurvivorCount = %d", g_realSurvivorCount); + PrintToConsole(client, "restCount = %d", g_restCount); + PrintToConsole(client, "extraFinaleTankEnabled = %b", g_extraFinaleTankEnabled); + PrintToConsole(client, "g_areItemsPopulated = %b", g_areItemsPopulated); + ReplyToCommand(client, "Values printed to console"); + return Plugin_Handled; + } + char arg[32], value[32]; + GetCmdArg(1, arg, sizeof(arg)); + GetCmdArg(2, value, sizeof(value)); + if(StrEqual(arg, "epiEnabled")) { + ValBool(client, "g_epiEnabled", g_epiEnabled, value); + } else if(StrEqual(arg, "isGamemodeAllowed")) { + ValBool(client, "g_isGamemodeAllowed", g_isGamemodeAllowed, value); + } else if(StrEqual(arg, "extraKitsAmount")) { + ValInt(client, "g_extraKitsAmount", g_extraKitsAmount, value); + } else if(StrEqual(arg, "extraKitsStart")) { + ValInt(client, "g_extraKitsStart", g_extraKitsStart, value); + } else if(StrEqual(arg, "currentChapter")) { + ValInt(client, "g_currentChapter", g_currentChapter, value); + } else if(StrEqual(arg, "extraWitchCount")) { + ValInt(client, "g_extraWitchCount", g_extraWitchCount, value); + } else if(StrEqual(arg, "restCount")) { + ValInt(client, "g_restCount", g_restCount, value); + } else if(StrEqual(arg, "survivorCount")) { + ValInt(client, "g_survivorCount", g_survivorCount, value); + } else if(StrEqual(arg, "realSurvivorCount")) { + ValInt(client, "g_survivorCount", g_survivorCount, value); + } else if(StrEqual(arg, "forcedSurvivorCount")) { + ValBool(client, "g_forcedSurvivorCount", g_forcedSurvivorCount, value); + } else if(StrEqual(arg, "forcedSurvivorCount")) { + ValBool(client, "g_extraFinaleTankEnabled", g_extraFinaleTankEnabled, value); + } else { + ReplyToCommand(client, "Unknown value"); + } + return Plugin_Handled; +} +Action Command_Trigger(int client, int args) { + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + if(StrEqual(arg, "witches")) { + InitExtraWitches(); + ReplyToCommand(client, "Extra witches active."); + } else if(StrEqual(arg, "items")) { + g_areItemsPopulated = false; + PopulateItems(); + ReplyToCommand(client, "Items populated."); + } else if(StrEqual(arg, "addbot")) { + if(GetFeatureStatus(FeatureType_Native, "NextBotCreatePlayerBotSurvivorBot") != FeatureStatus_Available){ + ReplyToCommand(client, "Unsupported."); + return Plugin_Handled; + } + int bot = CreateSurvivorBot(); + if(IsValidEdict(bot)) { + ReplyToCommand(client, "Created SurvivorBot: %d", bot); + } + } else { + ReplyToCommand(client, "Unknown trigger"); + } + return Plugin_Handled; +} +Action Command_SaveInventory(int client, int args) { + if(args == 0) { + ReplyToCommand(client, "Syntax: /epi_save "); + return Plugin_Handled; + } + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int player = GetSinglePlayer(client, arg, COMMAND_FILTER_NO_BOTS); + if(player == -1) { + ReplyToCommand(client, "No player found"); + return Plugin_Handled; + } + SaveInventory(player, true); + ReplyToCommand(client, "Saved inventory for %N", player); + return Plugin_Handled; +} +Action Command_RestoreInventory(int client, int args) { + if(args == 0) { + ReplyToCommand(client, "Syntax: /epi_restore "); + return Plugin_Handled; + } + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int player = GetSinglePlayer(client, arg, COMMAND_FILTER_NO_BOTS); + if(player == -1) { + ReplyToCommand(client, "No player found"); + return Plugin_Handled; + } + GetCmdArg(2, arg, sizeof(arg)); + PlayerInventory inv; + if(!GetLatestInventory(client, inv)) { + ReplyToCommand(client, "No stored inventory for player"); + return Plugin_Handled; + } + + if(StrEqual(arg, "full") || StrEqual(arg, "all")) { + RestoreInventory(client, inv); + } else if(StrEqual(arg, "pos")) { + TeleportEntity(player, inv.location, NULL_VECTOR, NULL_VECTOR); + } else { + ReplyToCommand(client, "Syntax: /epi_restore "); + return Plugin_Handled; + } + return Plugin_Handled; +} +// TODO: allow sc for new sys +int parseSurvivorCount(const char arg[8]) { + int newCount; + if(StringToIntEx(arg, newCount) > 0) { + if(newCount >= 0 && newCount <= MaxClients) { + return newCount; + } + } + return -1; +} +Action Command_SetSurvivorCount(int client, int args) { + if(args > 0) { + char arg[8]; + GetCmdArg(1, arg, sizeof(arg)); + if(arg[0] == 'c') { + g_forcedSurvivorCount = false; + ReplyToCommand(client, "Cleared forced survivor count."); + UpdateSurvivorCount(); + return Plugin_Handled; + } + int survivorCount = parseSurvivorCount(arg); + int oldSurvivorCount = g_survivorCount; + if(survivorCount == -1) { + ReplyToCommand(client, "Invalid survivor count. Must be between 0 and %d", MaxClients); + return Plugin_Handled; + } else if(args >= 2) { + GetCmdArg(2, arg, sizeof(arg)); + int realCount = parseSurvivorCount(arg); + if(realCount == -1 || realCount <= survivorCount) { + ReplyToCommand(client, "Invalid bot count. Must be between 0 and %d", survivorCount); + return Plugin_Handled; + } + int oldRealCount = g_realSurvivorCount; + g_realSurvivorCount = realCount; + ReplyToCommand(client, "Changed real survivor count %d -> %d", oldRealCount, realCount); + } else { + // If no real count count, it's the same as survivor count + g_realSurvivorCount = survivorCount; + } + g_survivorCount = survivorCount; + g_forcedSurvivorCount = true; + ReplyToCommand(client, "Forced survivor count %d -> %d", oldSurvivorCount, survivorCount); + } else { + ReplyToCommand(client, "Survivor Count = %d | Real Survivor Count = %d", g_survivorCount, g_realSurvivorCount); + } + return Plugin_Handled; +} + +#if defined DEBUG_LEVEL +Action Command_SetKitAmount(int client, int args) { + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + int number = StringToInt(arg); + if(number > 0 || number == -1) { + g_extraKitsAmount = number; + g_extraKitsStart = g_extraKitsAmount; + ReplyToCommand(client, "Set extra kits amount to %d", number); + } else { + ReplyToCommand(client, "Must be a number greater than 0. -1 to disable"); + } + return Plugin_Handled; +} + +Action Command_ToggleDoorLocks(int client, int args) { + for(int i = MaxClients + 1; i < GetMaxEntities(); i++) { + if(HasEntProp(i, Prop_Send, "m_bLocked")) { + int state = GetEntProp(i, Prop_Send, "m_bLocked"); + SetEntProp(i, Prop_Send, "m_bLocked", state > 0 ? 0 : 1); + } + } + return Plugin_Handled; +} + +Action Command_GetKitAmount(int client, int args) { + ReplyToCommand(client, "Extra kits available: %d (%d) | Survivors: %d", g_extraKitsAmount, g_extraKitsStart, g_survivorCount); + ReplyToCommand(client, "isCheckpointReached %b, g_isLateLoaded %b, firstGiven %b", g_isCheckpointReached, g_isLateLoaded, g_startCampaignGiven); + return Plugin_Handled; +} +Action Command_Debug(int client, int args) { + PrintToConsole(client, "g_survivorCount = %d | g_realSurvivorCount = %d", g_survivorCount, g_realSurvivorCount); + Director_PrintDebug(client); + return Plugin_Handled; +} +Action Command_DebugStats(int client, int args) { + if(args == 0) { + ReplyToCommand(client, "Player Statuses:"); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i)) { + ReplyToCommand(client, "\t\x04%d. %N:\x05 %s", i, i, StateNames[view_as(playerData[i].state)]); + } + } + } else { + char arg[32]; + GetCmdArg(1, arg, sizeof(arg)); + PlayerInventory inv; + int player = GetSinglePlayer(client, arg, COMMAND_FILTER_NO_BOTS); + if(player == 0) { + if(!GetInventory(arg, inv)) { + ReplyToCommand(client, "No player found"); + return Plugin_Handled; + } + } + + if(!GetLatestInventory(player, inv)) { + ReplyToCommand(client, "No saved inventory for %N", player); + return Plugin_Handled; + } + if(inv.isAlive) + ReplyToCommand(client, "\x04State: \x05%s (Alive)", StateNames[view_as(playerData[player].state)]); + else + ReplyToCommand(client, "\x04State: \x05%s (Dead)", StateNames[view_as(playerData[player].state)]); + FormatTime(arg, sizeof(arg), DATE_FORMAT, inv.timestamp); + ReplyToCommand(client, "\x04Timestamp: \x05%s (%d seconds)", arg, GetTime() - inv.timestamp); + ReplyToCommand(client, "\x04Location: \x05%.1f %.1f %.1f", inv.location[0], inv.location[1], inv.location[2]); + ReplyToCommand(client, "\x04Model: \x05%s (%d)", inv.model, inv.survivorType); + ReplyToCommand(client, "\x04Health: \x05%d perm. / %d temp.", inv.primaryHealth, inv.tempHealth); + ReplyToCommand(client, "\x04Items: \x05(Lasers:%b)", inv.lasers); + for(int i = 0; i < 6; i++) { + if(inv.itemID[i] != WEPID_NONE) { + GetLongWeaponName(inv.itemID[i], arg, sizeof(arg)); + ReplyToCommand(client, "\x04%d. \x05%s", i, arg); + } + } + } + return Plugin_Handled; +} +#endif +///////////////////////////////////// +/// EVENTS +//////////////////////////////////// +void OnTakeDamageAlivePost(int victim, int attacker, int inflictor, float damage, int damagetype) { + if(GetClientTeam(victim) == 2 && !IsFakeClient(victim)) + SaveInventory(victim); +} +void Event_PlayerToIdle(Event event, const char[] name, bool dontBroadcast) { + int bot = GetClientOfUserId(event.GetInt("bot")); + int client = GetClientOfUserId(event.GetInt("player")); + if(GetClientTeam(client) != 2) return; + PrintToServer("%N -> idle %N", client, bot); +} +void Event_PlayerFromIdle(Event event, const char[] name, bool dontBroadcast) { + int bot = GetClientOfUserId(event.GetInt("bot")); + int client = GetClientOfUserId(event.GetInt("player")); + if(GetClientTeam(client) != 2) return; + playerData[client].returnedIdleTime = GetGameTime(); + PrintToServer("idle %N -> idle %N", bot, client); +} +public void OnGetWeaponsInfo(int pThis, const char[] classname) { + char clipsize[8]; + InfoEditor_GetString(pThis, "clip_size", clipsize, sizeof(clipsize)); + + int maxClipSize = StringToInt(clipsize); + if(maxClipSize > 0) + weaponMaxClipSizes.SetValue(classname, maxClipSize); +} + +/////////////////////////////////////////////////////// +//// PLAYER STATE MANAGEMENT +/////////////////////////////////////////////////////// + +//Called on the first spawn in a mission. +void Event_GameStart(Event event, const char[] name, bool dontBroadcast) { + g_startCampaignGiven = false; + g_extraKitsAmount = 0; + g_extraKitsStart = 0; + g_realSurvivorCount = 0; + g_survivorCount = 0; + hMinPlayers.IntValue = 4; + g_currentChapter = 0; + pInv.Clear(); + for(int i = 1; i <= MaxClients; i++) { + playerData[i].state = State_Empty; + } +} + +// This is only called when a player joins for the first time during an entire campaign, unless they fully disconnect. +// Idle bots also call this as they are created and destroyed on idle/resume +void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int userid = event.GetInt("userid"); + int client = GetClientOfUserId(userid); + if(GetClientTeam(client) != 2) return; + UpdateSurvivorCount(); + if(IsFakeClient(client)) { + // Ignore any 'BOT' bots (ABMBot, etc), they are temporarily + char classname[32]; + GetEntityClassname(client, classname, sizeof(classname)); + if(StrContains(classname, "bot", false) > -1) return; + + // Make new bots invincible for a few seconds, as they spawn on other players. Only applies to a player's bot + int player = L4D_GetIdlePlayerOfBot(client); + // TODO: check instead hasJoined but state == state_empty + if(player > 0 && !playerData[client].hasJoined) { + playerData[client].hasJoined = true; + playerData[client].state = State_Pending; + CreateTimer(1.5, Timer_RemoveInvincibility, userid); + SDKHook(client, SDKHook_OnTakeDamage, OnInvincibleDamageTaken); + } + } else { + // Is a player + + // Make the (real) player invincible as well: + CreateTimer(1.5, Timer_RemoveInvincibility, userid); + SDKHook(client, SDKHook_OnTakeDamage, OnInvincibleDamageTaken); + SDKHook(client, SDKHook_OnTakeDamageAlivePost, OnTakeDamageAlivePost); + + playerData[client].state = State_Active; + playerData[client].joinTime = GetTime(); + + if(L4D_IsFirstMapInScenario() && !g_startCampaignGiven) { + // Players are joining the campaign, but not all clients are ready yet. Once a client is ready, we will give the extra players their items + if(AreAllClientsReady()) { + g_startCampaignGiven = true; + if(g_realSurvivorCount > 4) { + PrintToServer("[EPI] First chapter kits given"); + //Set the initial value ofhMinPlayers + PopulateItems(); + CreateTimer(1.0, Timer_GiveKits); + } + UnlockDoor(2); + } + } else { + // New client has connected, late on the first chapter or on any other chapter + // If 5 survivors, then set them up, TP them. + if(g_realSurvivorCount > 4) { + CreateTimer(0.2, Timer_SetupNewClient, userid); + } + } + } +} +// This is called everytime a player joins, such as map transitions +void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + if(!g_isGamemodeAllowed) return; + + int userid = event.GetInt("userid"); + int client = GetClientOfUserId(userid); + if(GetClientTeam(client) != 2) return; + UpdateSurvivorCount(); + if(!IsFakeClient(client) && !L4D_IsFirstMapInScenario()) { + // Start door timeout: + if(g_saferoomDoorEnt != INVALID_ENT_REFERENCE) { + CreateTimer(hSaferoomDoorWaitSeconds.FloatValue, Timer_OpenSaferoomDoor, _, TIMER_FLAG_NO_MAPCHANGE); + + if(g_prevPlayerCount > 0) { + // Open the door if we hit % percent + float percentIn = float(g_realSurvivorCount) / float(g_prevPlayerCount); + if(percentIn > hMinPlayersSaferoomDoor.FloatValue) + UnlockDoor(2); + } else{ + UnlockDoor(2); + } + } + CreateTimer(0.5, Timer_GiveClientKit, userid); + SDKHook(client, SDKHook_WeaponEquip, Event_Pickup); + } + TryStartHud(); + UpdatePlayerInventory(client); +} + +void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int userid = event.GetInt("userid"); + int client = GetClientOfUserId(userid); + if(client > 0 && IsClientInGame(client) && GetClientTeam(client) == 2 && playerData[client].state == State_Active) { + playerData[client].hasJoined = false; + playerData[client].state = State_PendingEmpty; + playerData[client].nameCache[0] = '\0'; + PrintToServer("debug: Player (index %d, uid %d) now pending empty", client, client, userid); + CreateTimer(cvDropDisconnectTime.FloatValue, Timer_DropSurvivor, client); + + } + if(g_saveTimer[client] != null) + delete g_saveTimer[client]; +} + +void Event_PlayerInfo(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && !IsFakeClient(client)) { + playerData[client].Setup(client); + } +} + +Action Timer_DropSurvivor(Handle h, int client) { + // Check that they are still pending empty (no one replaced them) + if(playerData[client].state == State_PendingEmpty) { + playerData[client].state = State_Empty; + if(hMinPlayers != null) { + PrintToServer("[EPI] Dropping survivor %d. hMinPlayers-pre:%d g_survivorCount=%d g_realSurvivorCount=%d", client, hMinPlayers.IntValue, g_survivorCount, g_realSurvivorCount); + PrintToConsoleAll("[EPI] Dropping survivor %d. hMinPlayers-pre:%d g_survivorCount=%d g_realSurvivorCount=%d", client, hMinPlayers.IntValue, g_survivorCount, g_realSurvivorCount); + hMinPlayers.IntValue = g_realSurvivorCount; + if(hMinPlayers.IntValue < 4) { + hMinPlayers.IntValue = 4; + } + } + DropDroppedInventories(); + } + return Plugin_Handled; +} + +///////////////////////////////////////// +/////// Events +///////////////////////////////////////// + +Action Event_Pickup(int client, int weapon) { + if(g_extraKitsAmount <= 0 || playerData[client].itemGiven || playerData[client].returnedIdleTime < 0.5 ) return Plugin_Continue; + static char name[32]; + GetEntityClassname(weapon, name, sizeof(name)); + if(StrEqual(name, "weapon_first_aid_kit", true)) { + // Use extra kit in checkpoints + if((L4D_IsInFirstCheckpoint(client) || L4D_IsInLastCheckpoint(client))) { + return UseExtraKit(client) ? Plugin_Handled : Plugin_Continue; + } else if(L4D_IsMissionFinalMap()) { + // If kit is in finale zone, then use extra kits here: + float pos[3]; + GetEntPropVector(weapon, Prop_Data, "m_vecOrigin", pos); + Address address = L4D_GetNearestNavArea(pos); + if(address != Address_Null) { + int attributes = L4D_GetNavArea_SpawnAttributes(address); + if(attributes & NAV_SPAWN_FINALE) { + return UseExtraKit(client) ? Plugin_Handled : Plugin_Continue; + } + } + } + } + return Plugin_Continue; +} + +void Event_ItemPickup(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && GetClientTeam(client) == 2 && !IsFakeClient(client)) { + UpdatePlayerInventory(client); + SaveInventory(client); + } + +} + +public Action L4D_OnIsTeamFull(int team, bool &full) { + if(team == 2 && full) { + full = false; + return Plugin_Changed; + } + return Plugin_Continue; +} + +#define TIER2_WEAPON_COUNT 9 +char TIER2_WEAPONS[9][] = { + "weapon_autoshotgun", + "weapon_rifle_ak47", + "weapon_sniper_military", + "weapon_rifle_sg552", + "weapon_rifle_desert", + "weapon_sniper_scout", + "weapon_rifle", + "weapon_hunting_rifle", + "weapon_shotgun_spas" +}; + +Action Timer_SetupNewClient(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client == 0) return Plugin_Handled; + if(HasSavedInventory(client)) { + PrintDebug(DEBUG_GENERIC, "%N has existing inventory", client); + // TODO: restore + } + + GiveWeapon(client, "weapon_first_aid_kit", 0.1); + + // Iterate all clients and get: + // a) the client with the lowest intensity + // b) every survivor's tier2 / tier1 / secondary weapons + int lowestClient = -1; + float lowestIntensity; + char weaponName[64]; + + ArrayList tier2Weapons = new ArrayList(ByteCountToCells(32)); + ArrayList tier1Weapons = new ArrayList(ByteCountToCells(32)); + ArrayList secondaryWeapons = new ArrayList(ByteCountToCells(32)); + + for(int i = 1; i <= MaxClients; i++) { + if(i != client && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + int wpn = GetPlayerWeaponSlot(i, 0); + if(wpn > 0) { + GetEdictClassname(wpn, weaponName, sizeof(weaponName)); + // Ignore grenade launcher / m60, not a normal weapon to give + if(!StrEqual(weaponName, "weapon_grenade_launcher") && !StrEqual(weaponName, "weapon_rifle_m60")) { + for(int j = 0; j < TIER2_WEAPON_COUNT; j++) { + if(StrEqual(TIER2_WEAPONS[j], weaponName)) { + tier2Weapons.PushString(weaponName); + break; + } + } + tier1Weapons.PushString(weaponName); + // playerWeapons.PushString(weaponName); + } + } + + wpn = GetPlayerWeaponSlot(i, 1); + if(wpn > 0) { + GetEdictClassname(wpn, weaponName, sizeof(weaponName)); + if(StrEqual(weaponName, "weapon_melee")) { + // Get melee name, won't have weapon_ prefix + GetEntPropString(wpn, Prop_Data, "m_strMapSetScriptName", weaponName, sizeof(weaponName)); + } + secondaryWeapons.PushString(weaponName); + } + + if (!GetEntProp(i, Prop_Send, "m_isHangingFromLedge") && !GetEntProp(client, Prop_Send, "m_isIncapacitated")) { + float intensity = L4D_GetPlayerIntensity(i); + if(intensity < lowestIntensity || lowestClient == -1) { + lowestIntensity = intensity; + lowestClient = i; + } + } + } + } + + // Give player any random t2 weapon, if no one has one, fallback to t1. + if(tier2Weapons.Length > 0) { + tier2Weapons.GetString(GetRandomInt(0, tier2Weapons.Length - 1), weaponName, sizeof(weaponName)); + // Format(weaponName, sizeof(weaponName), "weapon_%s", weaponName); + PrintDebug(DEBUG_SPAWNLOGIC, "Giving new client (%N) tier 2: %s", client, weaponName); + GiveWeapon(client, weaponName, 0.3, 0); + } else if(tier1Weapons.Length > 0) { + // Format(weaponName, sizeof(weaponName), "weapon_%s", TIER1_WEAPONS[GetRandomInt(0, TIER1_WEAPON_COUNT - 1)]); + tier1Weapons.GetString(GetRandomInt(0, tier1Weapons.Length - 1), weaponName, sizeof(weaponName)); + PrintDebug(DEBUG_SPAWNLOGIC, "Giving new client (%N) tier 1: %s", client, weaponName); + GiveWeapon(client, weaponName, 0.6, 0); + } + PrintDebug(DEBUG_SPAWNLOGIC, "%N: Giving random secondary / %d", secondaryWeapons.Length, client); + if(secondaryWeapons.Length > 0) { + secondaryWeapons.GetString(GetRandomInt(0, secondaryWeapons.Length - 1), weaponName, sizeof(weaponName)); + GiveWeapon(client, weaponName, 0.6, 1); + } + + if(lowestClient > 0) { + // Get a position behind the player, but not too far to put them in a wall. + // Hopefully reducing the chance they shot for "appearing" infront of a player + float pos[3]; + GetHorizontalPositionFromClient(lowestClient, -40.0, pos); + TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR); + // Just incase they _are_ in a wall, let the game check: + L4D_WarpToValidPositionIfStuck(client); + } + + delete tier2Weapons; + delete tier1Weapons; + delete secondaryWeapons; + + return Plugin_Handled; +} + +// Gives a player a weapon, clearing their previous and with a configurable delay to prevent issues +void GiveWeapon(int client, const char[] weaponName, float delay = 0.3, int clearSlot = -1) { + if(clearSlot > 0) { + int oldWpn = GetPlayerWeaponSlot(client, clearSlot); + if(oldWpn != -1) { + AcceptEntityInput(oldWpn, "Kill"); + } + } + PrintToServer("%N: Giving %s", client, weaponName); + PrintToConsoleAll("%N: Giving %s", client, weaponName); + DataPack pack; + CreateDataTimer(delay, Timer_GiveWeapon, pack); + pack.WriteCell(GetClientUserId(client)); + pack.WriteString(weaponName); +} + +Action Timer_GiveWeapon(Handle h, DataPack pack) { + pack.Reset(); + int userid = pack.ReadCell(); + int client = GetClientOfUserId(userid); + if(client > 0) { + char wpnName[32]; + pack.ReadString(wpnName, sizeof(wpnName)); + + int realSurvivor = L4D_GetBotOfIdlePlayer(client); + if(realSurvivor <= 0) realSurvivor = client; + CheatCommand(realSurvivor, "give", wpnName, ""); + } + return Plugin_Handled; +} +// First spawn invincibility: +Action Timer_RemoveInvincibility(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0) { + SetEntProp(client, Prop_Send, "m_iHealth", 100); + SDKUnhook(client, SDKHook_OnTakeDamage, OnInvincibleDamageTaken); + } + return Plugin_Handled; +} +Action OnInvincibleDamageTaken(int victim, int& attacker, int& inflictor, float& damage, int& damagetype, int& weapon, float damageForce[3], float damagePosition[3]) { + damage = 0.0; + return Plugin_Stop; +} +// Gives 5+ kit after saferoom loaded: +Action Timer_GiveClientKit(Handle hdl, int user) { + int client = GetClientOfUserId(user); + if(client > 0 && !DoesClientHaveKit(client)) { + UseExtraKit(client); + } + return Plugin_Continue; + +} + +// Gives start of campaign kits +Action Timer_GiveKits(Handle timer) { + GiveStartingKits(); + return Plugin_Continue; +} + +int SpawnItem(const char[] itemName, float pos[3], float ang[3] = NULL_VECTOR) { + static char classname[32]; + Format(classname, sizeof(classname), "weapon_%s", itemName); + int spawner = CreateEntityByName(classname); + if(spawner == -1) return -1; + DispatchKeyValue(spawner, "solid", "6"); + // DispatchKeyValue(entity_weapon, "model", g_bLeft4Dead2 ? g_sWeaponModels2[model] : g_sWeaponModels[model]); + DispatchKeyValue(spawner, "rendermode", "3"); + DispatchKeyValue(spawner, "disableshadows", "1"); + TeleportEntity(spawner, pos, ang, NULL_VECTOR); + DispatchSpawn(spawner); + TeleportEntity(spawner, pos, ang, NULL_VECTOR); + return spawner; +} + +void IncreaseKits(bool inFinale) { + float pos[3]; + int entity = FindEntityByClassname(-1, "weapon_first_aid_kit_spawn"); + if(entity == INVALID_ENT_REFERENCE) { + PrintToServer("[EPI] Warn: No kit spawns (weapon_first_aid_kit_spawn) found (inFinale=%b)", inFinale); + return; + } + int count = 0; + while(g_extraKitsAmount > 0) { + GetEntPropVector(entity, Prop_Data, "m_vecOrigin", pos); + bool result = false; + if(inFinale) { + // Finale + Address address = L4D_GetNearestNavArea(pos); + if(address != Address_Null) { + int attributes = L4D_GetNavArea_SpawnAttributes(address); + if(attributes & NAV_SPAWN_FINALE) { + result = true; + } + } + } else { + // Checkpoint + result = L4D_IsPositionInLastCheckpoint(pos); + } + if(result) { + count++; + // Give it a little chance to nudge itself + pos[0] += GetRandomFloat(-8.0, 8.0); + pos[1] += GetRandomFloat(-8.0, 8.0); + pos[2] += 0.4; + SpawnItem("first_aid_kit", pos); + g_extraKitsAmount--; + } + entity = FindEntityByClassname(entity, "weapon_first_aid_kit_spawn"); + // Loop around + if(entity == INVALID_ENT_REFERENCE) { + entity = -1; + // If we did not find any suitable kits, stop here. + if(count == 0) { + PrintToServer("[EPI] Warn: No valid kit spawns (weapon_first_aid_kit_spawn) found (inFinale=%b)", inFinale); + break; + } + } + } +} + + +char NAV_SPAWN_NAMES[32][] = { + "EMPTY", + "STOP_SCAN", // 1 << 1 + "", + "", + "", + "BATTLESTATION", // 1 << 5 + "FINALE", // 1 << 6 + "PLAYER_START", + "BATTLEFIELD", + "IGNORE_VISIBILITY", + "NOT_CLEARABLE", + "CHECKPOINT", // 1 << 11 + "OBSCURED", + "NO_MOBS", + "THREAT", + "RESCUE_VEHICLE", + "RESCUE_CLOSET", + "ESCAPE_ROUTE", + "DESTROYED_DOOR", + "NOTHREAT", + "LYINGDOWN", // 1 << 20 + "", + "", + "", + "COMPASS_NORTH", // 1 << 24 + "COMPASS_NORTHEAST", + "COMPASS_EAST", + "COMPASS_EASTSOUTH", + "COMPASS_SOUTH", + "COMPASS_SOUTHWEST", + "COMPASS_WEST", + "COMPASS_WESTNORTH" +}; + +void Debug_GetAttributes(int attributes, char[] output, int maxlen) { + output[0] = '\0'; + for(int i = 0; i < 32; i++) { + if(attributes & (1 << i)) { + Format(output, maxlen, "%s %s", output, NAV_SPAWN_NAMES[i]); + } + } +} + +public void OnMapStart() { + char map[32]; + GetCurrentMap(map, sizeof(map)); + // If map starts with c#m#, 98% an official map + g_isOfficialMap = map[0] == 'c' && IsCharNumeric(map[1]) && (map[2] == 'm' || map[3] == 'm'); + g_isCheckpointReached = false; + //If previous round was a failure, restore the amount of kits that were left directly after map transition + if(g_isFailureRound) { + g_extraKitsAmount = g_extraKitsStart; + //give kits if first + if(L4D_IsFirstMapInScenario() && IsEPIActive()) { + GiveStartingKits(); + } + g_isFailureRound = false; + } else { + g_currentChapter++; + } + + if(L4D_IsMissionFinalMap()) { + IncreaseKits(true); + // Disable tank split on hard rain finale + g_extraFinaleTankEnabled = true; + if(StrEqual(map, "c4m5_milltown_escape")) { + g_extraFinaleTankEnabled = false; + } + } + + //Lock the beginning door + if(hMinPlayersSaferoomDoor.FloatValue > 0.0) { + int entity = -1; + while ((entity = FindEntityByClassname(entity, "prop_door_rotating_checkpoint")) != -1 && entity > MaxClients) { + bool isLocked = GetEntProp(entity, Prop_Send, "m_bLocked") == 1; + if(isLocked) { + g_saferoomDoorEnt = EntIndexToEntRef(entity); + AcceptEntityInput(entity, "Open"); + AcceptEntityInput(entity, "Close"); + AcceptEntityInput(entity, "Lock"); + AcceptEntityInput(entity, "ForceClosed"); + SDKHook(entity, SDKHook_Use, Hook_Use); + // Failsafe: + CreateTimer(20.0, Timer_OpenSaferoomDoor, _, TIMER_FLAG_NO_MAPCHANGE); + break; + } + } + + } + + //Hook the end saferoom as event + HookEntityOutput("info_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); + HookEntityOutput("trigger_changelevel", "OnStartTouch", EntityOutput_OnStartTouchSaferoom); + + g_finaleStage = Stage_Inactive; + + L4D2_RunScript(HUD_SCRIPT_CLEAR); + Director_OnMapStart(); + g_areItemsPopulated = false; + CreateTimer(30.0, Timer_Populate); + + if(g_isLateLoaded) { + UpdateSurvivorCount(); + g_isLateLoaded = false; + } +} + +public void OnConfigsExecuted() { + if(hUpdateMinPlayers.BoolValue && hMinPlayers != null) { + hMinPlayers.IntValue = g_realSurvivorCount; + } +} + +public void OnMapEnd() { + g_isFinaleEnding = false; + // Reset the ammo packs, deleting the internal arraylist + for(int i = 0; i < g_ammoPacks.Length; i++) { + ArrayList clients = g_ammoPacks.Get(i, AMMOPACK_USERS); + delete clients; + } + g_ammoPacks.Clear(); + // Reset cabinets: + for(int i = 0; i < sizeof(cabinets); i++) { + cabinets[i].id = 0; + for(int b = 0; b < CABINET_ITEM_BLOCKS; b++) { + cabinets[i].items[b] = 0; + } + } + delete updateHudTimer; + Director_OnMapEnd(); +} + +void Event_FinaleStart(Event event, const char[] name, bool dontBroadcast) { + g_finaleStage = Stage_Active; +} +Action Timer_Populate(Handle h) { + PopulateItems(); + return Plugin_Continue; + +} +public void OnClientSpeaking(int client) { + g_isSpeaking[client] = true; +} +public void OnClientSpeakingEnd(int client) { + g_isSpeaking[client] = false; +} + +public void EntityOutput_OnStartTouchSaferoom(const char[] output, int caller, int client, float time) { + if(!g_isCheckpointReached && client > 0 && client <= MaxClients && IsValidClient(client) && GetClientTeam(client) == 2) { + g_isCheckpointReached = true; + UpdateSurvivorCount(); + if(IsEPIActive()) { + SetExtraKits(g_survivorCount); + IncreaseKits(false); + PrintToServer("[EPI] Player entered saferoom. Extra Kits: %d", g_extraKitsAmount); + } + } +} + +void SetExtraKits(int playerCount) { + int extraPlayers = playerCount - 4; + float averageTeamHP = GetAverageHP(); + if(averageTeamHP <= 30.0) extraPlayers += (extraPlayers / 2); //if perm. health < 30, give an extra 4 on top of the extra + else if(averageTeamHP <= 50.0) extraPlayers += (extraPlayers / 3); //if the team's average health is less than 50 (permament) then give another + //Chance to get an extra kit (might need to be nerfed or restricted to > 50 HP) + if(GetRandomFloat() < 0.3 && averageTeamHP <= 80.0) ++extraPlayers; + + + g_extraKitsAmount += extraPlayers; + g_extraKitsStart = g_extraKitsAmount; +} + +void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) { + if(!g_isFailureRound) g_isFailureRound = true; + g_areItemsPopulated = false; +} + +void Event_MapTransition(Event event, const char[] name, bool dontBroadcast) { + #if defined DEBUG + PrintToServer("Map transition | %d Extra Kits", g_extraKitsAmount); + #endif + g_isLateLoaded = false; + g_extraKitsStart = g_extraKitsAmount; + // Update g_survivorCount, people may have dipped right before transition + UpdateSurvivorCount(); + g_prevPlayerCount = g_survivorCount; +} + +public void OnEntityCreated(int entity, const char[] classname) { + if(StrEqual(classname, "weapon_pain_pills_spawn") || StrEqual(classname, "weapon_first_aid_kit_spawn")) { + SDKHook(entity, SDKHook_SpawnPost, Hook_CabinetItemSpawn); + }else if(StrEqual(classname, "prop_health_cabinet", true)) { + SDKHook(entity, SDKHook_SpawnPost, Hook_CabinetSpawn); + }else if (StrEqual(classname, "upgrade_ammo_explosive") || StrEqual(classname, "upgrade_ammo_incendiary")) { + int index = g_ammoPacks.Push(entity); + g_ammoPacks.Set(index, new ArrayList(1), AMMOPACK_USERS); + SDKHook(entity, SDKHook_Use, OnUpgradePackUse); + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Hooks +/////////////////////////////////////////////////////////////////////////////// + +//TODO: Implement extra kit amount to this +//TODO: Possibly check ammo stash and kit (relv. distance). Would fire on Last Stand 2nd . +Action Hook_CabinetItemSpawn(int entity) { + int cabinet = FindNearestEntityInRange(entity, "prop_health_cabinet", 60.0); + if(cabinet > 0) { + int ci = FindCabinetIndex(cabinet); + //Check for any open block + for(int block = 0; block < CABINET_ITEM_BLOCKS; block++) { + int cabEnt = cabinets[ci].items[block]; + PrintDebug(DEBUG_ANY, "cabinet %d spawner %d block %d: %d", cabinet, entity, block, cabEnt); + if(cabEnt <= 0) { + cabinets[ci].items[block] = entity; + PrintDebug(DEBUG_SPAWNLOGIC, "Adding spawner %d for cabinet %d block %d", entity, cabinet, block); + break; + } + } + //If Cabinet is full, spawner can not be a part of cabinet and is ignored. + } + return Plugin_Handled; +} + +Action Hook_CabinetSpawn(int entity) { + for(int i = 0; i < sizeof(cabinets); i++) { + if(cabinets[i].id == 0) { + cabinets[i].id = entity; + break; + } + } + PrintDebug(DEBUG_SPAWNLOGIC, "Adding cabinet %d", entity); + return Plugin_Handled; +} + +Action OnUpgradePackUse(int entity, int activator, int caller, UseType type, float value) { + if (entity > 2048 || entity <= MaxClients || !IsValidEntity(entity)) return Plugin_Continue; + + int primaryWeapon = GetPlayerWeaponSlot(activator, 0); + if(IsValidEdict(primaryWeapon) && HasEntProp(primaryWeapon, Prop_Send, "m_upgradeBitVec")) { + int index = g_ammoPacks.FindValue(entity, AMMOPACK_ENTID); + if(index == -1) return Plugin_Continue; + + ArrayList clients = g_ammoPacks.Get(index, AMMOPACK_USERS); + if(clients.FindValue(activator) > -1) { + ClientCommand(activator, "play ui/menu_invalid.wav"); + return Plugin_Handled; + } + + static char classname[32]; + int upgradeBits = GetEntProp(primaryWeapon, Prop_Send, "m_upgradeBitVec"), ammo; + + //Get the new flag bits + GetEntityClassname(entity, classname, sizeof(classname)); + //SetUsedBySurvivor(activator, entity); + int newFlags = StrEqual(classname, "upgrade_ammo_explosive") ? L4D2_WEPUPGFLAG_EXPLOSIVE : L4D2_WEPUPGFLAG_INCENDIARY; + if(upgradeBits & L4D2_WEPUPGFLAG_LASER == L4D2_WEPUPGFLAG_LASER) newFlags |= L4D2_WEPUPGFLAG_LASER; + SetEntProp(primaryWeapon, Prop_Send, "m_upgradeBitVec", newFlags); + GetEntityClassname(primaryWeapon, classname, sizeof(classname)); + + if(!weaponMaxClipSizes.GetValue(classname, ammo)) { + if(StrEqual(classname[7], "grenade_launcher", true)) ammo = 1; + else if(StrEqual(classname[7], "rifle_m60", true)) ammo = 150; + else { + int currentAmmo = GetEntProp(primaryWeapon, Prop_Send, "m_iClip1"); + if(currentAmmo > 10) ammo = 10; + } + } + + if(GetEntProp(primaryWeapon, Prop_Send, "m_iClip1") < ammo) { + SetEntProp(primaryWeapon, Prop_Send, "m_iClip1", ammo); + } + SetEntProp(primaryWeapon, Prop_Send, "m_nUpgradedPrimaryAmmoLoaded", ammo); + clients.Push(activator); + ClientCommand(activator, "play player/orch_hit_csharp_short.wav"); + + if(clients.Length >= g_survivorCount) { + AcceptEntityInput(entity, "kill"); + delete clients; + g_ammoPacks.Erase(index); + } + return Plugin_Handled; + } + return Plugin_Continue; +} + +public Action Hook_Use(int entity, int activator, int caller, UseType type, float value) { + SetEntProp(entity, Prop_Send, "m_bLocked", 1); + AcceptEntityInput(entity, "Close"); + ClientCommand(activator, "play ui/menu_invalid.wav"); + PrintHintText(activator, "Waiting for players"); + return Plugin_Handled; +} + +///////////////////////////////////// +/// TIMERS +//////////////////////////////////// + +//TODO: In future, possibly have a total percentage of spawns that are affected instead on a per-level +//TODO: In future, also randomize what items are selected? Two loops: +/* + first loop pushes any valid _spawns into dynamic array + while / for loop that runs until X amount affected (based on % of GetEntityCount()). + + Prioritize first aid kits somehow? Or split two groups: "utility" (throwables, kits, pill/shots), and "weapon" (all other spawns) +*/ + +Action Timer_OpenSaferoomDoor(Handle h) { + UnlockDoor(1); + return Plugin_Continue; +} + +void UnlockDoor(int flag) { + int entity = EntRefToEntIndex(g_saferoomDoorEnt); + if(entity > 0) { + PrintDebug(DEBUG_GENERIC, "Door unlocked, flag %d", flag); + AcceptEntityInput(entity, "Unlock"); + SetEntProp(entity, Prop_Send, "m_bLocked", 0); + SDKUnhook(entity, SDKHook_Use, Hook_Use); + if(hSaferoomDoorAutoOpen.IntValue & flag) { + AcceptEntityInput(entity, "Open"); + } + SetVariantString("Unlock"); + AcceptEntityInput(entity, "SetAnimation"); + g_saferoomDoorEnt = INVALID_ENT_REFERENCE; + PopulateItems(); + } +} + +Action Timer_UpdateHud(Handle h) { + if(hEPIHudState.IntValue == 1 && !g_isGamemodeAllowed) { + PrintToServer("[EPI] Gamemode not whitelisted, stopping (hudState=%d, g_survivorCount=%d, g_realSurvivorCount=%d)", hEPIHudState.IntValue, g_survivorCount, g_realSurvivorCount); + L4D2_RunScript(HUD_SCRIPT_CLEAR); + updateHudTimer = null; + return Plugin_Stop; + } + // TODO: Turn it off when state == 1 + // int threshold = hEPIHudState.IntValue == 1 ? 4 : 0; + // if(hEPIHudState.IntValue == 1 && abmExtraCount < threshold) { //|| broke && abmExtraCount < threshold + // PrintToServer("[EPI] Less than threshold (%d), stopping hud timer (hudState=%d, abmExtraCount=%d)", threshold, hEPIHudState.IntValue, abmExtraCount); + // L4D2_RunScript(HUD_SCRIPT_CLEAR); + // updateHudTimer = null; + // return Plugin_Stop; + // } + + if(cvEPIHudFlags.IntValue & 2) { + hudModeTicks++; + if(hudModeTicks > (showHudPingMode ? 8 : 20)) { + hudModeTicks = 0; + showHudPingMode = !showHudPingMode; + } + } + + static char players[512], data[32], prefix[16]; + players[0] = '\0'; + // TODO: name scrolling + // TODO: name cache (hook name change event), strip out invalid + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + data[0] = '\0'; + prefix[0] = '\0'; + int health = GetClientRealHealth(i); + int client = i; + if(IsFakeClient(i) && HasEntProp(i, Prop_Send, "m_humanSpectatorUserID")) { + client = GetClientOfUserId(GetEntProp(i, Prop_Send, "m_humanSpectatorUserID")); + if(client > 0) + Format(prefix, 5 + HUD_NAME_LENGTH, "AFK %s", playerData[client].nameCache[playerData[client].scrollIndex]); + else + Format(prefix, HUD_NAME_LENGTH, "%N", i); + } else { + Format(prefix, HUD_NAME_LENGTH, "%s", playerData[client].nameCache[playerData[client].scrollIndex]); + } + if(g_isSpeaking[i]) + Format(prefix, HUD_NAME_LENGTH, "🔊%s", prefix); + + playerData[client].AdvanceScroll(); + + if(showHudPingMode) { + if(client == 0) continue; + int ping = L4D_GetPlayerResourceData(client, L4DResource_Ping); + Format(data, sizeof(data), "%d ms", ping); + } else { + if(!IsPlayerAlive(i)) + Format(data, sizeof(data), "xx"); + else if(GetEntProp(i, Prop_Send, "m_bIsOnThirdStrike") == 1) + Format(data, sizeof(data), "+%d b&w %s%s%s", health, items[i].throwable, items[i].usable, items[i].consumable); + else if(GetEntProp(i, Prop_Send, "m_isIncapacitated") == 1) + Format(data, sizeof(data), "+%d --", health); + else + Format(data, sizeof(data), "+%d %s%s%s", health, items[i].throwable, items[i].usable, items[i].consumable); + } + + Format(players, sizeof(players), "%s%s %s\\n", players, prefix, data); + } + } + + if(players[0] == '\0') { + L4D2_RunScript(HUD_SCRIPT_CLEAR); + updateHudTimer = null; + return Plugin_Stop; + } + + if(hEPIHudState.IntValue < 3) { + // PrintToConsoleAll(HUD_SCRIPT_DATA, players); + RunVScriptLong(HUD_SCRIPT_DATA, players); + } else { + PrintHintTextToAll("DEBUG HUD TIMER"); + RunVScriptLong(HUD_SCRIPT_DEBUG, players); + } + + return Plugin_Continue; +} + +/////////////////////////////////////////////////////////////////////////////// +// Methods +/////////////////////////////////////////////////////////////////////////////// + +void PopulateItems() { + if(g_areItemsPopulated) return; + UpdateSurvivorCount(); + if(!IsEPIActive()) return; + + g_areItemsPopulated = true; + + //Generic Logic + float percentage = hExtraItemBasePercentage.FloatValue * (g_survivorCount - 4); + PrintToServer("[EPI] Populating extra items based on player count (%d-4) | Percentage %.2f%%", g_survivorCount, percentage * 100); + PrintToConsoleAll("[EPI] Populating extra items based on player count (%d-4) | Percentage %.2f%%", g_survivorCount, percentage * 100); + char classname[64]; + int affected = 0; + + for(int i = MaxClients + 1; i < 2048; i++) { + if(IsValidEntity(i)) { + GetEntityClassname(i, classname, sizeof(classname)); + if(StrContains(classname, "_spawn", true) > -1 + && StrContains(classname, "zombie", true) == -1 + && StrContains(classname, "scavenge", true) == -1 + && HasEntProp(i, Prop_Data, "m_itemCount") + ) { + int count = GetEntProp(i, Prop_Data, "m_itemCount"); + if(count > 0 && GetURandomFloat() < percentage) { + SetEntProp(i, Prop_Data, "m_itemCount", ++count); + ++affected; + } + } + } + } + PrintDebug(DEBUG_SPAWNLOGIC, "Incremented counts for %d items", affected); + + PopulateCabinets(); +} + +void PopulateCabinets() { + char classname[64]; + //Cabinet logic + PrintDebug(DEBUG_SPAWNLOGIC, "Populating cabinets with extra items"); + int spawner, count; + for(int i = 0; i < sizeof(cabinets); i++) { + if(cabinets[i].id == 0 || !IsValidEntity(cabinets[i].id)) break; + GetEntityClassname(cabinets[i].id, classname, sizeof(classname)); + if(!StrEqual(classname, "prop_health_cabinet")) { + PrintToServer("Cabinet %d (ent %d) is not a valid entity, is %s. Skipping", i, cabinets[i].id, classname); + cabinets[i].id = 0; + continue; + } + int spawnCount = GetEntProp(cabinets[i].id, Prop_Data, "m_pillCount"); + int extraAmount = RoundToCeil(float(g_survivorCount) * (float(spawnCount)/4.0) - spawnCount); + bool hasSpawner; + while(extraAmount > 0) { + //FIXME: spawner is sometimes invalid entity. Ref needed? + for(int block = 0; block < CABINET_ITEM_BLOCKS; block++) { + spawner = cabinets[i].items[block]; + if(spawner > 0) { + if(!HasEntProp(spawner, Prop_Data, "m_itemCount")) continue; + hasSpawner = true; + count = GetEntProp(spawner, Prop_Data, "m_itemCount") + 1; + SetEntProp(spawner, Prop_Data, "m_itemCount", count); + if(--extraAmount == 0) break; + } + } + //Incase cabinet is empty + if(!hasSpawner) break; + } + } +} + +///////////////////////////////////// +/// Stocks +//////////////////////////////////// +bool IsGamemodeAllowed() { + char buffer[128]; + cvEPIGamemodes.GetString(buffer, sizeof(buffer)); + return StrContains(buffer, g_currentGamemode, false) > -1; +} + +void DropDroppedInventories() { + StringMapSnapshot snapshot = pInv.Snapshot(); + static PlayerInventory inv; + static char buffer[32]; + int time = GetTime(); + for(int i = 0; i < snapshot.Length; i++) { + snapshot.GetKey(i, buffer, sizeof(buffer)); + pInv.GetArray(buffer, inv, sizeof(inv)); + if(time - inv.timestamp > PLAYER_DROP_TIMEOUT_SECONDS) { + PrintDebug(DEBUG_GENERIC, "[EPI] Dropping inventory for %s", buffer); + pInv.Remove(buffer); + } + } +} +// Used for EPI hud +void UpdatePlayerInventory(int client) { + static char item[16]; + if(GetClientWeaponName(client, 2, item, sizeof(item))) { + items[client].throwable[0] = CharToUpper(item[7]); + if(items[client].throwable[0] == 'V') { + items[client].throwable[0] = 'B'; //Replace [V]omitjar with [B]ile + } + items[client].throwable[1] = '\0'; + } else { + items[client].throwable[0] = '\0'; + } + + if(GetClientWeaponName(client, 3, item, sizeof(item))) { + items[client].usable[0] = CharToUpper(item[7]); + items[client].usable[1] = '\0'; + if(items[client].throwable[0] == 'F') { + items[client].throwable[0] = '+'; //Replace [V]omitjar with [B]ile + } + } else { + items[client].usable[0] = '-'; + items[client].usable[1] = '\0'; + } + + if(GetClientWeaponName(client, 4, item, sizeof(item))) { + items[client].consumable[0] = CharToUpper(item[7]); + items[client].consumable[1] = '\0'; + } else { + items[client].consumable[0] = '\0'; + } +} + +Action Timer_SaveInventory(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0) { + // Force save to bypass our timeout + SaveInventory(client, true); + } + return Plugin_Stop; +} + +void SaveInventory(int client, bool force = false) { + int time = GetTime(); + if(!force) { + if(time - playerData[client].joinTime < MIN_JOIN_TIME) return; + // Queue their inventory to be saved after a timeout. + // Any time a save happens between prev save and timeout will delay the timeout. + // This should ensure that the saved inventory is most of the time up-to-date + if(g_saveTimer[client] != null) + delete g_saveTimer[client]; + g_saveTimer[client] = CreateTimer(INV_SAVE_TIME, Timer_SaveInventory, GetClientUserId(client)); + } else { + g_saveTimer[client] = null; + } + PlayerInventory inventory; + inventory.timestamp = time; + inventory.isAlive = IsPlayerAlive(client); + playerData[client].state = State_Active; + GetClientAbsOrigin(client, inventory.location); + + inventory.primaryHealth = GetClientHealth(client); + GetClientModel(client, inventory.model, 64); + inventory.survivorType = GetEntProp(client, Prop_Send, "m_survivorCharacter"); + + int weapon; + static char buffer[32]; + for(int i = 5; i >= 0; i--) { + weapon = GetPlayerWeaponSlot(client, i); + inventory.itemID[i] = IdentifyWeapon(weapon); + // If slot 1 is melee, get the melee ID + if(i == 1 && inventory.itemID[i] == WEPID_MELEE) { + inventory.meleeID = IdentifyMeleeWeapon(weapon); + } + } + if(inventory.itemID[0] != WEPID_NONE) + inventory.lasers = GetEntProp(weapon, Prop_Send, "m_upgradeBitVec") == 4; + + GetClientAuthId(client, AuthId_Steam3, buffer, sizeof(buffer)); + pInv.SetArray(buffer, inventory, sizeof(inventory)); + g_lastInvSave[client] = GetTime(); +} + +void RestoreInventory(int client, PlayerInventory inventory) { + PrintToConsoleAll("[debug:RINV] health=%d primaryID=%d secondID=%d throw=%d kit=%d pill=%d surv=%d", inventory.primaryHealth, inventory.itemID[0], inventory.itemID[1], inventory.itemID[2], inventory.itemID[3], inventory.itemID[4], inventory.itemID[5], inventory.survivorType); + + if(inventory.model[0] != '\0') + SetEntityModel(client, inventory.model); + SetEntProp(client, Prop_Send, "m_survivorCharacter", inventory.survivorType); + + char buffer[32]; + if(inventory.isAlive) { + SetEntProp(client, Prop_Send, "m_iHealth", inventory.primaryHealth); + + int weapon; + for(int i = 5; i >= 0; i--) { + WeaponId id = inventory.itemID[i]; + if(id != WEPID_NONE) { + if(id == WEPID_MELEE) { + GetWeaponName(id, buffer, sizeof(buffer)); + } else { + GetMeleeWeaponName(inventory.meleeID, buffer, sizeof(buffer)); + } + weapon = GiveClientWeapon(client, buffer); + } + } + if(inventory.lasers) { + SetEntProp(weapon, Prop_Send, "m_upgradeBitVec", 4); + } + } +} + +bool GetLatestInventory(int client, PlayerInventory inventory) { + static char buffer[32]; + GetClientAuthId(client, AuthId_Steam3, buffer, sizeof(buffer)); + return pInv.GetArray(buffer, inventory, sizeof(inventory)); +} + +bool GetInventory(const char[] steamid, PlayerInventory inventory) { + return pInv.GetArray(steamid, inventory, sizeof(inventory)); +} + +bool HasSavedInventory(int client) { + char buffer[32]; + GetClientAuthId(client, AuthId_Steam3, buffer, sizeof(buffer)); + return pInv.ContainsKey(buffer); +} + +bool DoesInventoryDiffer(int client) { + static char buffer[32]; + GetClientAuthId(client, AuthId_Steam3, buffer, sizeof(buffer)); + PlayerInventory inventory; + if(!pInv.GetArray(buffer, inventory, sizeof(inventory)) || inventory.timestamp == 0) { + return false; + } + + WeaponId currentPrimary = IdentifyWeapon(GetPlayerWeaponSlot(client, 0)); + WeaponId currentSecondary = IdentifyWeapon(GetPlayerWeaponSlot(client, 1)); + WeaponId storedPrimary = inventory.itemID[0]; + WeaponId storedSecondary = inventory.itemID[1]; + + return currentPrimary != storedPrimary || currentSecondary != storedSecondary; +} + +bool IsEPIActive() { + return g_epiEnabled; +} +/* +[Debug] UpdateSurvivorCount: total=4 real=4 active=4 +[Debug] UpdateSurvivorCount: total=4 real=4 active=4 +Player no longer idle +[Debug] UpdateSurvivorCount: total=5 real=4 active=5 +[Debug] UpdateSurvivorCount: total=4 real=4 active=4 +Player no longer idle +*/ +void UpdateSurvivorCount() { + #if defined DEBUG_FORCE_PLAYERS + g_survivorCount = DEBUG_FORCE_PLAYERS; + g_realSurvivorCount = DEBUG_FORCE_PLAYERS; + g_epiEnabled = g_realSurvivorCount > 4 && g_isGamemodeAllowed; + return; + #endif + if(g_forcedSurvivorCount) return; // Don't update if forced + int countTotal = 0, countReal = 0, countActive = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + // Count idle player's bots as well + if(!IsFakeClient(i) || L4D_GetIdlePlayerOfBot(i) > 0) { + countReal++; + } + // FIXME: counting idle players for a brief tick + countTotal++; + if(playerData[i].state == State_Active) { + countActive++; + } + } + } + g_survivorCount = countTotal; + g_realSurvivorCount = countReal; + // PrintDebug(DEBUG_GENERIC, "UpdateSurvivorCount: total=%d real=%d active=%d", countTotal, countReal, countActive); + // Temporarily for now use g_realSurvivorCount, as players joining have a brief second where they are 5 players + + // 1 = 5+ official + // 2 = 5+ any map + // 3 = always on + bool isActive = g_isGamemodeAllowed; + if(isActive && cvEPIEnabledMode.IntValue != 3) { + // Enable only if mode is 2 or is official map AND 5+ + isActive = (g_isOfficialMap || cvEPIEnabledMode.IntValue == 2) && g_realSurvivorCount > 4; + } + g_epiEnabled = isActive; + SetFFFactor(g_epiEnabled); +} + +void SetFFFactor(bool enabled) { + static float prevValue; + // Restore the previous value (we use the value for the calculations of new value) + if(g_ffFactorCvar == null) return; // Ignore invalid difficulties + g_ffFactorCvar.FloatValue = prevValue; + if(enabled) { + prevValue = g_ffFactorCvar.FloatValue; + g_ffFactorCvar.FloatValue = g_ffFactorCvar.FloatValue - ((g_realSurvivorCount - 4) * cvFFDecreaseRate.FloatValue); + if(g_ffFactorCvar.FloatValue < 0.01) { + g_ffFactorCvar.FloatValue = 0.01; + } + } +} + +stock int FindFirstSurvivor() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + return i; + } + } + return -1; +} + +stock void GiveStartingKits() { + int skipLeft = 4; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + //Skip at least the first 4 players, as they will pickup default kits. + //If player somehow already has it ,also skip them. + if(skipLeft > 0 || DoesClientHaveKit(i)) { + --skipLeft; + continue; + } else { + int item = GivePlayerItem(i, "weapon_first_aid_kit"); + EquipPlayerWeapon(i, item); + } + } + } +} + +stock bool AreAllClientsReady() { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsClientInGame(i)) { + return false; + } + } + return true; +} + +stock bool DoesClientHaveKit(int client) { + if(IsClientConnected(client) && IsClientInGame(client)) { + char wpn[32]; + if(GetClientWeaponName(client, 3, wpn, sizeof(wpn))) + return StrEqual(wpn, "weapon_first_aid_kit"); + } + return false; +} + +stock bool UseExtraKit(int client) { + if(g_extraKitsAmount > 0) { + playerData[client].itemGiven = true; + int ent = GivePlayerItem(client, "weapon_first_aid_kit"); + EquipPlayerWeapon(client, ent); + playerData[client].itemGiven = false; + if(--g_extraKitsAmount <= 0) { + g_extraKitsAmount = 0; + } + return true; + } + return false; +} + +stock void PrintDebug(int level, const char[] format, any ... ) { + #if defined DEBUG_LEVEL + if(level <= DEBUG_LEVEL) { + char buffer[256]; + VFormat(buffer, sizeof(buffer), format, 3); + PrintToServer("[Debug] %s", buffer); + PrintToConsoleAll("[Debug] %s", buffer); + } + #endif +} +stock float GetAverageHP() { + int totalHP, clients; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + totalHP += GetClientHealth(i); + ++clients; + } + } + return float(totalHP) / float(clients); +} + +stock int GetClientRealHealth(int client) { + //First filter -> Must be a valid client, successfully in-game and not an spectator (The dont have health). + if(!client || !IsValidEntity(client) + || !IsClientInGame(client) + || !IsPlayerAlive(client) + || IsClientObserver(client) + ) { + return -1; + } + + //If the client is not on the survivors team, then just return the normal client health. + if(GetClientTeam(client) != 2) { + return GetClientHealth(client); + } + + //First, we get the amount of temporal health the client has + float buffer = GetEntPropFloat(client, Prop_Send, "m_healthBuffer"); + + //We declare the permanent and temporal health variables + float TempHealth; + int PermHealth = GetClientHealth(client); + + //In case the buffer is 0 or less, we set the temporal health as 0, because the client has not used any pills or adrenaline yet + if(buffer <= 0.0) { + TempHealth = 0.0; + } else { + //In case it is higher than 0, we proceed to calculate the temporl health + //This is the difference between the time we used the temporal item, and the current time + float difference = GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime"); + + //We get the decay rate from this convar (Note: Adrenaline uses this value) + float decay = GetConVarFloat(FindConVar("pain_pills_decay_rate")); + + //This is a constant we create to determine the amount of health. This is the amount of time it has to pass + //before 1 Temporal HP is consumed. + float constant = 1.0 / decay; + + //Then we do the calcs + TempHealth = buffer - (difference / constant); + } + + //If the temporal health resulted less than 0, then it is just 0. + if(TempHealth < 0.0) { + TempHealth = 0.0; + } + + //Return the value + return RoundToFloor(PermHealth + TempHealth); +} + +int FindCabinetIndex(int cabinetId) { + for(int i = 0; i < sizeof(cabinets); i++) { + if(cabinets[i].id == cabinetId) return i; + } + return -1; +} + +stock void RunVScriptLong(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[2048]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} + +// Gets a position (from a nav area) +stock bool GetIdealPositionInSurvivorFlow(int target, float pos[3]) { + static float ang[3]; + int client = GetLowestFlowSurvivor(target); + if(client > 0) { + GetClientAbsOrigin(client, pos); + GetClientAbsAngles(client, ang); + ang[2] = -ang[2]; + TR_TraceRayFilter(pos, ang, MASK_SHOT, RayType_Infinite, Filter_GroundOnly); + if(TR_DidHit()) { + TR_GetEndPosition(pos); + return true; + } else { + return false; + } + } + return false; +} + +bool Filter_GroundOnly(int entity, int mask) { + return entity == 0; +} + +stock int GetLowestFlowSurvivor(int ignoreTarget = 0) { + int client = L4D_GetHighestFlowSurvivor(); + if(client != ignoreTarget) { + return client; + } else { + client = -1; + float lowestFlow = L4D2Direct_GetFlowDistance(client); + for(int i = 1; i <= MaxClients; i++) { + if(ignoreTarget != i && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + if(L4D2Direct_GetFlowDistance(i) < lowestFlow) { + client = i; + lowestFlow = L4D2Direct_GetFlowDistance(i); + } + } + } + return client; + } +} + +// Get the farthest ahead survivor, but ignoring ignoreTarget +stock int GetHighestFlowSurvivor(int ignoreTarget = 0) { + int client = L4D_GetHighestFlowSurvivor(); + if(client != ignoreTarget) { + return client; + } else { + client = -1; + float highestFlow = L4D2Direct_GetFlowDistance(client); + for(int i = 1; i <= MaxClients; i++) { + if(ignoreTarget != i && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + float dist = L4D2Direct_GetFlowDistance(i); + if(dist > highestFlow) { + client = i; + highestFlow = dist; + } + } + } + return client; + } +} + + +stock float GetSurvivorFlowDifference() { + int client = L4D_GetHighestFlowSurvivor(); + float highestFlow = L4D2Direct_GetFlowDistance(client); + client = GetLowestFlowSurvivor(); + return highestFlow - L4D2Direct_GetFlowDistance(client); +} + +Action Timer_Kick(Handle h, int bot) { + KickClient(bot); + return Plugin_Handled; +} + +enum DiceBias { + BIAS_LEFT = -1, + BIAS_RIGHT = 1 +} +int DiceRoll(int min, int max, int dices = 2, DiceBias bias) { + int compValue = -1; + for(int i = 0; i < dices; i++) { + int value = RoundToFloor(GetURandomFloat() * (max - min) + min); + if(bias == BIAS_LEFT) { + if(value < compValue || compValue == -1) { + compValue = value; + } + } else { + if(value > compValue || compValue == -1) { + compValue = value; + } + } + } + return compValue; +} \ No newline at end of file diff --git a/scripting/l4d2_feedthetrolls.sp b/scripting/l4d2_feedthetrolls.sp new file mode 100644 index 0000000..b4bea0b --- /dev/null +++ b/scripting/l4d2_feedthetrolls.sp @@ -0,0 +1,234 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define MAIN_TIMER_INTERVAL_S 3.5 +#define PLUGIN_VERSION "1.0" +#define THROWITALL_INTERVAL 30.0 + +#include +#include +#include +#include +#include +#tryinclude +#tryinclude +#include +#include +#include +#tryinclude + +public Plugin myinfo = +{ + name = "L4D2 Feed The Trolls", + author = "jackzmc", + description = "https://forums.alliedmods.net/showthread.php?t=325331", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + CreateNative("ApplyTroll", Native_ApplyTroll); + return APLRes_Success; +} + + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + LoadTranslations("common.phrases"); + + g_PlayerMarkedForward = new GlobalForward("OnTrollMarked", ET_Ignore, Param_Cell, Param_Cell); + g_TrollAppliedForward = new GlobalForward("OnTrollApplied", ET_Ignore, Param_Cell, Param_Cell); + + + // Load core things (trolls & phrases): + REPLACEMENT_PHRASES = new StringMap(); + TYPOS_DICT = new StringMap(); + LoadPhrases(); + LoadTypos(); + SetupTrolls(); + SetupsTrollCombos(); + + CreateTimer(1.0, Timer_DecreaseAntiRush, TIMER_REPEAT); + + g_spSpawnQueue = new ArrayList(sizeof(SpecialSpawnRequest)); + + // Witch target overwrite stuff: + GameData data = new GameData("feedthetrolls"); + StartPrepSDKCall(SDKCall_Raw); + PrepSDKCall_SetFromConf(data, SDKConf_Signature, "WitchAttack::WitchAttack"); + PrepSDKCall_AddParameter(SDKType_CBaseEntity, SDKPass_Pointer, VDECODE_FLAG_ALLOWNULL | VDECODE_FLAG_ALLOWWORLD); + g_hWitchAttack = EndPrepSDKCall(); + delete data; + + hAllowEnemyTeam = CreateConVar("sm_ftt_select_enemy", "0", "Allow applying trolls to enemy teams", FCVAR_NONE, true, 0.0, true, 1.0); + hAutoPunish = CreateConVar("sm_ftt_autopunish_action", "0", "Setup automatic punishment of players. Add bits together\n0=Disabled, 1=Tank magnet, 2=Special magnet, 4=Swarm, 8=InstantVomit", FCVAR_NONE, true, 0.0); + hAutoPunishExpire = CreateConVar("sm_ftt_autopunish_expire", "0", "How many minutes of gametime until autopunish is turned off? 0 for never.", FCVAR_NONE, true, 0.0); + hMagnetTargetMode = CreateConVar("sm_ftt_magnet_targetting", "6", "How does the specials target players. Add bits together\n0=Incapped are ignored, 1=Specials targets incapped, 2=Tank targets incapped 4=Witch targets incapped"); + hShoveFailChance = CreateConVar("sm_ftt_shove_fail_chance", "0.65", "The % chance that a shove fails", FCVAR_NONE, true, 0.0, true, 1.0); + hBadThrowHitSelf = CreateConVar("sm_ftt_badthrow_fail_chance", "1", "The % chance that on a throw, they will instead hit themselves. 0 to disable", FCVAR_NONE, true, 0.0, true, 1.0); + hBotReverseFFDefend = CreateConVar("sm_ftt_bot_defend", "0", "Should bots defend themselves?\n0 = OFF\n1 = Will retaliate against non-admins\n2 = Anyone", FCVAR_NONE, true, 0.0, true, 2.0); + hAntirushBaseFreq = CreateConVar("sm_ftt_antirush_freq_base", "24", "The base frequency of anti-rush", FCVAR_NONE, true, 0.0); + hAntirushIncFreq = CreateConVar("sm_ftt_antirush_freq_inc", "1", "The incremental frequency of anti-rush", FCVAR_NONE, true, 0.0); + hBotDefendChance = CreateConVar("sm_ftt_bot_defend_chance", "0.75", "% Chance bots will defend themselves.", FCVAR_NONE, true, 0.0, true, 1.0); + + hSbFriendlyFire = FindConVar("sb_friendlyfire"); + + if(hBotReverseFFDefend.IntValue > 0) hSbFriendlyFire.BoolValue = true; + hBotReverseFFDefend.AddChangeHook(Change_BotDefend); + + RegAdminCmd("sm_ftl", Command_ListTheTrolls, ADMFLAG_GENERIC, "Lists all the trolls currently ingame."); + RegAdminCmd("sm_ftm", Command_ListModes, ADMFLAG_GENERIC, "Lists all the troll modes and their description"); + RegAdminCmd("sm_ftr", Command_ResetUser, ADMFLAG_GENERIC, "Resets user of any troll effects."); + RegAdminCmd("sm_fta", Command_ApplyUser, ADMFLAG_KICK, "Apply a troll mod to a player, or shows menu if no parameters."); + RegAdminCmd("sm_ftas", Command_ApplyUserSilent, ADMFLAG_ROOT, "Apply a troll mod to a player, or shows menu if no parameters."); + RegAdminCmd("sm_ftt", Command_FeedTheTrollMenu, ADMFLAG_GENERIC, "Opens a list that shows all the commands"); + RegAdminCmd("sm_mark", Command_MarkPendingTroll, ADMFLAG_KICK, "Marks a player as to be banned on disconnect"); + RegAdminCmd("sm_ftp", Command_FeedTheCrescendoTroll, ADMFLAG_KICK, "Applies a manual punish on the last crescendo activator"); + RegAdminCmd("sm_ftc", Command_ApplyComboTrolls, ADMFLAG_KICK, "Applies predefined combinations of trolls"); + #if defined _actions_included + RegAdminCmd("sm_witch_attack", Command_WitchAttack, ADMFLAG_BAN, "Makes all witches target a player"); + #endif + RegAdminCmd("sm_insta", Command_InstaSpecial, ADMFLAG_KICK, "Spawns a special that targets them, close to them."); + RegAdminCmd("sm_stagger", Command_Stagger, ADMFLAG_KICK, "Stagger a player"); + RegAdminCmd("sm_inface", Command_InstaSpecialFace, ADMFLAG_KICK, "Spawns a special that targets them, right in their face."); + RegAdminCmd("sm_bots_attack", Command_BotsAttack, ADMFLAG_BAN, "Instructs all bots to attack a player until they have X health."); + RegAdminCmd("sm_scharge", Command_SmartCharge, ADMFLAG_BAN, "Auto Smart charge"); + RegAdminCmd("sm_healbots", Command_HealTarget, ADMFLAG_BAN, "Make bots heal a player"); + RegAdminCmd("sm_rff", Command_SetReverseFF, ADMFLAG_KICK, "Set reverse FF on player"); + RegAdminCmd("sm_magnet", Command_SetMagnetShortcut, ADMFLAG_KICK, ""); + RegAdminCmd("sm_csplat", Command_CarSplat, ADMFLAG_KICK, ""); + + HookEvent("player_spawn", Event_PlayerSpawn); + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + HookEvent("player_death", Event_PlayerDeath); + HookEvent("triggered_car_alarm", Event_CarAlarm); + HookEvent("witch_harasser_set", Event_WitchVictimSet); + HookEvent("door_open", Event_DoorToggle); + HookEvent("door_close", Event_DoorToggle); + HookEvent("adrenaline_used", Event_SecondaryHealthUsed); + HookEvent("pills_used", Event_SecondaryHealthUsed); + HookEvent("entered_spit", Event_EnteredSpit); + HookEvent("bot_player_replace", Event_BotPlayerSwap); + HookEvent("heal_success", Event_HealSuccess); + HookEvent("player_incapacitated", Event_Incapped); + + AddNormalSoundHook(SoundHook); + + AutoExecConfig(true, "l4d2_feedthetrolls"); + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + SDKHook(i, SDKHook_OnTakeDamage, Event_TakeDamage); + } + } +} +/////////////////////////////////////////////////////////////////////////////// +// CVAR CHANGES +/////////////////////////////////////////////////////////////////////////////// + +// Turn on bot FF if bot defend enabled +void Change_BotDefend(ConVar convar, const char[] oldValue, const char[] newValue) { + hSbFriendlyFire.IntValue = convar.IntValue != 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// METHODS - Old methods, some are also in feedthetrolls/misc.inc +/////////////////////////////////////////////////////////////////////////////// + +void ThrowAllItems(int victim) { + float vicPos[3], destPos[3]; + int clients[4]; + GetClientAbsOrigin(victim, vicPos); + //Find a survivor to throw to (grabs the first nearest non-self survivor) + int clientCount = GetClientsInRange(vicPos, RangeType_Visibility, clients, sizeof(clients)); + for(int i = 0; i < clientCount; i++) { + if(clients[i] != victim) { + GetClientAbsOrigin(clients[i], destPos); + break; + } + } + + //Loop all item slots + for(int slot = 0; slot <= 4; slot++) { + Handle pack; + CreateDataTimer(0.22 * float(slot), Timer_ThrowWeapon, pack); + + WritePackFloat(pack, destPos[0]); + WritePackFloat(pack, destPos[1]); + WritePackFloat(pack, destPos[2]); + WritePackCell(pack, slot); + WritePackCell(pack, victim); + } +} + +bool IsPlayerFarDistance(int client, float distance) { + int farthestClient = -1, secondClient = -1; + float highestFlow, secondHighestFlow; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + float flow = L4D2Direct_GetFlowDistance(i); + if(flow > highestFlow || farthestClient == -1) { + secondHighestFlow = highestFlow; + secondClient = farthestClient; + farthestClient = i; + highestFlow = flow; + } + } + } + //Incase the first player checked is the farthest: + if(secondClient == -1) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + float flow = L4D2Direct_GetFlowDistance(i); + if(farthestClient != i && ((flow < highestFlow && flow > secondHighestFlow) || secondClient == -1)) { + secondClient = i; + secondHighestFlow = flow; + } + } + } + } + float difference = highestFlow - secondHighestFlow; + PrintToConsoleAll("Flow Check | Player1=%N Flow1=%f Delta=%f", farthestClient, highestFlow, difference); + PrintToConsoleAll("Flow Check | Player2=%N Flow2=%f", secondClient, secondHighestFlow); + return client == farthestClient && difference > distance; +} + +BehaviorAction CreateWitchAttackAction(int target = 0) { + BehaviorAction action = ActionsManager.Allocate(18556); + SDKCall(g_hWitchAttack, action, target); + return action; +} + +Action OnWitchActionUpdate(BehaviorAction action, int actor, float interval, ActionResult result) { + /* Change to witch attack */ + result.type = CHANGE_TO; + result.action = CreateWitchAttackAction(g_iWitchAttackVictim); + result.SetReason("FTT"); + return Plugin_Handled; +} + +void HideHUD(int victim, float timeout = 0.0) { + SetEntProp(victim, Prop_Send, "m_iHideHUD", 64); + if(timeout > 0.0) + CreateTimer(timeout, Timer_RestoreHud, GetClientUserId(victim)); +} +void HideHUDRandom(int victim) { + float timeout = 0.0; + if(~Trolls[t_hideHUDIndex].activeFlagClients[victim] & 3) { + if(Trolls[t_hideHUDIndex].activeFlagClients[victim] & 1) { + if(GetURandomFloat() > 0.2) + return; + timeout = GetRandomFloat(1.0, 5.0); + } else if(Trolls[t_hideHUDIndex].activeFlagClients[victim] & 2) { + if(GetURandomFloat() < 0.5) + return; + timeout = GetRandomFloat(5.0, 10.0); + } + } + HideHUD(victim, timeout); +} \ No newline at end of file diff --git a/scripting/l4d2_forceset.sp b/scripting/l4d2_forceset.sp new file mode 100644 index 0000000..6c4fc28 --- /dev/null +++ b/scripting/l4d2_forceset.sp @@ -0,0 +1,48 @@ +#include +#include +#include + +#pragma semicolon 1 +#pragma newdecls required + +ConVar g_cvSurvivorSet; + +public Plugin myinfo = +{ + name = "[L4D2] Survivor Set Enforcer", + author = "DeathChaos, modified by Psyk0tik (Crasher_3637)", + description = "Forces L4D2 survivor set.", + version = "1.0", + url = "" +}; + +public void OnPluginStart() +{ + g_cvSurvivorSet = CreateConVar("l4d_force_survivorset", "0", "Forces specified survivor set (0 - no change, 1 - force L4D1, 2 - Force L4D2)", _, true, 0.0, true, 2.0); +} + +public Action L4D_OnGetSurvivorSet(int &retVal) +{ + int iSet = g_cvSurvivorSet.IntValue; + if (iSet > 0) + { + retVal = iSet; + + return Plugin_Handled; + } + + return Plugin_Continue; +} + +public Action L4D_OnFastGetSurvivorSet(int &retVal) +{ + int iSet = g_cvSurvivorSet.IntValue; + if (iSet > 0) + { + retVal = iSet; + + return Plugin_Handled; + } + + return Plugin_Continue; +} \ No newline at end of file diff --git a/scripting/l4d2_guesswho.sp b/scripting/l4d2_guesswho.sp new file mode 100644 index 0000000..2c9eb75 --- /dev/null +++ b/scripting/l4d2_guesswho.sp @@ -0,0 +1,897 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG_BOT_MOVE +#define DEBUG_BOT_MOVE_REACH +#define DEBUG +#define DEBUG_SHOW_POINTS +#define DEBUG_BLOCKERS +// #define DEBUG_LOG_MAPSTART +// #define DEBUG_MOVE_ATTEMPTS +// #define DEBUG_SEEKER_PATH_CREATION 1 + +#define PLUGIN_VERSION "1.0" + +#define BOT_MOVE_RANDOM_MIN_TIME 2.0 // The minimum random time for Timer_BotMove to activate (set per bot, per round) +#define BOT_MOVE_RANDOM_MAX_TIME 3.0 // The maximum random time for Timer_BotMove to activate (set per bot, per round) +#define BOT_MOVE_CHANCE 0.96 // The chance the bot will move each Timer_BotMove +#define BOT_MOVE_AVOID_FLOW_DIST 12.0 // The flow range of flow distance that triggers avoid +#define BOT_MOVE_AVOID_SEEKER_CHANCE 0.50 // The chance that if the bot gets too close to the seeker, it runs away +#define BOT_MOVE_AVOID_MIN_DISTANCE 200.0 // The minimum distance for a far away point. (NOT flow) +#define BOT_MOVE_USE_CHANCE 0.001 // Chance the bots will use +USE (used for opening doors, buttons, etc) +#define BOT_MOVE_JUMP_CHANCE 0.001 +#define BOT_MOVE_SHOVE_CHANCE 0.0015 +#define BOT_MOVE_RUN_CHANCE 0.15 +#define BOT_MOVE_NOT_REACHED_DISTANCE 60.0 // The distance that determines if a bot reached a point +#define BOT_MOVE_NOT_REACHED_ATTEMPT_RUNJUMP 6 // The minimum amount of attempts where bot will run or jump to dest +#define BOT_MOVE_NOT_REACHED_ATTEMPT_RETRY 10 // The minimum amount of attempts where bot gives up and picks new +#define DOOR_TOGGLE_INTERVAL 5.0 // Interval that loops throuh all doors to randomly toggle +#define DOOR_TOGGLE_CHANCE 0.01 // Chance that every Timer_DoorToggles triggers a door to toggle state +#define HIDER_SWAP_COOLDOWN 30.0 // Amount of seconds until they can swap +#define HIDER_SWAP_LIMIT 3 // Amount of times a hider can swap per round +#define FLOW_BOUND_BUFFER 200.0 // Amount to add to calculated bounds (Make it very generous) +#define HIDER_MIN_AVG_DISTANCE_AUTO_VOCALIZE 300.0 // The average minimum distance a hider is from the player that triggers auto vocalizating +#define HIDER_AUTO_VOCALIZE_GRACE_TIME 20.0 // Number of seconds between auto vocalizations +#define DEFAULT_MAP_TIME 480 +#define SEED_MIN_LOCATIONS 500 // Seed if less than this many locations + +#if defined DEBUG + #define SEED_TIME 1.0 +#else + #define SEED_TIME 15.0 // Time the seeker is blind, used to gather locations for bots +#endif + + +#define SMOKE_PARTICLE_PATH "particles/smoker_fx.pcf" +// #define SMOKE_PARTICLE_PATH "materials/particle/splashsprites/largewatersplash.vmt" +// #define SMOKE_PARTICLE_PATH "materials/particle/fire_explosion_1/fire_explosion_1.vmt" +#define SOUND_MODEL_SWAP "ui/pickup_secret01.wav" +#define MAX_VALID_LOCATIONS 2000 // The maximum amount of locations to hold, once this limit is reached only MAX_VALID_LOCATIONS_KEEP_PERCENT entries will be kept at random +#define MAX_VALID_LOCATIONS_KEEP_PERCENT 0.30 // The % of locations to be kept when dumping movePoints + +float DEBUG_POINT_VIEW_MIN[3] = { -5.0, -5.0, 0.0 }; +float DEBUG_POINT_VIEW_MAX[3] = { 5.0, 5.0, 2.0 }; +int SEEKER_GLOW_COLOR[3] = { 128, 0, 0 }; +int PLAYER_GLOW_COLOR[3] = { 0, 255, 0 }; + +#include +#include +#include +#include +#include +#include + +char SURVIVOR_MODELS[8][] = { + "models/survivors/survivor_gambler.mdl", + "models/survivors/survivor_producer.mdl", + "models/survivors/survivor_coach.mdl", + "models/survivors/survivor_mechanic.mdl", + "models/survivors/survivor_namvet.mdl", + "models/survivors/survivor_teenangst.mdl", + "models/survivors/survivor_biker.mdl", + "models/survivors/survivor_manager.mdl" +}; + + +// Game settings + +enum GameState { + State_Unknown = 0, + State_Starting, + State_Active, + State_HidersWin, + State_SeekerWon, +} + +// Game state specific +int currentSeeker; +bool hasBeenSeeker[MAXPLAYERS+1]; +bool ignoreSeekerBalance; +int hiderSwapTime[MAXPLAYERS+1]; +int hiderSwapCount[MAXPLAYERS+1]; +bool ignoreDrop[MAXPLAYERS+1]; +bool isStarting; + +// Temp Ent Materials & Timers +Handle spawningTimer; +Handle hiderCheckTimer; +Handle doorToggleTimer; +Handle recordTimer; +Handle timesUpTimer; +Handle waitTimer; +Handle waitForStartTimer; +Handle acquireLocationsTimer; +Handle moveTimers[MAXPLAYERS+1]; +UserMsg g_FadeUserMsgId; +int g_iSmokeParticle; +int g_iTeamNum = -1; + +// Cvars +ConVar cvar_seekerFailDamageAmount; + +GameConVarStorage cvarStorage; + +GameConVar cvar_survivorLimit; +GameConVar cvar_separationMinRange; +GameConVar cvar_separationMaxRange; +GameConVar cvar_abmAutoHard; +GameConVar cvar_sbFixEnabled; +GameConVar cvar_sbPushScale; +GameConVar cvar_battlestationGiveUp; +GameConVar cvar_sbMaxBattlestationRange; +GameConVar cvar_enforceProximityRange; +GameConVar cvar_spectatorIdleTime; +// Bot Movement specifics +float flowMin, flowMax; +float seekerPos[3]; +float seekerFlow = 0.0; + +float vecLastLocation[MAXPLAYERS+1][3]; + +MovePoints movePoints; +GuessWhoGame Game; + + +#include +#include + + +public Plugin myinfo = { + name = "L4D2 Guess Who", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + lateLoaded = late; + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + + Game.Init("GuessWho"); + + g_iTeamNum = FindSendPropInfo("CTerrorPlayerResource", "m_iTeam"); + if (g_iTeamNum == -1) + SetFailState("CTerrorPlayerResource \"m_iTeam\" offset is invalid"); + + validMaps = new ArrayList(ByteCountToCells(64)); + validSets = new ArrayList(ByteCountToCells(16)); + mapConfigs = new StringMap(); + + g_FadeUserMsgId = GetUserMessageId("Fade"); + + cvarStorage = new GameConVarStorage(); + + cvar_survivorLimit = new GameConVar("cvar_survivorLimit"); + cvar_separationMinRange = new GameConVar("sb_separation_danger_min_range"); + cvar_separationMaxRange = new GameConVar("sb_separation_danger_max_range"); + cvar_abmAutoHard = new GameConVar("abm_autohard"); + cvar_sbFixEnabled = new GameConVar("sb_fix_enabled"); + cvar_sbPushScale = new GameConVar("sb_pushscale"); + cvar_battlestationGiveUp = new GameConVar("sb_battlestation_give_up_range_from_human"); + cvar_sbMaxBattlestationRange = new GameConVar("sb_max_battlestation_range_from_human"); + cvar_enforceProximityRange = new GameConVar("enforce_proximity_range"); + cvar_spectatorIdleTime = new GameConVar("sv_spectatoridletime"); + + ConVar hGamemode = FindConVar("mp_gamemode"); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, gamemode, gamemode); + + cvar_seekerFailDamageAmount = CreateConVar("guesswho_seeker_damage", "20.0", "The amount of damage the seeker takes when they attack a bot.", FCVAR_NONE, true, 1.0); + + RegAdminCmd("sm_guesswho", Command_GuessWho, ADMFLAG_KICK); + RegAdminCmd("sm_gw", Command_GuessWho, ADMFLAG_KICK); + RegConsoleCmd("sm_joingame", Command_Join); +} + + + +public void OnPluginEnd() { + Game.Cleanup(); +} + +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); + bool shouldEnable = StrEqual(gamemode, "guesswho", false); + if(isEnabled == shouldEnable) return; + if(spawningTimer != null) delete spawningTimer; + firstCheckDone = false; + if(shouldEnable) { + cvarStorage = new GameConVarStorage(); + SetCvars(cvarStorage); + Game.Broadcast("Gamemode is starting"); + HookEvent("round_start", Event_RoundStart); + HookEvent("round_end", Event_RoundEnd); + HookEvent("player_death", Event_PlayerDeath); + HookEvent("player_bot_replace", Event_PlayerToBot); + HookEvent("player_ledge_grab", Event_LedgeGrab); + AddCommandListener(OnGoAwayFromKeyboard, "go_away_from_keyboard"); + } else if(!lateLoaded) { + cvarStorage.Restore(); + delete cvarStorage; + UnhookEvent("round_start", Event_RoundStart); + UnhookEvent("round_end", Event_RoundEnd); + UnhookEvent("player_death", Event_PlayerDeath); + UnhookEvent("player_bot_replace", Event_PlayerToBot); + UnhookEvent("player_ledge_grab", Event_LedgeGrab); + Game.Cleanup(); + RemoveCommandListener(OnGoAwayFromKeyboard, "go_away_from_keyboard"); + } + isEnabled = shouldEnable; +} + +public Action OnGoAwayFromKeyboard(int client, const char[] command, int argc) { + return Plugin_Handled; +} + +void Event_LedgeGrab(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + L4D_ReviveSurvivor(client); + } +} + +void Event_PlayerToBot(Event event, const char[] name, bool dontBroadcast) { + int userid = event.GetInt("player"); + int player = GetClientOfUserId(userid); + int bot = GetClientOfUserId(event.GetInt("bot")); + + // Do not kick bots being spawned in + if(spawningTimer == null && !IsFakeClient(player)) { + Game.Debug("possible idle bot: %d (player: %d)", bot, player); + // ChangeClientTeam(player, 0); + // L4D_SetHumanSpec(bot, player); + CreateTimer(0.1, Timer_ResumeFromIdle, userid); + // KickClient(bot); + } +} + +Action Timer_ResumeFromIdle(Handle h, int userid) { + int player = GetClientOfUserId(userid); + if(player > 0) + L4D_TakeOverBot(player); + return Plugin_Handled; +} + + +void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + if(client > 0 && Game.State == State_Active) { + if(client == currentSeeker) { + Game.Broadcast("The seeker, %N, has died. Hiders win!", currentSeeker); + Game.End(State_HidersWin); + } else if(!IsFakeClient(client)) { + if(attacker == currentSeeker) { + Game.Broadcast("%N was killed", client); + } else { + Game.Broadcast("%N died", client); + } + } else { + ClearInventory(client); + KickClient(client); + Game.Debug("Bot(%d) was killed", client); + } + } + + if(Game.AlivePlayers == 0) { + if(Game.State == State_Active) { + Game.Broadcast("Everyone has died. %N wins!", currentSeeker); + Game.End(State_SeekerWon); + } + } +} + +void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + waitTimer = CreateTimer(firstCheckDone ? 2.5 : 6.0, Timer_WaitForPlayers, _, TIMER_REPEAT); +} + +void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) { + // Skip the check, everyone's loaded in + firstCheckDone = true; +} + +public void OnMapStart() { + isStarting = false; + if(!isEnabled) return; + + SDKHook(FindEntityByClassname(0, "terror_player_manager"), SDKHook_ThinkPost, ThinkPost); + + char map[128]; + GetCurrentMap(map, sizeof(map)); + if(!StrEqual(g_currentMap, map)) { + firstCheckDone = false; + strcopy(g_currentSet, sizeof(g_currentSet), "default"); + if(!StrEqual(g_currentMap, "")) { + if(!movePoints.SaveMap(g_currentMap, g_currentSet)) { + LogError("Could not save map data to disk"); + } + } + ReloadMapDB(); + strcopy(g_currentMap, sizeof(g_currentMap), map); + Game.SetPoints(MovePoints.LoadMap(map, g_currentSet)); + } + + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt"); + g_iSmokeParticle = GetParticleIndex(SMOKE_PARTICLE_PATH); + if(g_iSmokeParticle == INVALID_STRING_INDEX) { + LogError("g_iSmokeParticle (%s) is invalid", SMOKE_PARTICLE_PATH); + } + // g_iSmokeParticle = PrecacheModel(SMOKE_PARTICLE_PATH); + PrecacheSound(SOUND_MODEL_SWAP); + SetCvars(null); + + if(lateLoaded) { + int seeker = Game.Seeker; + if(seeker > -1) { + currentSeeker = seeker; + Game.Debug("-Late load- Seeker: %N", currentSeeker); + } + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + Game.SetupPlayer(i); + } + } + InitGamemode(); + } + Game.State = State_Unknown; +} + +public void ThinkPost(int entity) { + static int iTeamNum[MAXPLAYERS+1]; + GetEntDataArray(entity, g_iTeamNum, iTeamNum, sizeof(iTeamNum)); + + for(int i = 1 ; i<= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsFakeClient(i)) { + iTeamNum[i] = 1; + } + } + + SetEntDataArray(entity, g_iTeamNum, iTeamNum, sizeof(iTeamNum)); +} + +public void OnClientPutInServer(int client) { + if(!isEnabled) return; + if(IsFakeClient(client)) { + if(GetClientTeam(client) == 3) { + KickClient(client, "GW: Remove Special Infected"); + } + } else { + ChangeClientTeam(client, 1); + isPendingPlay[client] = true; + Game.Broadcast("%N will play next round", client); + Game.TeleportToSpawn(client); + } +} + + +public void OnClientDisconnect(int client) { + if(!isEnabled) return; + if(client == currentSeeker) { + Game.Broadcast("The seeker has disconnected"); + Game.End(State_HidersWin); + } else if(!IsFakeClient(client) && Game.State == State_Active) { + Game.Broadcast("A hider has left (%N)", client); + if(Game.AlivePlayers == 0 && Game.State == State_Active) { + Game.Broadcast("Game Over. %N wins!", currentSeeker); + Game.End(State_SeekerWon); + } + } +} + + +void SetCvars(GameConVarStorage storage) { + Game.Debug("Setting convars"); + if(cvar_survivorLimit != null) { + cvar_survivorLimit.SetBounds(ConVarBound_Upper, true, 64.0); + cvar_survivorLimit.RecordInt(MaxClients, storage); + } + cvar_separationMinRange.RecordInt(1000, storage); + cvar_separationMaxRange.RecordInt(1000, storage); + cvar_abmAutoHard.RecordInt(0, storage); + cvar_sbFixEnabled.RecordInt(0, storage); + cvar_sbPushScale.RecordInt(0, storage); + cvar_battlestationGiveUp.RecordFloat(5000.0, storage); + cvar_sbMaxBattlestationRange.RecordFloat(5000.0, storage); + cvar_enforceProximityRange.RecordInt(10000, storage); + cvar_spectatorIdleTime.RecordInt(120, storage); +} + +void InitGamemode() { + if(isStarting && Game.State != State_Unknown) { + Game.Warn("InitGamemode() called in an incorrect state (%d)", Game.State); + return; + } + SetupEntities(); + Game.DebugConsole("InitGamemode(): activating"); + ArrayList validPlayerIds = new ArrayList(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + L4D2_SetPlayerSurvivorGlowState(i, false); + L4D2_RemoveEntityGlow(i); + + // ChangeClientTeam(i, 2); + activeBotLocations[i].attempts = 0; + hiderSwapCount[i] = 0; + distQueue[i].Clear(); + ClearInventory(i); + if(IsFakeClient(i)) { + KickClient(i); + } else { + ChangeClientTeam(i, 2); + if(!IsPlayerAlive(i)) { + L4D_RespawnPlayer(i); + } + if(!hasBeenSeeker[i] || ignoreSeekerBalance) + validPlayerIds.Push(GetClientUserId(i)); + } + } + } + if(validPlayerIds.Length == 0) { + Game.Warn("Ignoring InitGamemode() with no valid survivors"); + return; + } + ignoreSeekerBalance = false; + int newSeeker = GetClientOfUserId(validPlayerIds.Get(GetURandomInt() % validPlayerIds.Length)); + delete validPlayerIds; + if(newSeeker > 0) { + hasBeenSeeker[newSeeker] = true; + Game.Broadcast("%N is the seeker", newSeeker); + Game.Seeker = newSeeker; + SetPlayerBlind(newSeeker, 255); + SetEntPropFloat(newSeeker, Prop_Send, "m_flLaggedMovementValue", 0.0); + } + + Game.TeleportAllToStart(); + spawningTimer = CreateTimer(0.2, Timer_SpawnBots, 16, TIMER_REPEAT); +} + +Action Timer_SpawnBots(Handle h, int max) { + static int count; + if(count < max) { + if(AddSurvivor()) { + count++; + return Plugin_Continue; + } else { + PrintToChatAll("GUESS WHO: FATAL ERROR: AddSurvivor() failed"); + LogError("Guess Who: Fatal Error: AddSurvivor() failed"); + count = 0; + return Plugin_Stop; + } + } + count = 0; + CreateTimer(1.0, Timer_SpawnPost); + return Plugin_Stop; +} + +Action Timer_SpawnPost(Handle h) { + spawningTimer = null; + Game.DebugConsole("Timer_SpawnPost(): activating"); + bool isL4D1 = L4D2_GetSurvivorSetMap() == 1; + int remainingSeekers; + int survivorMaxIndex = isL4D1 ? 3 : 7; + int survivorIndexBot; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + int survivor; + if(IsFakeClient(i)) { + // Set bot models uniformly + survivor = survivorIndexBot; + if(++survivorIndexBot > survivorMaxIndex) { + survivorIndexBot = 0; + } + } else { + // Set hiders models randomly + survivor = GetURandomInt() % survivorMaxIndex; + if(i != currentSeeker) { + if(!hasBeenSeeker[i]) { + remainingSeekers++; + } + PrintToChat(i, "You can change your model %d times by looking at a player and pressing RELOAD", HIDER_SWAP_LIMIT); + } + } + + Game.SetupPlayer(i); + + SetEntityModel(i, SURVIVOR_MODELS[survivor]); // L4D2 first then L4D1 + SetEntProp(i, Prop_Send, "m_survivorCharacter", survivor); + } + } + + if(remainingSeekers == 0) { + Game.Broadcast("All players have been seekers once"); + for(int i = 0; i <= MaxClients; i++) { + hasBeenSeeker[i] = false; + } + } + + Game.Debug("waiting for safe area leave", BaseDebug_Server | BaseDebug_ChatAll); + waitForStartTimer = CreateTimer(1.0, Timer_WaitForStart, _, TIMER_REPEAT); + + return Plugin_Handled; +} + +Action Timer_WaitForStart(Handle h) { + if(mapConfig.hasSpawnpoint || L4D_HasAnySurvivorLeftSafeArea()) { + int targetPlayer = L4D_GetHighestFlowSurvivor(); + if(targetPlayer > 0) { + GetClientAbsOrigin(targetPlayer, seekerPos); + } + int seeker = Game.Seeker; + if(seeker <= 0) { + Game.Broadcast("Error: No seeker found, game in bugged state, restarting"); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + ForcePlayerSuicide(i); + } + } + return Plugin_Stop; + } + seekerFlow = L4D2Direct_GetFlowDistance(Game.Seeker); + acquireLocationsTimer = CreateTimer(0.5, Timer_AcquireLocations, _, TIMER_REPEAT); + hiderCheckTimer = CreateTimer(5.0, Timer_CheckHiders, _, TIMER_REPEAT); + doorToggleTimer = CreateTimer(DOOR_TOGGLE_INTERVAL, Timer_DoorToggles, _, TIMER_REPEAT); + for(int i = 1; i <= MaxClients; i++) { + if(i != currentSeeker && IsClientConnected(i) && IsClientInGame(i)) { + if(IsFakeClient(i)) { + if(movePoints.Length > 0) { + moveTimers[i] = CreateTimer(GetRandomFloat(BOT_MOVE_RANDOM_MIN_TIME, BOT_MOVE_RANDOM_MAX_TIME), Timer_BotMove, GetClientUserId(i), TIMER_REPEAT); + movePoints.GetRandomPoint(activeBotLocations[i]); + } + if(targetPlayer > 0) + TeleportEntity(i, activeBotLocations[i].pos, activeBotLocations[i].ang, NULL_VECTOR); + } else if(targetPlayer > 0) { + TeleportEntity(i, seekerPos, NULL_VECTOR, NULL_VECTOR); + } + } + } + + float seedTime = movePoints.Length > SEED_MIN_LOCATIONS ? 5.0 : SEED_TIME; + Game.Broadcast("The Seeker (%N) will start in %.0f seconds", Game.Seeker, seedTime); + Game.State = State_Starting; + Game.Tick = 0; + Game.MapTime = RoundFloat(seedTime); + CreateTimer(seedTime, Timer_StartSeeker); + return Plugin_Stop; + } + return Plugin_Continue; +} + +Action Timer_StartSeeker(Handle h) { + CPrintToChatAll("{blue}%N{default} : Here I come", currentSeeker); + Game.TeleportToSpawn(currentSeeker); + SetPlayerBlind(currentSeeker, 0); + Game.State = State_Active; + Game.Tick = 0; + SetEntPropFloat(currentSeeker, Prop_Send, "m_flLaggedMovementValue", 1.0); + if(mapConfig.mapTime == 0) { + mapConfig.mapTime = DEFAULT_MAP_TIME; + } + Game.MapTime = mapConfig.mapTime; + timesUpTimer = CreateTimer(float(mapConfig.mapTime), Timer_TimesUp); + return Plugin_Continue; +} + +Action Timer_TimesUp(Handle h) { + Game.Broadcast("The seeker ran out of time. Hiders win!"); + Game.End(State_HidersWin); + return Plugin_Handled; +} + + +Action OnWeaponEquip(int client, int weapon) { + if(weapon <= 0 || ignoreDrop[client]) return Plugin_Continue; + if(Game.Seeker == client) + return Plugin_Handled; + return Plugin_Continue; +} + + + +Action OnTakeDamageAlive(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + if(attacker == currentSeeker) { + damage = 100.0; + ClearInventory(victim); + if(attacker > 0 && attacker <= MaxClients && IsFakeClient(victim)) { + PrintToChat(attacker, "That was a bot! -%.0f health", cvar_seekerFailDamageAmount.FloatValue); + SDKHooks_TakeDamage(attacker, 0, 0, cvar_seekerFailDamageAmount.FloatValue, DMG_DIRECT); + } + return Plugin_Changed; + } else if(attacker > 0 && attacker <= MaxClients) { + damage = 0.0; + return Plugin_Changed; + } else { + return Plugin_Continue; + } +} + + +Action Timer_DoorToggles(Handle h) { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "prop_door_rotating")) != INVALID_ENT_REFERENCE) { + if(GetURandomFloat() < DOOR_TOGGLE_CHANCE) + AcceptEntityInput(entity, "Toggle"); + } + return Plugin_Handled; +} + +Action Timer_AcquireLocations(Handle h) { + bool ignoreSeeker = true; + #if defined DEBUG_SEEKER_PATH_CREATION + ignoreSeeker = false; + #endif + seekerFlow = L4D2Direct_GetFlowDistance(currentSeeker); + GetClientAbsOrigin(currentSeeker, seekerPos); + for(int i = 1; i <= MaxClients; i++) { + if((!ignoreSeeker || i != currentSeeker) && IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2 && GetEntityFlags(i) & FL_ONGROUND ) { + LocationMeta meta; + GetClientAbsOrigin(i, meta.pos); + GetClientEyeAngles(i, meta.ang); + if(meta.pos[0] != vecLastLocation[i][0] || meta.pos[1] != vecLastLocation[i][1] || meta.pos[2] != vecLastLocation[i][2]) { + movePoints.AddPoint(meta); + if(movePoints.Length > MAX_VALID_LOCATIONS) { + Game.Warn("Hit MAX_VALID_LOCATIONS (%d), clearing some locations", MAX_VALID_LOCATIONS); + movePoints.Sort(Sort_Random, Sort_Float); + movePoints.Erase(RoundFloat(MAX_VALID_LOCATIONS * MAX_VALID_LOCATIONS_KEEP_PERCENT)); + } + #if defined DEBUG_SHOW_POINTS + Effect_DrawBeamBoxRotatableToClient(i, meta.pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {0, 0, 255, 64}, 0); + #endif + vecLastLocation[i] = meta.pos; + } + } + } + return Plugin_Continue; +} + +Action Timer_BotMove(Handle h, int userid) { + int i = GetClientOfUserId(userid); + if(i == 0) return Plugin_Stop; + if(GetURandomFloat() > BOT_MOVE_CHANCE) { + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", + GetClientUserId(i), + activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2] + ); + #if defined DEBUG_SHOW_POINTS + Effect_DrawBeamBoxRotatableToAll(activeBotLocations[i].pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {157, 0, 255, 255}, 0); + #endif + return Plugin_Continue; + } + + float botFlow = L4D2Direct_GetFlowDistance(i); + static float pos[3]; + if(botFlow > 0.0 && (botFlow < flowMin || botFlow > flowMax)) { + activeBotLocations[i].runto = GetURandomFloat() > 0.90; + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", GetClientUserId(i), seekerPos[0], seekerPos[1], seekerPos[2]); + #if defined DEBUG_BOT_MOVE + TE_SetupBeamLaser(i, currentSeeker, g_iLaserIndex, 0, 0, 0, 8.0, 0.5, 0.1, 0, 1.0, {255, 255, 0, 125}, 1); + TE_SendToAll(); + Game.DebugConsole("BOT %N TOO FAR (%f) BOUNDS (%f, %f)-> Moving to seeker (%f %f %f)", i, botFlow, flowMin, flowMax, seekerPos[0], seekerPos[1], seekerPos[2]); + #endif + activeBotLocations[i].attempts = 0; + } else if(movePoints.Length > 0) { + GetAbsOrigin(i, pos); + float distanceToPoint = GetVectorDistance(pos, activeBotLocations[i].pos); + if(distanceToPoint < BOT_MOVE_NOT_REACHED_DISTANCE || GetURandomFloat() < 0.20) { + activeBotLocations[i].attempts = 0; + #if defined DEBUG_BOT_MOVE + L4D2_SetPlayerSurvivorGlowState(i, false); + L4D2_RemoveEntityGlow(i); + #endif + // Has reached destination + if(mapConfig.hasSpawnpoint && FloatAbs(botFlow - seekerFlow) < BOT_MOVE_AVOID_FLOW_DIST && GetURandomFloat() < BOT_MOVE_AVOID_SEEKER_CHANCE) { + if(!movePoints.GetRandomPointFar(seekerPos, activeBotLocations[i].pos, BOT_MOVE_AVOID_MIN_DISTANCE)) { + #if defined DEBUG_BOT_MOVE + // DebugConsole("BOT %N TOO CLOSE -> Failed to find far point, falling back to spawn", i); + #endif + activeBotLocations[i].pos = mapConfig.spawnpoint; + } else { + #if defined DEBUG_BOT_MOVE + // DebugConsole("BOT %N TOO CLOSE -> Moving to far point (%f %f %f) (%f units away)", i, activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2], GetVectorDistance(seekerPos, activeBotLocations[i].pos)); + #endif + } + activeBotLocations[i].runto = GetURandomFloat() < 0.75; + #if defined DEBUG_SHOW_POINTS + Effect_DrawBeamBoxRotatableToAll(activeBotLocations[i].pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.2, 0.1, 0, 0.0, {255, 255, 255, 255}, 0); + #endif + } else { + movePoints.GetRandomPoint(activeBotLocations[i]); + } + if(!L4D2_IsReachable(i, activeBotLocations[i].pos)) { + #if defined DEBUG_BOT_MOVE + Game.Warn("Point is unreachable at (%f, %f, %f) for %L", activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2], i); + Effect_DrawBeamBoxRotatableToAll(activeBotLocations[i].pos, DEBUG_POINT_VIEW_MIN, view_as({ 10.0, 10.0, 100.0 }), NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 400.0, 2.0, 3.0, 0, 0.0, {255, 0, 0, 255}, 0); + #endif + movePoints.GetRandomPoint(activeBotLocations[i]); + } + } else { + // Has not reached dest + activeBotLocations[i].attempts++; + #if defined DEBUG_MOVE_ATTEMPTS + PrintToConsoleAll("[gw/debug] Bot %d - move attempt %d - dist: %f", i, activeBotLocations[i].attempts, distanceToPoint); + #endif + if(activeBotLocations[i].attempts == BOT_MOVE_NOT_REACHED_ATTEMPT_RUNJUMP) { + if(distanceToPoint <= (BOT_MOVE_NOT_REACHED_DISTANCE * 2)) { + #if defined DEBUG_BOT_MOVE + Game.DebugConsole("Bot %d still has not reached point (%f %f %f), jumping", i, activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2]); + #if defined DEBUG_BOT_MOVE_REACH + L4D2_SetPlayerSurvivorGlowState(i, true); + L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 10, PLAYER_GLOW_COLOR, true); + #endif + #endif + activeBotLocations[i].jump = true; + } else { + activeBotLocations[i].runto = true; + #if defined DEBUG_BOT_MOVE + Game.DebugConsole("Bot %d not reached point (%f %f %f), running", i, activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2]); + #if defined DEBUG_BOT_MOVE_REACH + L4D2_SetPlayerSurvivorGlowState(i, true); + L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 10, PLAYER_GLOW_COLOR, true); + #endif + #endif + } + } else if(activeBotLocations[i].attempts > BOT_MOVE_NOT_REACHED_ATTEMPT_RETRY) { + #if defined DEBUG_BOT_MOVE + PrintToConsoleAll("[gw/debug] Bot %d giving up at reaching point (%f %f %f)", i, activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2]); + #if defined DEBUG_BOT_MOVE_REACH + L4D2_SetPlayerSurvivorGlowState(i, true); + L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 10, PLAYER_GLOW_COLOR, true); + #endif + #endif + movePoints.GetRandomPoint(activeBotLocations[i]); + } + #if defined DEBUG_SHOW_POINTS + int color[4]; + color[0] = 255; + color[2] = 255; + color[3] = 120 + activeBotLocations[i].attempts * 45; + Effect_DrawBeamBoxRotatableToAll(activeBotLocations[i].pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, color, 0); + #endif + } + + LookAtPoint(i, activeBotLocations[i].pos); + L4D2_RunScript("CommandABot({cmd=1,bot=GetPlayerFromUserID(%i),pos=Vector(%f,%f,%f)})", + GetClientUserId(i), + activeBotLocations[i].pos[0], activeBotLocations[i].pos[1], activeBotLocations[i].pos[2] + ); + } + return Plugin_Continue; +} + +public Action OnPlayerRunCmd(int client, int& buttons, int& impulse, float vel[3], float angles[3], int& weapon, int& subtype, int& cmdnum, int& tickcount, int& seed, int mouse[2]) { + if(!isEnabled) return Plugin_Continue; + if(IsFakeClient(client)) { + if(activeBotLocations[client].jump) { + activeBotLocations[client].jump = false; + buttons |= (IN_WALK | IN_JUMP | IN_FORWARD); + return Plugin_Changed; + } + buttons |= (activeBotLocations[client].runto ? IN_WALK : IN_SPEED); + if(GetURandomFloat() < BOT_MOVE_USE_CHANCE) { + buttons |= IN_USE; + } + float random = GetURandomFloat(); + if(random < BOT_MOVE_JUMP_CHANCE) { + buttons |= IN_JUMP; + } else if(random < BOT_MOVE_SHOVE_CHANCE) { + buttons |= IN_ATTACK2; + } + return Plugin_Changed; + } else if(client != currentSeeker && buttons & IN_RELOAD) { + if(hiderSwapCount[client] >= HIDER_SWAP_LIMIT) { + PrintHintText(client, "Swap limit reached"); + } else { + int target = GetClientAimTarget(client, true); + + if(target > 0) { + int time = GetTime(); + float diff = float(time - hiderSwapTime[client]); + if(diff > HIDER_SWAP_COOLDOWN) { + hiderSwapTime[client] = GetTime(); + hiderSwapCount[client]++; + + /*float pos[3], pos2[3]; + GetClientAbsOrigin(client, pos); + GetClientEyePosition(client, pos2); + TE_SetupParticle(g_iSmokeParticle, pos, pos2, .iEntity = client); + TE_SendToAllInRange(pos, RangeType_Audibility, 0.0);*/ + + ClearInventory(target); + + char modelName[64]; + GetClientModel(target, modelName, sizeof(modelName)); + int type = GetEntProp(target, Prop_Send, "m_survivorCharacter"); + SetEntityModel(client, modelName); + SetEntProp(client, Prop_Send, "m_survivorCharacter", type); + + float pos[3]; + GetClientAbsOrigin(client, pos); + + EmitSoundToAll("ui/pickup_secret01.wav", client, SNDCHAN_STATIC, .origin = pos); + PrintHintText(client, "You have %d swaps remaining", HIDER_SWAP_LIMIT - hiderSwapCount[client]); + + CreateTimer(0.1, Timer_ReGnome, client); + } else { + PrintHintText(client, "You can swap in %.0f seconds", HIDER_SWAP_COOLDOWN - diff); + } + } + } + } + return Plugin_Continue; +} + +Action Timer_ReGnome(Handle h, int client) { + GivePlayerItem(client, "weapon_gnome"); + return Plugin_Handled; +} + + +void ClearInventory(int client) { + for(int i = 0; i <= 5; i++) { + int item = GetPlayerWeaponSlot(client, i); + if(item > 0) { + RemovePlayerItem(client, item); + AcceptEntityInput(item, "kill"); + } + } +} + +bool AddSurvivor() { + if (GetClientCount(false) >= MaxClients - 1) { + return false; + } + + int i = CreateFakeClient("GuessWhoBot"); + bool result; + if (i > 0) { + if (DispatchKeyValue(i, "classname", "SurvivorBot")) { + ChangeClientTeam(i, 2); + + if (DispatchSpawn(i)) { + result = true; + } + } + + CreateTimer(0.2, Timer_Kick, GetClientUserId(i)); + } + return result; +} + +Action Timer_Kick(Handle h, int u) { + int i = GetClientOfUserId(u); + if(i > 0) KickClient(i); + return Plugin_Handled; +} + +stock void L4D2_RunScript(const char[] sCode, any ...) { + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE|| !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} + +public void OnSceneStageChanged(int scene, SceneStages stage) { + if(isEnabled && stage == SceneStage_Started) { + int activator = GetSceneInitiator(scene); + if(activator == 0) { + CancelScene(scene); + } + } +} \ No newline at end of file diff --git a/scripting/l4d2_hideandseek.sp b/scripting/l4d2_hideandseek.sp new file mode 100644 index 0000000..60a011c --- /dev/null +++ b/scripting/l4d2_hideandseek.sp @@ -0,0 +1,720 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define DEBUG_BLOCKERS 1 +// #define FORCE_ENABLED 1 +#define DEBUG_LOG_MAPSTART 1 + +#include +#include +#include +#include +#include +#if defined DEBUG_BLOCKERS +#include +#endif + +#define PARTICLE_ELMOS "st_elmos_fire_cp0" +#define PARTICLE_TES1 "electrical_arc_01" + +public Plugin myinfo = +{ + name = "L4D2 Hide & Seek", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +/*TODO: +2. Seeker helping +3. flare on hunted +*/ + +/* +script g_ModeScript.DeepPrintTable(g_ModeScript.MutationState) +{ + MapName = "c6m2_bedlam" + StartActive = true + CurrentSlasher = ([1] player) + MapTime = 480 + StateTick = 464 + LastGiveAdren = 10 + ModeName = "hideandseek" + Tick = 484 + CurrentStage = 3 + SlasherLastStumbled = 0 +} +*/ + +#define SOUND_SUSPENSE_1 "custom/suspense1.mp3" +#define SOUND_SUSPENSE_1_FAST "custom/suspense1fast.mp3" +#define SOUND_SHAKE "doors/gate_move1.wav" + +enum GameState { + State_Unknown = -1, + State_Startup, + State_Hiding, + State_Restarting, + State_Hunting +} + +bool isNearbyPlaying[MAXPLAYERS+1]; +bool wasThirdPersonVomitted[MAXPLAYERS+1]; +bool gameOver; +int currentSeeker; +int currentPlayers = 0; + +Handle suspenseTimer, thirdPersonTimer, peekCamStopTimer, hiderCheckTimer; + + +int g_BeamSprite; +int g_HaloSprite; + +bool hasBeenSeeker[MAXPLAYERS+1]; +float lastPos[MAXPLAYERS+1][3]; +float distanceTraveled[MAXPLAYERS+1]; +bool ignoreSeekerBalance; + +ConVar cvar_peekCam; +ConVar cvar_seekerBalance; +ConVar cvar_abm_autohard; +ConVar cvar_seekerHelpers; + +BaseGame Game; +#include +#include + + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + lateLoaded = late; + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + + Game.Init("Hide&Seek", "H&S"); + + validMaps = new ArrayList(ByteCountToCells(64)); + validSets = new ArrayList(ByteCountToCells(16)); + mapConfigs = new StringMap(); + + if(!ReloadMapDB()) { + SetFailState("Could not load entity config from data/hideandseek.cfg"); + } + + cvar_peekCam = CreateConVar("hs_peekcam", "0", "Controls the peek camera on events. Set bits\n0 = OFF, 1 = On Game End, 2 = Any death", FCVAR_NONE, true, 0.0, true, 3.0); + cvar_seekerBalance = CreateConVar("hs_seekerbalance", "1", "Enable or disable ensuring every player has played as seeker", FCVAR_NONE, true, 0.0, true, 1.0); + cvar_seekerHelpers = CreateConVar("hs_seekerhelper", "1", "Dev. 0 = off, 1 = Glow", FCVAR_NONE, true, 0.0); + + ConVar hGamemode = FindConVar("mp_gamemode"); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, gamemode, gamemode); + + cvar_abm_autohard = FindConVar("cvar_abm_autohard"); + + RegConsoleCmd("sm_joingame", Command_Join, "Joins or joins someone else"); + RegAdminCmd("sm_hs", Command_HideAndSeek, ADMFLAG_CHEATS, "The main command. see /hs help"); + +} + +public void OnPluginEnd() { + Cleanup(); +} + +public void OnClientConnected(int client) { + hasBeenSeeker[client] = false; + if(!IsFakeClient(client)) { + currentPlayers++; + if(isEnabled) { + GameState state = GetState(); + if(currentPlayers == 1 && state == State_Startup) { + CreateTimer(10.0, Timer_KeepWaiting, _, TIMER_REPEAT); + } + } + } +} + +public Action Timer_KeepWaiting(Handle h) { + SetTick(-40); + SetState(State_Startup); + PrintHintTextToAll("Waiting for players to join..."); + return IsGameSoloOrPlayersLoading() ? Plugin_Continue : Plugin_Stop; +} + +public void OnClientDisconnect(int client) { + if(!IsFakeClient(client)) { + distanceTraveled[client] = 0.0; + currentPlayers--; + } +} + +public void OnMapStart() { + if(!isEnabled) return; + + currentSeeker = 0; + + if(cvar_abm_autohard != null) { + cvar_abm_autohard.IntValue = 0; + } + char map[64]; + GetCurrentMap(map, sizeof(map)); + + if(!StrEqual(g_currentMap, map)) { + PrintToServer("[H&S] Map changed, loading fresh config"); + strcopy(g_currentMap, sizeof(g_currentMap), map); + if(!mapConfigs.GetArray(map, mapConfig, sizeof(MapConfig))) { + LoadConfigForMap(map); + } + strcopy(g_currentSet, sizeof(g_currentSet), "default"); + if(IsGameSoloOrPlayersLoading()) { + Handle timer = CreateTimer(10.0, Timer_KeepWaiting, _, TIMER_REPEAT); + TriggerTimer(timer); + PrintToServer("[H&S] Player(s) are connecting, or solo. Waiting..."); + SetState(State_Startup); + } + } + + #if defined DEBUG_BLOCKERS + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt"); + #endif + PrecacheSound(SOUND_SUSPENSE_1); + PrecacheSound(SOUND_SUSPENSE_1_FAST); + PrecacheSound(SOUND_SHAKE); + PrecacheSound("custom/xen_teleport.mp3"); + AddFileToDownloadsTable("sound/custom/suspense1.mp3"); + AddFileToDownloadsTable("sound/custom/suspense1fast.mp3"); + AddFileToDownloadsTable("sound/custom/xen_teleport.mp3"); + + PrecacheParticle(PARTICLE_ELMOS); + PrecacheParticle(PARTICLE_TES1); + + g_BeamSprite = PrecacheModel("sprites/laser.vmt"); + g_HaloSprite = PrecacheModel("sprites/halo01.vmt"); + PrecacheSound("buttons/button17.wav", true); + + if(lateLoaded) { + SetupEntities(); + int seeker = GetSlasher(); + if(seeker > -1) { + currentSeeker = seeker; + PrintToServer("[H&S] Late load, found seeker %N", currentSeeker); + } + if(IsGameSoloOrPlayersLoading()) { + Handle timer = CreateTimer(10.0, Timer_KeepWaiting, _, TIMER_REPEAT); + TriggerTimer(timer); + PrintToServer("[H&S] Late load, player(s) are connecting, or solo. Waiting..."); + SetState(State_Startup); + } + lateLoaded = false; + } +} + +public Action L4D2_OnChangeFinaleStage(int &finaleType, const char[] arg) { + if(isEnabled) { + finaleType = 0; + return Plugin_Changed; + } + return Plugin_Continue; +} + +public void OnSceneStageChanged(int scene, SceneStages stage) { + if(isEnabled && stage == SceneStage_Spawned) { + int activator = GetSceneInitiator(scene); + if(activator != GetActorFromScene(scene)) { + CancelScene(scene); + } + } +} + +bool wasEnabled; +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); + #if defined FORCE_ENABLED + isEnabled = true; + PrintToServer("[H&S] Force-enabled debug"); + #else + isEnabled = StrEqual(gamemode, "hideandseek", false); + #endif + if(isEnabled) { + PrintToChatAll("[H&S] Hide and seek gamemode activated, starting"); + HookEvent("round_end", Event_RoundEnd); + HookEvent("round_start", Event_RoundStart); + HookEvent("player_spawn", Event_PlayerSpawn); + HookEvent("item_pickup", Event_ItemPickup); + HookEvent("player_death", Event_PlayerDeath); + // OnMapStart(); // Don't use, need to track OnMapStart + if(lateLoaded) + CreateTimer(2.0, Timer_RoundStart); + else + CreateTimer(10.0, Timer_RoundStart); + if(suspenseTimer != null) + delete suspenseTimer; + suspenseTimer = CreateTimer(20.0, Timer_Music, _, TIMER_REPEAT); + if(hiderCheckTimer != null) + delete hiderCheckTimer; + hiderCheckTimer = CreateTimer(30.0, Timer_CheckHiders, _, TIMER_REPEAT); + if(thirdPersonTimer != null) + delete thirdPersonTimer; + thirdPersonTimer = CreateTimer(2.0, Timer_CheckPlayers, _, TIMER_REPEAT); + if(!lateLoaded) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + ForcePlayerSuicide(i); + } + } + } + wasEnabled = true; + } else if(wasEnabled) { + wasEnabled = false; + UnhookEvent("round_end", Event_RoundEnd); + UnhookEvent("round_start", Event_RoundStart); + UnhookEvent("item_pickup", Event_ItemPickup); + UnhookEvent("player_death", Event_PlayerDeath); + UnhookEvent("player_spawn", Event_PlayerSpawn); + Cleanup(); + delete suspenseTimer; + delete thirdPersonTimer; + delete hiderCheckTimer; + } +} + +const float DEATH_CAM_MIN_DIST = 150.0; +public Action Timer_StopPeekCam(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + PeekCam.Disable(i); + } + PeekCam.Disable(); + RequestFrame(Frame_StopPeekCam); + peekCamStopTimer = null; + return Plugin_Stop; +} + +void Frame_StopPeekCam() { + PeekCam.Destroy(); +} + +public void OnEntityCreated(int entity, const char[] classname) { + if(isEnabled) { + if(StrEqual(classname, "infected")) + AcceptEntityInput(entity, "Kill"); + } +} + +public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + if(gameOver) return; + + int client = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + + if(!gameOver && client && GetClientTeam(client) == 2) { + PeekCam.Create(); + PeekCam.Target = attacker > 0 ? attacker : client; + PeekCam.Perspective = Cam_FirstPerson; + + float seekerPos[3], pos[3]; + // If player died on their own, set attacker to themselves for viewing purposes + if(attacker <= 0) attacker = client; + GetClientAbsOrigin(attacker, seekerPos); + PeekCam.Enable(attacker); + + int alive = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + // If death was by a seeker: + if(attacker == currentSeeker && cvar_peekCam.IntValue & 2) { + GetClientAbsOrigin(i, pos); + if(GetVectorDistance(seekerPos, pos) > DEATH_CAM_MIN_DIST) { + PeekCam.Enable(i); + } + } + if(IsPlayerAlive(i) && GetClientTeam(i) == 2) alive++; + } + } + + PrintToConsoleAll("attacker: %N | victim: %N | alive: %d", client, attacker, alive); + if(client == currentSeeker && alive == 1) { + // If seeker died + CPrintToChatAll("{green}Hiders win!"); + gameOver = true; + } else { + if(alive == 2) { + CPrintToChatAll("{green}One hider remains."); + } else if(alive <= 0) { + // Player died and not seeker, therefore seeker killed em + // If who died was not the seeker + if(attacker == 0) { + CPrintToChatAll("Seeker has left, game over."); + } + if(client == currentSeeker) { + CPrintToChatAll("{green}Hiders win! The seeker has perished."); + } else { + CPrintToChatAll("{green}The seeker %N won!", currentSeeker); + } + + if(cvar_peekCam.IntValue & 1) { + PeekCam.Target = client; + PeekCam.Perspective = Cam_ThirdPerson; + } + + gameOver = true; + return; + } else if(alive > 2 && client != currentSeeker) { + CPrintToChatAll("{green}%d hiders remain", alive - 1); + } + } + if(peekCamStopTimer != null && IsValidHandle(peekCamStopTimer)) delete peekCamStopTimer; + peekCamStopTimer = CreateTimer(2.0, Timer_StopPeekCam); + } +} + +public void OnClientPutInServer(int client) { + if(isEnabled && !IsFakeClient(client)) { + ChangeClientTeam(client, 1); + isPendingPlay[client] = true; + isNearbyPlaying[client] = false; + PrintToChatAll("%N will play next round", client); + float pos[3]; + GetSpawnPosition(pos); + TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR); + } +} + + +public void Event_ItemPickup(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && client > 0 && currentSeeker != client) { + static char item[32]; + event.GetString("item", item, sizeof(item)); + if(StrEqual(item, "melee")) { + int entity = GetPlayerWeaponSlot(client, 1); + GetEntPropString(entity, Prop_Data, "m_strMapSetScriptName", item, sizeof(item)); + if(StrEqual(item, "fireaxe")) { + gameOver = false; + currentSeeker = GetSlasher(); + if(currentSeeker <= 0) { + PrintToServer("[H&S] ERROR: GetSlasher() returned invalid seeker"); + currentSeeker = client; + } else if(currentSeeker != client) { + PrintToConsoleAll("[H&S] Seeker does not equal axe-receiver. Possible seeker: %N", client); + } + PeekCam.Target = currentSeeker; + if(!ignoreSeekerBalance && cvar_seekerBalance.BoolValue) { + if(hasBeenSeeker[currentSeeker]) { + ArrayList notPlayedSeekers = new ArrayList(1); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && !hasBeenSeeker[i]) { + notPlayedSeekers.Push(i); + } + } + if(notPlayedSeekers.Length > 0) { + int newSlasher = notPlayedSeekers.Get(GetURandomInt() % notPlayedSeekers.Length); + PrintToServer("[H&S] Switching seeker to a new random seeker: %N", newSlasher); + SetSlasher(newSlasher); + delete notPlayedSeekers; + return; + } else { + PrintToServer("[H&S] All players have played as seeker, resetting"); + PrintToChatAll("[H&S] Everyone has played as a seeker once"); + for(int i = 1; i <= MaxClients; i++) { + hasBeenSeeker[i] = false; + } + hasBeenSeeker[currentSeeker] = true; + } + delete notPlayedSeekers; + } else { + hasBeenSeeker[currentSeeker] = true; + } + } + ignoreSeekerBalance = false; + CPrintToChatAll("{green}%N{yellow} is the seeker", currentSeeker); + } + } + } +} + +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && mapConfig.hasSpawnpoint) { + TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + } + PeekCam.Disable(client); +} + +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + if(mapConfig.hasSpawnpoint) { + PrintToServer("[H&S] Using provided spawnpoint: %.1f %.1f %.1f", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]); + } + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(isPendingPlay[i]) { + JoinGame(i); + } + if(mapConfig.hasSpawnpoint) + TeleportEntity(i, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR); + } + } + EntFire("relay_intro_start", "Kill"); + EntFire("outro", "Kill"); + CreateTimer(1.0, Timer_SetupEntities); + CreateTimer(15.0, Timer_RoundStart); +} + +public Action Timer_SetupEntities(Handle h) { + SetupEntities(); + return Plugin_Handled; +} + +public void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) { + if(nextRoundMap[0] != '\0') { + ForceChangeLevel(nextRoundMap, "SetMapSelect"); + nextRoundMap[0] = '\0'; + return; + } + currentSeeker = 0; + for(int i = 1; i <= MaxClients; i++) { + isNearbyPlaying[i] = false; + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 1) { + distanceTraveled[i] = 0.0; + PeekCam.Disable(i); + if(isPendingPlay[i]) { + JoinGame(i); + } + } + } + PeekCam.Destroy(); +} + +public Action Timer_CheckPlayers(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(!IsClientConnected(i) || !IsClientInGame(i)) continue; + + if(GetClientTeam(i) == 2 && IsPlayerAlive(i) && i != currentSeeker) { + float pos[3]; + GetClientAbsOrigin(i, pos); + distanceTraveled[i] = FloatAbs(Get2DVectorDistance(pos, lastPos[i])); + + lastPos[i] = pos; + QueryClientConVar(i, "cam_collision", QueryClientConVarCallback); + } + SetEntProp(i, Prop_Send, "m_audio.soundscapeIndex", -1); + + } + // Rare Crashes: + // ServerCommand("soundscape_flush"); + return Plugin_Continue; +} + +public void QueryClientConVarCallback(QueryCookie cookie, int client, ConVarQueryResult result, const char[] sCvarName, const char[] bCvarValue) { + int value = 0; + if (result == ConVarQuery_Okay && StringToIntEx(bCvarValue, value) > 0 && value == 0) { + wasThirdPersonVomitted[client] = true; + PrintHintText(client, "Third person is disabled in this mode"); + // L4D_OnITExpired(client); + // L4D_CTerrorPlayer_OnVomitedUpon(client, client); + float random = GetRandomFloat(); + if(random < 0.3) + PerformScene(client, "Playerareaclear"); + else if(random <= 0.6) + PerformScene(client, "PlayerLaugh"); + else + PerformScene(client, "PlayerDeath"); + } else if(wasThirdPersonVomitted[client]) { + wasThirdPersonVomitted[client] = false; + L4D_OnITExpired(client); + } +} + +int PLAYER_GLOW_COLOR[3] = { 0, 255, 0 }; +public Action Timer_CheckHiders(Handle h) { + static float seekerLoc[3]; + static float playerLoc[3]; + if(cvar_seekerHelpers.IntValue != 0) return Plugin_Continue; + if(currentSeeker > 0) { + GetClientAbsOrigin(currentSeeker, seekerLoc); + } + for(int i = 1; i <= MaxClients; i++) { + if(i != currentSeeker && IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && GetClientTeam(i) == 2) { + GetClientAbsOrigin(i, playerLoc); + float dist = GetVectorDistance(seekerLoc, playerLoc, true); + if(dist > 290000.0) { + L4D2_SetPlayerSurvivorGlowState(i, true); + L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 10, PLAYER_GLOW_COLOR, true); + CreateTimer(2.0, Timer_RemoveGlow, GetClientUserId(i)); + } + } + } + return Plugin_Continue; +} + +public Action Timer_RemoveGlow(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client) { + L4D2_SetPlayerSurvivorGlowState(client, false); + L4D2_RemoveEntityGlow(client); + } + return Plugin_Handled; +} +GameState prevState; + +// #define HEARTBEAT_NEAR_DIST 1_000_000 +// #define HEARTBEAT_CLOSE_DIST 250_000 + +#define HEARTBEAT_NEAR_DIST 1000 +#define HEARTBEAT_CLOSE_DIST 300 + +public Action Timer_Music(Handle h) { + static float seekerLoc[3]; + static float playerLoc[3]; + if(currentSeeker > 0) { + GetClientAbsOrigin(currentSeeker, seekerLoc); + GameState state = GetState(); + if(state == State_Hunting) { + if(prevState == State_Hiding) { + ShowBeacon(currentSeeker); + PeekCam.Target = currentSeeker; + PeekCam.Create(); + PeekCam.Enable(); + CreateTimer(2.2, Timer_StopPeekCam); + } + EmitSoundToClient(currentSeeker, SOUND_SUSPENSE_1, currentSeeker, SNDCHAN_AUTO, SNDLEVEL_NORMAL, SND_CHANGEPITCH, 0.2, 90, currentSeeker, seekerLoc, seekerLoc, true); + } + prevState = state; + } + int playerCount; + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && i != currentSeeker) { + playerCount++; + // GetClientAbsOrigin(i, playerLoc); + // float dist = GetVectorDistance(seekerLoc, playerLoc, true); + float dist = GetFlowDistance(currentSeeker, i); + if(dist <= HEARTBEAT_CLOSE_DIST) { + StopSound(i, SNDCHAN_AUTO, SOUND_SUSPENSE_1); + EmitSoundToClient(i, SOUND_SUSPENSE_1_FAST, i, SNDCHAN_AUTO, SNDLEVEL_NORMAL, SND_CHANGEPITCH, 1.0, 100, currentSeeker, seekerLoc, playerLoc, true); + isNearbyPlaying[i] = true; + } else if(dist <= HEARTBEAT_CLOSE_DIST) { + EmitSoundToClient(i, SOUND_SUSPENSE_1, i, SNDCHAN_AUTO, SNDLEVEL_NORMAL, SND_CHANGEPITCH, 0.4, 90, currentSeeker, seekerLoc, playerLoc, true); + isNearbyPlaying[i] = true; + StopSound(i, SNDCHAN_AUTO, SOUND_SUSPENSE_1_FAST); + } else if(isNearbyPlaying[i]) { + isNearbyPlaying[i] = false; + StopSound(i, SNDCHAN_AUTO, SOUND_SUSPENSE_1_FAST); + StopSound(i, SNDCHAN_AUTO, SOUND_SUSPENSE_1); + } + } + } + return Plugin_Continue; +} + + +float GetFlowDistance(int survivorA, int survivorB) { + return FloatAbs(L4D2Direct_GetFlowDistance(survivorA) - L4D2Direct_GetFlowDistance(survivorB)); +} + +public Action Timer_RoundStart(Handle h) { + PrintToServer("[H&S] Running round entity tweaks"); + CreateTimer(0.1, Timer_CheckWeapons); + CreateTimer(10.0, Timer_CheckWeapons); + int entity = INVALID_ENT_REFERENCE; + if(mapConfig.pressButtons) { + while ((entity = FindEntityByClassname(entity, "func_button")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Press"); + } + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "infected")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Kill"); + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "prop_door_rotating")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Unlock"); + if(GetURandomFloat() > 0.5) + AcceptEntityInput(entity, "Toggle"); + } + if(mapConfig.canClimb) { + while ((entity = FindEntityByClassname(entity, "func_simpleladder")) != INVALID_ENT_REFERENCE) { + SDKHook(entity, SDKHook_TraceAttackPost, Hook_OnAttackPost); + SetEntProp(entity, Prop_Send, "m_iTeamNum", 0); + } + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "env_soundscape")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Disable"); + AcceptEntityInput(entity, "Kill"); + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "env_soundscape_triggerable")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Disable"); + AcceptEntityInput(entity, "Kill"); + } + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "env_soundscape_proxy")) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "Disable"); + AcceptEntityInput(entity, "Kill"); + } + if(mapConfig.mapTime > 0) { + SetMapTime(mapConfig.mapTime); + } + + PrintToServer("[H&S] Map time is %d seconds", GetMapTime()); + return Plugin_Continue; +} + +static float lastShakeTime; +public void Hook_OnAttackPost(int entity, int attacker, int inflictor, float damage, int damagetype, int ammotype, int hitbox, int hitgroup) { + if(attacker == currentSeeker && attacker > 0 && GetGameTime() - lastShakeTime > 2.0) { + lastShakeTime = GetGameTime(); + float min[3], max[3], origin[3], top[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", origin); + GetEntPropVector(entity, Prop_Send, "m_vecMins", min); + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", max); + PrintHintText(attacker, "Shaking ladder"); + top = origin; + top[2] = max[2]; + origin[2] = min[2]; + TR_EnumerateEntitiesHull(origin, top, min, max, PARTITION_SOLID_EDICTS, Ray_Enumerator, attacker); + EmitAmbientSound(SOUND_SHAKE, top, SOUND_FROM_WORLD, SNDLEVEL_SCREAMING, SND_NOFLAGS, SNDVOL_NORMAL, SNDPITCH_NORMAL); + } +} +bool Ray_Enumerator(int entity, int attacker) { + if(entity > 0 && entity <= MaxClients && entity != attacker) { + L4D_StaggerPlayer(entity, attacker, NULL_VECTOR); + } + return true; +} +public Action Timer_CheckWeapons(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + // Check if has no melee: + if(GetPlayerWeaponSlot(i, 1) == -1) { + CheatCommand(i, "give", "knife"); + } + int item = GetPlayerWeaponSlot(i, 0); + if(item != -1) AcceptEntityInput(item, "Kill"); + } + } + if(currentSeeker) { + int wpn = GetPlayerWeaponSlot(currentSeeker, 1); + if(wpn > 0) { + char buffer[32]; + GetEntityClassname(wpn, buffer, sizeof(buffer)); + if(StrEqual(buffer, "melee")) { + GetEntPropString(wpn, Prop_Data, "m_strMapSetScriptName", buffer, sizeof(buffer)); + if(StrEqual(buffer, "fireaxe")) { + return Plugin_Continue; + } + } + AcceptEntityInput(wpn, "Kill"); + } + CheatCommand(currentSeeker, "give", "fireaxe"); + } + return Plugin_Continue; +} \ No newline at end of file diff --git a/scripting/l4d2_perms.sp b/scripting/l4d2_perms.sp new file mode 100644 index 0000000..8fcf4e8 --- /dev/null +++ b/scripting/l4d2_perms.sp @@ -0,0 +1,200 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +#include +#include + +#define RESERVE_LEVELS 4 +char ReserveLevels[RESERVE_LEVELS][] = { + "Public", "Watch", "Admin Only", "Private" +}; + +StringMap g_steamIds; + + +ConVar cv_cheatsMode; +ConVar cv_reserveMode; +ConVar cv_reserveMessage; char g_reserveMessage[64]; +ConVar cv_sm_cheats; + +bool g_ignoreModeChange; +ReserveMode g_previousMode; + +public Plugin myinfo = +{ + name = "L4D2 Perms", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + return APLRes_Success; +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + g_steamIds = new StringMap(); + + cv_reserveMessage = CreateConVar("sm_perms_reserve_msg", "Sorry, server is reserved.", "The message sent to users when server is reserved."); + cv_reserveMessage.AddChangeHook(OnReserveMsgChanged); + + cv_reserveMode = CreateConVar("sm_perms_reserve_mode", "0", "The current reservation mode. \n 0 = None (public)\n 1 = Watch\n 2 = Admin Only\n 3 = Private", FCVAR_DONTRECORD, true, 0.0, true, float(RESERVE_LEVELS)); + cv_reserveMode.AddChangeHook(OnReserveModeChanged); + + cv_sm_cheats = CreateConVar("sm_cheats", "0", "Is sm cheats enabled?", FCVAR_NONE, true, 0.0, true, 1.0); + cv_sm_cheats.AddChangeHook(OnCheatsChanged); + + cv_cheatsMode = CreateConVar("sm_perms_cheats_mode", "2", "When cheats are turned on, which reservation should be set?.\n 0 = None (public)\n 1 = Watch\n 2 = Admin Only\n 3 = Private", FCVAR_NONE, true, 0.0, true, float(RESERVE_LEVELS - 1)); + + // cv_cheats = FindConVar("sv_cheats"); + + HookEvent("player_disconnect", Event_PlayerDisconnect); + + AutoExecConfig(true, "l4d2_perms"); + + + RegAdminCmd("sm_perm", Command_SetServerPermissions, ADMFLAG_KICK, "Sets the server's permissions."); + RegAdminCmd("sm_perms", Command_SetServerPermissions, ADMFLAG_KICK, "Sets the server's permissions."); +} + +void OnCheatsChanged(ConVar cvar, const char[] oldValue, const char[] newValue) { + if(g_ignoreModeChange) { + g_ignoreModeChange = false; + return; + } + if(cvar.IntValue > 0) { + g_previousMode = GetReserveMode(); + if(g_previousMode == Reserve_None || g_previousMode == Reserve_Watch) + SetReserveMode(view_as(cv_cheatsMode.IntValue), "cheats activated"); + } else { + SetReserveMode(g_previousMode); + } +} + +void OnReserveModeChanged(ConVar cvar, const char[] oldValue, const char[] newValue) { + if(g_ignoreModeChange) { + g_ignoreModeChange = false; + return; + } + if(cvar.IntValue >= 0 && cvar.IntValue < RESERVE_LEVELS) { + PrintChatToAdmins("Server access changed to %s", ReserveLevels[cvar.IntValue]); + PrintToServer("Server access changed to %s", ReserveLevels[cvar.IntValue]); + ReserveMode mode = view_as(cvar.IntValue); + char buffer[32]; + if(mode == Reserve_AdminOnly || mode == Reserve_Private) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientInGame(i) && !IsFakeClient(i)) { + GetClientAuthId(i, AuthId_Steam2, buffer, sizeof(buffer)); + g_steamIds.SetValue(buffer, i); + } + } + } + } else { + // cvar.SetString(oldValue); + } +} + +void OnReserveMsgChanged(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(g_reserveMessage, sizeof(g_reserveMessage)); +} + +public void OnClientConnected(int client) { + if(!IsFakeClient(client) && GetReserveMode() == Reserve_Watch) { + PrintChatToAdmins("%N is connecting", client); + } +} + +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + if(GetClientCount(false) == 0) { + // Clear when last player disconnected + SetReserveMode(Reserve_None); + g_ignoreModeChange = true; + cv_sm_cheats.IntValue = 0; + } + } +} + +public void OnClientPostAdminCheck(int client) { + if(!IsFakeClient(client)) { + if(GetReserveMode() == Reserve_AdminOnly && GetUserAdmin(client) == INVALID_ADMIN_ID) { + char auth[32]; + GetClientAuthId(client, AuthId_Steam2, auth, sizeof(auth)); + // Check if they are whitelisted: + if(!g_steamIds.ContainsKey(auth)) { + KickClient(client, "Sorry, server is reserved"); + return; + } + } + } +} + +public void OnClientAuthorized(int client, const char[] auth) { + if(IsFakeClient(client)) return; + if(GetReserveMode() == Reserve_Private) { + if(!g_steamIds.ContainsKey(auth)) { + KickClient(client, "Sorry, server is reserved"); + } + } + // Don't insert id here if admin only, let admin check do that + if(GetReserveMode() != Reserve_AdminOnly) { + g_steamIds.SetValue(auth, client); + } +} + + +Action Command_SetServerPermissions(int client, int args) { + if(args > 0) { + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + if(StrEqual(arg1, "public", false)) { + SetReserveMode(Reserve_None); + } else if(StrContains(arg1, "noti", false) > -1 || StrContains(arg1, "watch", false) > -1) { + SetReserveMode(Reserve_Watch); + } else if(StrContains(arg1, "admin", false) > -1) { + SetReserveMode(Reserve_AdminOnly); + } else if(StrEqual(arg1, "private", false)) { + SetReserveMode(Reserve_Private); + } else { + ReplyToCommand(client, "Usage: sm_reserve [public/notify/admin/private] or no arguments to view current reservation."); + return Plugin_Handled; + } + } else { + ReplyToCommand(client, "Server access level is currently %s", ReserveLevels[GetReserveMode()]); + } + return Plugin_Handled; +} + +ReserveMode GetReserveMode() { + return view_as(cv_reserveMode.IntValue); +} + +void SetReserveMode(ReserveMode mode, const char[] reason = "") { + ReserveMode curMode = GetReserveMode(); + // Clear allowed users when undoing private + if(curMode != mode && curMode == Reserve_Private) { + g_steamIds.Clear(); + } + + if(reason[0] != '\0') { + // Print custom message if a reason is passed: + g_ignoreModeChange = true; + PrintChatToAdmins("Server access changed to %s (%s)", ReserveLevels[mode], reason); + PrintToServer("Server access changed to %s (%s)", ReserveLevels[mode], reason); + } + cv_reserveMode.IntValue = view_as(mode); +} \ No newline at end of file diff --git a/scripting/l4d2_population_control.sp b/scripting/l4d2_population_control.sp new file mode 100644 index 0000000..663db88 --- /dev/null +++ b/scripting/l4d2_population_control.sp @@ -0,0 +1,214 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define CLOWN_MUSIC_THRESHOLD 30 + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include + +public Plugin myinfo = +{ + name = "L4D2 Population Control", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +static ConVar hPercentTotal; +static ConVar hPercentClown; +static ConVar hPercentMud; +static ConVar hPercentCeda; +static ConVar hPercentWorker; +static ConVar hPercentRiot; +static ConVar hPercentJimmy; +static ConVar hTotalZombies; +static ConVar hZCommonLimit; + +static bool IsDoneLoading, clownMusicPlayed; + +static int iCurrentCommons, commonLimit, clownCommonsSpawned; +static int commonType[2048]; + +#define COMMON_MODELS_COUNT 6 +static char INFECTED_MODELS[COMMON_MODELS_COUNT][] = { + "models/infected/common_male_clown.mdl", //clown + "models/infected/common_male_mud.mdl", //mud + "models/infected/common_male_ceda.mdl", //ceda + "models/infected/common_male_riot.mdl", //riot + "models/infected/common_male_jimmy.mdl", //jimmy + "models/infected/common_male_fallen_survivor.mdl", //fallen + +}; +static char WORKER_MODELS[3][] = { + "models/infected/common_worker_male01.mdl", + "models/infected/common_male_roadcrew.mdl", + "models/infected/common_male_roadcrew_rain.mdl" +}; +enum CommonTypes { + Common_Clown, + Common_Mud, + Common_Ceda, + Common_Riot, + Common_Jimmy, + Common_Worker = -1, +}; + +//TODO: Add back survivor zombie, inc z_fallen_max_count + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + + HookEvent("game_start", OnGameStart); + + hPercentTotal = CreateConVar("l4d2_population_global_chance", "1.0", "The % chance that any the below chances occur.\n0.0 = NEVER, 1.0: ALWAYS"); + hPercentClown = CreateConVar("l4d2_population_clowns", "0.0", "The % chance that a common spawns as a clown.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hPercentMud = CreateConVar("l4d2_population_mud", "0.0", "The % chance that a common spawns as a mud zombie.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hPercentCeda = CreateConVar("l4d2_population_ceda", "0.0", "The % chance that a common spawns as a ceda zombie.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hPercentWorker = CreateConVar("l4d2_population_worker", "0.0", "The % chance that a common spawns as a worker zombie.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hPercentRiot = CreateConVar("l4d2_population_riot", "0.0", "The % chance that a common spawns as a riot zombie.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hPercentJimmy = CreateConVar("l4d2_population_jimmy", "0.0", "The % chance that a common spawns as a Jimmy Gibs Jr. zombie.\n0.0 = OFF, 1.0 = ALWAYS", FCVAR_NONE, true, 0.0, true, 1.0); + hTotalZombies = CreateConVar("l4d2_population_common", "0.0", "The maximum amount of commons, anymore will be deleted.\n0 = Turn Off\n> 0: Fixed limit\n< 0: z_common_limit + absolute value", FCVAR_NONE); + hZCommonLimit = FindConVar("z_common_limit"); + + hTotalZombies.AddChangeHook(CVAR_hTotalZombiesChanged); + CVAR_hTotalZombiesChanged(hTotalZombies, "0", "0"); + + //HookEvent("infected_death", Event_InfectedDeath); + + RegConsoleCmd("sm_population_list", Cmd_List, "Lists the current population percentages", FCVAR_NONE); + RegConsoleCmd("sm_populations", Cmd_List, "Lists the current population percentages", FCVAR_NONE); + + //AutoExecConfig(true, "l4d2_population_control"); +} + +public void OnGameStart(Event event, const char[] name, bool dontBroadcast) { + hPercentTotal.FloatValue = 1.0; + hPercentClown.FloatValue = 0.0; + hPercentMud.FloatValue = 0.0; + hPercentCeda.FloatValue = 0.0; + hPercentWorker.FloatValue = 0.0; + hPercentRiot.FloatValue = 0.0; + hPercentJimmy.FloatValue = 0.0; + hTotalZombies.FloatValue = 0.0; +} + +public void OnMapStart() { + for(int i = 0; i < COMMON_MODELS_COUNT; i++) { + PrecacheModel(INFECTED_MODELS[i], true); + } + for(int i = 0; i < 3; i++) { + PrecacheModel(WORKER_MODELS[i], true); + } + IsDoneLoading = true; +} +public void OnMapEnd() { + IsDoneLoading = false; + iCurrentCommons = 0; + clownCommonsSpawned = 0; +} + +public void CVAR_hTotalZombiesChanged(ConVar convar, const char[] oldValue, const char[] newValue) { + if(hTotalZombies.IntValue > 0) { + commonLimit = hTotalZombies.IntValue; + } else if(hTotalZombies.IntValue < 0) { + commonLimit = hZCommonLimit.IntValue - hTotalZombies.IntValue; + } else { + commonLimit = 0; + } +} + +//TODO: Setup music to play when % of clowns are in + +public void OnEntityCreated(int entity, const char[] classname) { + if (StrEqual(classname, "infected") && IsDoneLoading) { + SDKHook(entity, SDKHook_SpawnPost, Hook_SpawnPost); + + // char m_ModelName[PLATFORM_MAX_PATH]; + // GetEntPropString(entity, Prop_Data, "m_ModelName", m_ModelName, sizeof(m_ModelName)); + if(GetRandomFloat() <= hPercentTotal.FloatValue) { + if(GetRandomFloat() <= hPercentClown.FloatValue) { + SetEntityModel(entity, INFECTED_MODELS[Common_Clown]); + commonType[entity] = 2; + }else if(GetRandomFloat() <= hPercentMud.FloatValue) { + SetEntityModel(entity, INFECTED_MODELS[Common_Mud]); + commonType[entity] = 3; + }else if(GetRandomFloat() <= hPercentCeda.FloatValue) { + SetEntityModel(entity, INFECTED_MODELS[Common_Ceda]); + commonType[entity] = 4; + }else if(GetRandomFloat() <= hPercentWorker.FloatValue) { + //worker has multiple models: + SetEntityModel(entity, WORKER_MODELS[GetRandomInt(0,2)]); + commonType[entity] = 5; + }else if(GetRandomFloat() <= hPercentRiot.FloatValue) { + SetEntityModel(entity, INFECTED_MODELS[Common_Riot]); + commonType[entity] = 6; + }else if(GetRandomFloat() <= hPercentJimmy.FloatValue) { + SetEntityModel(entity, INFECTED_MODELS[Common_Jimmy]); + commonType[entity] = 7; + }else{ + commonType[entity] = 1; + } + }else{ + commonType[entity] = 1; + } + } +} + +public Action Hook_SpawnPost(int entity) { + if(commonLimit != 0) { + if(iCurrentCommons >= commonLimit) { + AcceptEntityInput(entity, "Kill"); + return Plugin_Continue; + } + } + ++iCurrentCommons; + if(commonType[entity] == 2) { + if(++clownCommonsSpawned > CLOWN_MUSIC_THRESHOLD && !clownMusicPlayed) { + clownMusicPlayed = true; + EmitSoundToAll("custom/clown.mp3"); + //Play music + } + } + return Plugin_Continue; +} + +// public Action Event_InfectedDeath(Event event, const char[] name, bool dontBroadcast) { +// --iCurrentCommons; +// if(commonType[entity] == 2) { +// --clownCommonsSpawned; +// } +// } + +public void OnEntityDestroyed(int entity) { + if(entity > 0 && entity <= 2048 && commonType[entity] > 0) { + commonType[entity] = 0; + if(commonType[entity] == 2) { + --clownCommonsSpawned; + } + if(--iCurrentCommons < CLOWN_MUSIC_THRESHOLD - 10) { + clownMusicPlayed = false; + } + } +} + +public Action Cmd_List(int client, int args) { + ReplyToCommand(client, "L4D2 Population Chances"); + ReplyToCommand(client, "%.1f%% global chance", hPercentTotal.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Clowns", hPercentClown.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Mud Commons", hPercentMud.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Ceda Commons", hPercentCeda.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Worker Commons", hPercentWorker.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Riot Commons", hPercentRiot.FloatValue * 100); + ReplyToCommand(client, "%.1f%% Jimmy Gibs", hPercentJimmy.FloatValue * 100); + ReplyToCommand(client, "%d total commons allowed", commonLimit); + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/l4d2_prophunt.sp b/scripting/l4d2_prophunt.sp new file mode 100644 index 0000000..4c7964c --- /dev/null +++ b/scripting/l4d2_prophunt.sp @@ -0,0 +1,432 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define BLIND_TIME 30 +#define DEFAULT_GAME_TIME 600 + +#include +#include +#include +#include +#include + + +enum GameState { + State_Unknown = 0, + State_Hiding, + State_Active, + State_PropsWin, + State_SeekerWin, +} + +#define MAX_VALID_MODELS 2 +char VALID_MODELS[MAX_VALID_MODELS][] = { + "models/props_crates/static_crate_40.mdl", + "models/props_junk/gnome.mdl" +}; + +#define SOUND_SWITCH_MODEL "buttons/button22.wav" + +#define TRANSPARENT "255 255 255 0" +#define WHITE "255 255 255 255" + +enum struct PropData { + int prop; + float verticalOffset; + bool rotationLock; +} + +UserMsg g_FadeUserMsgId; + +PropData propData[MAXPLAYERS+1]; + +bool isSeeker[MAXPLAYERS+1]; +bool hasBeenSeeker[MAXPLAYERS+1]; +bool isStarting, firstCheckDone; + +Handle timesUpTimer; +Handle waitTimer; + +StringMap propHealths; +PropHuntGame Game; + + +#include +#include + +public Plugin myinfo = +{ + name = "Prophunt", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D2 only."); + } + validMaps = new ArrayList(ByteCountToCells(64)); + validSets = new ArrayList(ByteCountToCells(16)); + mapConfigs = new StringMap(); + + Game.Init("PropHunt"); + + g_FadeUserMsgId = GetUserMessageId("Fade"); + + RegConsoleCmd("sm_game", Command_Test); + RegAdminCmd("sm_prophunt", Command_PropHunt, ADMFLAG_KICK); + RegAdminCmd("sm_ph", Command_PropHunt, ADMFLAG_KICK); + + ConVar hGamemode = FindConVar("mp_gamemode"); + hGamemode.AddChangeHook(Event_GamemodeChange); + Event_GamemodeChange(hGamemode, gamemode, gamemode); +} + +public void OnPluginEnd() { + OnMapEnd(); +} + +void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) { + waitTimer = CreateTimer(firstCheckDone ? 2.5 : 6.0, Timer_WaitForPlayers, _, TIMER_REPEAT); +} + +void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) { + // Skip the check, everyone's loaded in + firstCheckDone = true; +} + + +public void OnClientPutInServer(int client) { + if(!isEnabled) return; + if(IsFakeClient(client)) { + KickClient(client, "ph: Remove Special Infected"); + } else { + ChangeClientTeam(client, 1); + isPendingPlay[client] = true; + Game.Broadcast("%N will play next round", client); + Game.TeleportToSpawn(client); + } +} + + +public void OnClientDisconnect(int client) { + if(!isEnabled || IsFakeClient(client)) return; + ResetPlayerData(client); + if(Game.IsSeeker(client)) { + if(Game.SeekersAlive == 0) { + Game.Broadcast("All seekers have disconnected, Props win"); + Game.End(State_PropsWin); + } + } else if(Game.PropsAlive == 0) { + Game.Broadcast("All hiders have disconnected, Seekers win"); + Game.End(State_SeekerWin); + } +} + +public void Event_GamemodeChange(ConVar cvar, const char[] oldValue, const char[] newValue) { + cvar.GetString(gamemode, sizeof(gamemode)); + bool shouldEnable = StrEqual(gamemode, "prophunt", false); + if(isEnabled == shouldEnable) return; + firstCheckDone = false; + if(shouldEnable) { + Game.Broadcast("Gamemode is starting"); + HookEvent("round_start", Event_RoundStart); + HookEvent("round_end", Event_RoundEnd); + HookEvent("player_death", Event_PlayerDeath); + } else if(!lateLoaded) { + UnhookEvent("round_start", Event_RoundStart); + UnhookEvent("round_end", Event_RoundEnd); + UnhookEvent("player_death", Event_PlayerDeath); + Game.Cleanup(); + } + isEnabled = shouldEnable; +} + +public void OnMapStart() { + if(!isEnabled) return; + for(int i = 0; i < MAX_VALID_MODELS; i++) { + PrecacheModel(VALID_MODELS[i]); + } + PrecacheSound(SOUND_SWITCH_MODEL); + isStarting = false; + + char map[128]; + GetCurrentMap(map, sizeof(map)); + if(!StrEqual(g_currentMap, map)) { + firstCheckDone = false; + strcopy(g_currentSet, sizeof(g_currentSet), "default"); + ReloadPropDB(); + ReloadMapDB(); + strcopy(g_currentMap, sizeof(g_currentMap), map); + } + + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt", true); + + + if(lateLoaded) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + Game.SetupPlayer(i); + } + } + InitGamemode(); + } + + Game.State = State_Unknown; +} + +void InitGamemode() { + if(isStarting && Game.State != State_Unknown) { + Game.Warn("InitGamemode() called in an incorrect state (%d)", Game.State); + return; + } + SetupEntities(); + Game.DebugConsole("InitGamemode(): activating"); + ArrayList validPlayerIds = new ArrayList(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + if(IsFakeClient(i)) { + KickClient(i); + } else { + Game.SetupPlayer(i); + if(!IsPlayerAlive(i)) { + L4D_RespawnPlayer(i); + } + if(!hasBeenSeeker[i]) + validPlayerIds.Push(GetClientUserId(i)); + } + } + } + if(validPlayerIds.Length == 0) { + Game.Warn("Ignoring InitGamemode() with no valid survivors"); + return; + } + int numberOfSeekers = RoundToCeil(float(validPlayerIds.Length) / 3.0); + int timeout = 0; + while(numberOfSeekers > 0 && timeout < 2) { + int newSeeker = GetClientOfUserId(validPlayerIds.Get(GetURandomInt() % validPlayerIds.Length)); + if(newSeeker > 0) { + hasBeenSeeker[newSeeker] = true; + Game.SetSeeker(newSeeker, true); + Game.Broadcast("%N is a seeker", newSeeker); + numberOfSeekers--; + SetPlayerBlind(newSeeker, 255); + SetEntPropFloat(newSeeker, Prop_Send, "m_flLaggedMovementValue", 0.0); + } else { + timeout++; + } + } + delete validPlayerIds; + Game.TeleportAllToStart(); + Game.MapTime = BLIND_TIME; + Game.Tick = 0; + Game.State = State_Hiding; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && !Game.IsSeeker(i)) { + Game.SetupPropTeam(i); + } + } + CreateTimer(float(BLIND_TIME), Timer_StartGame); +} + +void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + if(!Game.IsSeeker(client)) { + if(attacker > 0) + PrintToChatAll("%N was killed by %N", client, attacker); + else + PrintToChatAll("%N died", client); + } + + ResetPlayerData(client); + + if(client > 0 && Game.State == State_Active) { + if(Game.SeekersAlive == 0) { + Game.Broadcast("All seekers have perished. Hiders win!"); + Game.End(State_PropsWin); + } else if(Game.PropsAlive == 0) { + Game.Broadcast("Seekers win!"); + Game.End(State_SeekerWin); + } + } +} + +void ResetPlayerData(int client) { + if(propData[client].prop > 0 && IsValidEntity(propData[client].prop)) { + AcceptEntityInput(propData[client].prop, "Kill"); + propData[client].prop = 0; + } + propData[client].rotationLock = false; +} + +public void OnMapEnd() { + for(int i = 1; i <= MaxClients; i++) { + ResetPlayerData(i); + if(IsClientConnected(i) && IsClientInGame(i)) { + Game.UnsetupPlayer(i); + } + } +} + +void ClearInventory(int client) { + for(int i = 0; i <= 5; i++) { + int item = GetPlayerWeaponSlot(client, i); + if(item > 0) { + AcceptEntityInput(item, "Kill"); + } + } +} + +public Action Command_Test(int client, int args) { + InitGamemode(); + return Plugin_Handled; +} + +Action OnPropTransmit(int entity, int client) { + return propData[client].prop == entity ? Plugin_Stop : Plugin_Continue; +} + +Action OnPlayerTransmit(int entity, int client) { + return entity == client ? Plugin_Continue : Plugin_Stop; +} + +int CreatePropInternal(const char[] model) { + int entity = CreateEntityByName("prop_physics_override"); + DispatchKeyValue(entity, "model", model); + DispatchKeyValue(entity, "disableshadows", "1"); + DispatchKeyValue(entity, "targetname", "phprop"); + DispatchSpawn(entity); + SetEntProp(entity, Prop_Send, "m_nSolidType", 6); + SetEntProp(entity, Prop_Send, "m_CollisionGroup", 1); + SetEntProp(entity, Prop_Send, "movetype", MOVETYPE_NONE); + return entity; +} + +stock int CloneProp(int prop) { + char model[64]; + GetEntPropString(prop, Prop_Data, "m_ModelName", model, sizeof(model)); + return CreatePropInternal(model); +} + +stock void GlowNearbyProps(int client, float range, bool optimizeRange = false) { + int entity = INVALID_ENT_REFERENCE; + static float pos[3], clientPos[3]; + GetClientAbsOrigin(client, clientPos); + static char model[64]; + while ((entity = FindEntityByClassname(entity, "prop_dynamic")) != -1) { + GetEntPropVector(entity, Prop_Data, "m_vecOrigin", pos); + float distance = GetVectorDistance(clientPos, pos, optimizeRange); + if (distance < range) { + GetEntPropString(entity, Prop_Data, "m_ModelName", model, sizeof(model)); + GlowEntity(entity, client, 2.0); + } + } + while ((entity = FindEntityByClassname(entity, "prop_physics")) != -1) { + GetEntPropVector(entity, Prop_Data, "m_vecOrigin", pos); + float distance = GetVectorDistance(clientPos, pos, optimizeRange); + if (distance < range) { + GetEntPropString(entity, Prop_Data, "m_ModelName", model, sizeof(model)); + GlowEntity(entity, client, 2.0); + } + } +} + +static int COLOR_PROPFINDER[4] = { 255, 255, 255, 128 }; + +stock void GlowEntity(int entity, int client, float lifetime = 5.0) { + static float pos[3], mins[3], maxs[3], ang[3]; + GetEntPropVector(entity, Prop_Data, "m_vecOrigin", pos); + GetEntPropVector(entity, Prop_Data, "m_vecMins", mins); + GetEntPropVector(entity, Prop_Data, "m_vecMaxs", maxs); + GetEntPropVector(entity, Prop_Data, "m_angRotation", ang); + + Effect_DrawBeamBoxRotatableToClient(client, pos, mins, maxs, ang, g_iLaserIndex, 0, 0, 1, lifetime, 1.0, 1.0, 100, 0.1, COLOR_PROPFINDER, 0.0); +} + +public Action OnPlayerRunCmd(int client, int& buttons, int& impulse, float vel[3], float angles[3], int& weapon, int& subtype, int& cmdnum, int& tickcount, int& seed, int mouse[2]) { + if(!isEnabled || !IsPlayerAlive(client) || GetClientTeam(client) < 2 || Game.IsSeeker(client)) return Plugin_Continue; + // TODO: Check team + int oldButtons = GetEntProp(client, Prop_Data, "m_nOldButtons"); + if(buttons & IN_RELOAD && !(oldButtons & IN_RELOAD)) { + propData[client].rotationLock = !propData[client].rotationLock; + PrintHintText(client, "Rotation lock now %s", propData[client].rotationLock ? "enabled" : "disabled"); + return Plugin_Continue; + } else if(buttons & IN_ATTACK && !(oldButtons & IN_ATTACK)) { + GlowNearbyProps(client, 200.0); + int lookAtProp = GetLookingProp(client, 100.0); + if(lookAtProp > 0) { + int prop = CloneProp(lookAtProp); + if(prop > 0) { + EmitSoundToClient(client, SOUND_SWITCH_MODEL); + Game.SetupProp(client, prop); + PrintHintText(client, "Changed prop"); + SetEntPropFloat(client, Prop_Send, "m_flNextAttack", GetGameTime() + 1.0); + return Plugin_Handled; + } + } + } + if(propData[client].prop > 0 && IsValidEntity(propData[client].prop)) { + static float pos[3], ang[3]; + GetClientAbsOrigin(client, pos); + TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR); + pos[2] += propData[client].verticalOffset; + if(propData[client].rotationLock) + TeleportEntity(propData[client].prop, pos, NULL_VECTOR, NULL_VECTOR); + else { + ang[0] = 0.0; + ang[1] = angles[1]; + ang[2] = 0.0; + TeleportEntity(propData[client].prop, pos, ang, NULL_VECTOR); + } + } + return Plugin_Continue; +} + +int GetLookingProp(int client, float distance = 0.0, bool optimizeDist = false) { + static float pos[3], ang[3]; + GetClientEyePosition(client, pos); + GetClientEyeAngles(client, ang); + TR_TraceRayFilter(pos, ang, MASK_SHOT, RayType_Infinite, Filter_FindProp, propData[client].prop); + if(TR_DidHit()) { + if(distance > 0) { + TR_GetEndPosition(ang); + if(GetVectorDistance(pos, ang, optimizeDist) > distance) { + return -1; + } + } + return TR_GetEntityIndex(); + } + return -1; +} + +bool Filter_FindProp(int entity, int mask, int data) { + if(entity <= MaxClients || data == entity) return false; + static char classname[32]; + GetEntityClassname(entity, classname, sizeof(classname)); + return StrEqual(classname, "prop_dynamic") || StrEqual(classname, "prop_physics"); +} + +Action OnTakeDamageAlive(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + if(attacker > MaxClients || Game.IsSeeker(attacker)) { + if(victim <= MaxClients && victim > 0) { + damage = 5.0; + return Plugin_Changed; + } else { + SDKHooks_TakeDamage(attacker, 0, 0, 10.0, DMG_DIRECT); + damage = 0.0; + return Plugin_Handled; + } + } else if(attacker == victim || attacker == 0) { + return Plugin_Continue; + } else { + damage = 0.0; + return Plugin_Handled; + } +} diff --git a/scripting/l4d2_randomizer.sp b/scripting/l4d2_randomizer.sp new file mode 100644 index 0000000..f7d98a7 --- /dev/null +++ b/scripting/l4d2_randomizer.sp @@ -0,0 +1,781 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define DEBUG_SCENE_PARSE 1 +#define DEBUG_BLOCKERS 1 + +#include +#include +//#include +#include +#include +#include +#include + +int g_iLaserIndex; +#if defined DEBUG_BLOCKERS +#include +#endif +#define ENT_PROP_NAME "l4d2_randomizer" +#define ENT_ENV_NAME "l4d2_randomizer" +#define ENT_BLOCKER_NAME "l4d2_randomizer" +#include + +#define MAX_SCENE_NAME_LENGTH 32 +#define MAX_INPUTS_CLASSNAME_LENGTH 64 + +public Plugin myinfo = +{ + name = "L4D2 Randomizer", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +ConVar cvarEnabled; +enum struct ActiveSceneData { + char name[MAX_SCENE_NAME_LENGTH]; + int variantIndex; +} +MapData g_MapData; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + RegAdminCmd("sm_rcycle", Command_CycleRandom, ADMFLAG_CHEATS); + RegAdminCmd("sm_expent", Command_ExportEnt, ADMFLAG_GENERIC); + + cvarEnabled = CreateConVar("sm_randomizer_enabled", "0"); + + g_MapData.activeScenes = new ArrayList(sizeof(ActiveSceneData)); +} + +char currentMap[64]; + +// TODO: on round start +public void OnMapStart() { + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt", true); + GetCurrentMap(currentMap, sizeof(currentMap)); +} + +public void OnMapEnd() { + Cleanup(); +} + +bool hasRan; +public void OnMapInit(const char[] map) { + if(cvarEnabled.BoolValue) { + if(LoadMapData(currentMap, FLAG_NONE) && g_MapData.lumpEdits.Length > 0) { + Log("Found %d lump edits, running...", g_MapData.lumpEdits.Length); + LumpEditData lump; + for(int i = 0; i < g_MapData.lumpEdits.Length; i++) { + g_MapData.lumpEdits.GetArray(i, lump); + lump.Trigger(); + } + } + } + hasRan = false; +} + +public void OnClientPutInServer(int client) { + if(!hasRan) { + hasRan = true; + if(cvarEnabled.BoolValue) + RunMap(currentMap, FLAG_NONE); + } +} + +stock int GetLookingEntity(int client, TraceEntityFilter filter) { + float pos[3], ang[3]; + GetClientEyePosition(client, pos); + GetClientEyeAngles(client, ang); + TR_TraceRayFilter(pos, ang, MASK_SOLID, RayType_Infinite, filter, client); + if(TR_DidHit()) { + return TR_GetEntityIndex(); + } + return -1; +} + +stock int GetLookingPosition(int client, TraceEntityFilter filter, float pos[3]) { + float ang[3]; + GetClientEyePosition(client, pos); + GetClientEyeAngles(client, ang); + TR_TraceRayFilter(pos, ang, MASK_SOLID, RayType_Infinite, filter, client); + if(TR_DidHit()) { + TR_GetEndPosition(pos); + return TR_GetEntityIndex(); + } + return -1; +} + + +public Action Command_CycleRandom(int client, int args) { + if(args > 0) { + DeleteCustomEnts(); + + char arg1[8]; + GetCmdArg(1, arg1, sizeof(arg1)); + int flags = StringToInt(arg1) | view_as(FLAG_REFRESH); + RunMap(currentMap, flags); + if(client > 0) + PrintCenterText(client, "Cycled flags=%d", flags); + } else { + ReplyToCommand(client, "Active Scenes:"); + ActiveSceneData scene; + for(int i = 0; i < g_MapData.activeScenes.Length; i++) { + g_MapData.activeScenes.GetArray(i, scene); + ReplyToCommand(client, "\t%s: variant #%d", scene.name, scene.variantIndex); + } + } + return Plugin_Handled; +} + +public Action Command_ExportEnt(int client, int args) { + float origin[3]; + int entity = GetLookingPosition(client, Filter_IgnorePlayer, origin); + float angles[3]; + float size[3]; + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + if(entity > 0) { + + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", origin); + GetEntPropVector(entity, Prop_Send, "m_angRotation", angles); + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", size); + + char model[64]; + ReplyToCommand(client, "{"); + GetEntityClassname(entity, model, sizeof(model)); + if(StrContains(model, "prop_") == -1) { + ReplyToCommand(client, "\t\"scale\": [%.2f, %.2f, %.2f],", size[0], size[1], size[2]); + } + if(StrEqual(arg1, "hammerid")) { + int hammerid = GetEntProp(entity, Prop_Data, "m_iHammerID"); + ReplyToCommand(client, "\t\"type\": \"hammerid\","); + ReplyToCommand(client, "\t\"model\": \"%d\",", hammerid); + } else if(StrEqual(arg1, "targetname")) { + GetEntPropString(entity, Prop_Data, "m_iName", model, sizeof(model)); + ReplyToCommand(client, "\t\"type\": \"targetname\","); + ReplyToCommand(client, "\t\"model\": \"%s\",", model); + } else { + GetEntPropString(entity, Prop_Data, "m_ModelName", model, sizeof(model)); + ReplyToCommand(client, "\t\"model\": \"%s\",", model); + } + ReplyToCommand(client, "\t\"origin\": [%.2f, %.2f, %.2f],", origin[0], origin[1], origin[2]); + ReplyToCommand(client, "\t\"angles\": [%.2f, %.2f, %.2f]", angles[0], angles[1], angles[2]); + ReplyToCommand(client, "}"); + } else { + if(!StrEqual(arg1, "cursor")) + GetEntPropVector(client, Prop_Send, "m_vecOrigin", origin); + GetEntPropVector(client, Prop_Send, "m_angRotation", angles); + ReplyToCommand(client, "{"); + ReplyToCommand(client, "\t\"type\": \"%s\",", arg1); + ReplyToCommand(client, "\t\"scale\": [%.2f, %.2f, %.2f],", size[0], size[1], size[2]); + ReplyToCommand(client, "\t\"origin\": [%.2f, %.2f, %.2f],", origin[0], origin[1], origin[2]); + ReplyToCommand(client, "\t\"angles\": [%.2f, %.2f, %.2f]", angles[0], angles[1], angles[2]); + ReplyToCommand(client, "}"); + } + return Plugin_Handled; +} + + +enum struct SceneData { + char name[MAX_SCENE_NAME_LENGTH]; + float chance; + char group[MAX_SCENE_NAME_LENGTH]; + ArrayList variants; + + void Cleanup() { + g_MapData.activeScenes.Clear(); + SceneVariantData choice; + for(int i = 0; i < this.variants.Length; i++) { + this.variants.GetArray(i, choice); + choice.Cleanup(); + } + delete this.variants; + } +} + +enum struct SceneVariantData { + int weight; + ArrayList inputsList; + ArrayList entities; + + void Cleanup() { + delete this.inputsList; + delete this.entities; + } +} + +enum struct VariantEntityData { + char type[32]; + char model[64]; + float origin[3]; + float angles[3]; + float scale[3]; + int color[4]; +} + +enum InputType { + Input_Classname, + Input_Targetname, + Input_HammerId +} +enum struct VariantInputData { + char name[MAX_INPUTS_CLASSNAME_LENGTH]; + InputType type; + char input[32]; + + void Trigger() { + int entity = -1; + switch(this.type) { + case Input_Classname: { + entity = FindEntityByClassname(entity, this.name); + this._trigger(entity); + } + case Input_Targetname: { + char targetname[32]; + while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, this.name)) { + this._trigger(entity); + } + } + } + case Input_HammerId: { + int targetId = StringToInt(this.name); + while((entity = FindEntityByClassname(entity, "*")) != INVALID_ENT_REFERENCE) { + int hammerId = GetEntProp(entity, Prop_Data, "m_iHammerID"); + if(hammerId == targetId ) { + this._trigger(entity); + break; + } + } + } + } + } + + void _trigger(int entity) { + if(entity > 0 && IsValidEntity(entity)) { + if(StrEqual(this.input, "_allow_ladder")) { + if(HasEntProp(entity, Prop_Send, "m_iTeamNum")) { + SetEntProp(entity, Prop_Send, "m_iTeamNum", 0); + } else { + Log("Warn: Entity (%d) with id \"%s\" has no teamnum for \"_allow_ladder\"", entity, this.name); + } + } else if(StrEqual(this.input, "_lock")) { + AcceptEntityInput(entity, "Close"); + AcceptEntityInput(entity, "Lock"); + } else if(StrEqual(this.input, "_lock_nobreak")) { + AcceptEntityInput(entity, "Close"); + AcceptEntityInput(entity, "Lock"); + AcceptEntityInput(entity, "SetUnbreakable"); + }else { + char cmd[32]; + // Split input "a b" to a with variant "b" + int len = SplitString(this.input, " ", cmd, sizeof(cmd)); + if(len > -1) SetVariantString(this.input[len]); + + Debug("_trigger(%d): %s (v=%s)", entity, this.input, cmd); + AcceptEntityInput(entity, this.input); + } + } + } +} + +enum struct LumpEditData { + char name[MAX_INPUTS_CLASSNAME_LENGTH]; + InputType type; + char action[32]; + char value[64]; + + int _findLumpIndex(int startIndex = 0, EntityLumpEntry entry) { + int length = EntityLump.Length(); + char val[64]; + Debug("Scanning for \"%s\" (type=%d)", this.name, this.type); + for(int i = startIndex; i < length; i++) { + entry = EntityLump.Get(i); + int index = entry.FindKey("hammerid"); + if(index != -1) { + entry.Get(index, "", 0, val, sizeof(val)); + if(StrEqual(val, this.name)) { + return i; + } + } + + index = entry.FindKey("classname"); + if(index != -1) { + entry.Get(index, "", 0, val, sizeof(val)); + Debug("%s vs %s", val, this.name); + if(StrEqual(val, this.name)) { + return i; + } + } + + index = entry.FindKey("targetname"); + if(index != -1) { + entry.Get(index, "", 0, val, sizeof(val)); + if(StrEqual(val, this.name)) { + return i; + } + } + delete entry; + } + Log("Warn: Could not find any matching lump for \"%s\" (type=%d)", this.name, this.type); + return -1; + } + + void Trigger() { + int index = 0; + EntityLumpEntry entry; + while((index = this._findLumpIndex(index, entry) != -1)) { + // for(int i = 0; i < entry.Length; i++) { + // entry.Get(i, a, sizeof(a), v, sizeof(v)); + // Debug("%s=%s", a, v); + // } + this._trigger(entry); + } + } + + void _updateKey(EntityLumpEntry entry, const char[] key, const char[] value) { + int index = entry.FindKey(key); + if(index != -1) { + Debug("update key %s = %s", key, value); + entry.Update(index, key, value); + } + } + + void _trigger(EntityLumpEntry entry) { + if(StrEqual(this.action, "setclassname")) { + this._updateKey(entry, "classname", this.value); + } + + delete entry; + } +} + +enum struct MapData { + ArrayList scenes; + ArrayList lumpEdits; + ArrayList activeScenes; +} + +enum loadFlags { + FLAG_NONE = 0, + FLAG_ALL_SCENES = 1, // Pick all scenes, no random chance + FLAG_ALL_VARIANTS = 2, // Pick all variants (for debug purposes), + FLAG_REFRESH = 4, // Load data bypassing cache +} + +// Reads (mapname).json file and parses it +public bool LoadMapData(const char[] map, int flags) { + Debug("Loading config for %s", map); + char filePath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, filePath, sizeof(filePath), "data/randomizer/%s.json", map); + if(!FileExists(filePath)) { + Log("[Randomizer] No map config file (data/randomizer/%s.json), not loading", map); + return false; + } + + char buffer[65536]; + File file = OpenFile(filePath, "r"); + if(file == null) { + LogError("Could not open map config file (data/randomizer/%s.json)", map); + return false; + } + file.ReadString(buffer, sizeof(buffer)); + JSON_Object data = json_decode(buffer); + if(data == null) { + json_get_last_error(buffer, sizeof(buffer)); + LogError("Could not parse map config file (data/randomizer/%s.json): %s", map, buffer); + delete file; + return false; + } + + Debug("Starting parsing json data"); + + Cleanup(); + g_MapData.scenes = new ArrayList(sizeof(SceneData)); + g_MapData.lumpEdits = new ArrayList(sizeof(LumpEditData)); + g_MapData.activeScenes.Clear(); + + Profiler profiler = new Profiler(); + profiler.Start(); + + int length = data.Length; + char key[32]; + for (int i = 0; i < length; i += 1) { + data.GetKey(i, key, sizeof(key)); + + if(key[0] == '_') { + if(StrEqual(key, "_lumps")) { + JSON_Array lumpsList = view_as(data.GetObject(key)); + if(lumpsList != null) { + for(int l = 0; l < lumpsList.Length; l++) { + loadLumpData(g_MapData.lumpEdits, lumpsList.GetObject(l)); + } + } + } else { + Debug("Unknown special entry \"%s\", skipping", key); + } + } else { + if(data.GetType(key) != JSON_Type_Object) { + Debug("Invalid normal entry \"%s\" (not an object), skipping", key); + continue; + } + JSON_Object scene = data.GetObject(key); + // Parses scene data and inserts to scenes + loadScene(key, scene); + } + } + + json_cleanup_and_delete(data); + profiler.Stop(); + Log("Parsed map file and found %d scenes in %.4f seconds", g_MapData.scenes.Length, profiler.Time); + delete profiler; + delete file; + return true; +} + +// Calls LoadMapData (read&parse (mapname).json) then select scenes +public bool RunMap(const char[] map, int flags) { + if(g_MapData.scenes == null || flags & view_as(FLAG_REFRESH)) { + LoadMapData(map, flags); + } + Profiler profiler = new Profiler(); + + profiler.Start(); + selectScenes(flags); + profiler.Stop(); + + Log("Done processing in %.4f seconds", g_MapData.scenes.Length, profiler.Time); + return true; +} + +void loadScene(const char key[MAX_SCENE_NAME_LENGTH], JSON_Object sceneData) { + SceneData scene; + scene.name = key; + scene.chance = sceneData.GetFloat("chance"); + if(scene.chance < 0.0 || scene.chance > 1.0) { + LogError("Scene \"%s\" has invalid chance (%f)", scene.name, scene.chance); + return; + } + sceneData.GetString("group", scene.group, sizeof(scene.group)); + scene.variants = new ArrayList(sizeof(SceneVariantData)); + JSON_Array variants = view_as(sceneData.GetObject("variants")); + for(int i = 0; i < variants.Length; i++) { + // Parses choice and loads to scene.choices + loadChoice(scene, variants.GetObject(i)); + } + g_MapData.scenes.PushArray(scene); +} + +void loadChoice(SceneData scene, JSON_Object choiceData) { + SceneVariantData choice; + choice.weight = choiceData.GetInt("weight", 1); + choice.entities = new ArrayList(sizeof(VariantEntityData)); + choice.inputsList = new ArrayList(sizeof(VariantInputData)); + JSON_Array entities = view_as(choiceData.GetObject("entities")); + if(entities != null) { + for(int i = 0; i < entities.Length; i++) { + // Parses entities and loads to choice.entities + loadChoiceEntity(choice.entities, entities.GetObject(i)); + } + } + JSON_Array inputsList = view_as(choiceData.GetObject("inputs")); + if(inputsList != null) { + for(int i = 0; i < inputsList.Length; i++) { + loadChoiceInput(choice.inputsList, inputsList.GetObject(i)); + } + } + scene.variants.PushArray(choice); +} + +void loadChoiceInput(ArrayList list, JSON_Object inputData) { + VariantInputData input; + // Check classname -> targetname -> hammerid + if(!inputData.GetString("classname", input.name, sizeof(input.name))) { + if(inputData.GetString("targetname", input.name, sizeof(input.name))) { + input.type = Input_Targetname; + } else { + if(inputData.GetString("hammerid", input.name, sizeof(input.name))) { + input.type = Input_HammerId; + } else { + int id = inputData.GetInt("hammerid"); + if(id > 0) { + input.type = Input_HammerId; + IntToString(id, input.name, sizeof(input.name)); + } else { + LogError("Missing valid input specification (hammerid, classname, targetname)"); + return; + } + } + } + } + inputData.GetString("input", input.input, sizeof(input.input)); + list.PushArray(input); +} + +void loadLumpData(ArrayList list, JSON_Object inputData) { + LumpEditData input; + // Check classname -> targetname -> hammerid + if(!inputData.GetString("classname", input.name, sizeof(input.name))) { + if(inputData.GetString("targetname", input.name, sizeof(input.name))) { + input.type = Input_Targetname; + } else { + if(inputData.GetString("hammerid", input.name, sizeof(input.name))) { + input.type = Input_HammerId; + } else { + int id = inputData.GetInt("hammerid"); + if(id > 0) { + input.type = Input_HammerId; + IntToString(id, input.name, sizeof(input.name)); + } else { + LogError("Missing valid input specification (hammerid, classname, targetname)"); + return; + } + } + } + } + inputData.GetString("action", input.action, sizeof(input.action)); + inputData.GetString("value", input.value, sizeof(input.value)); + list.PushArray(input); +} + +void loadChoiceEntity(ArrayList list, JSON_Object entityData) { + VariantEntityData entity; + entityData.GetString("model", entity.model, sizeof(entity.model)); + if(!entityData.GetString("type", entity.type, sizeof(entity.type))) { + entity.type = "prop_dynamic"; + } else if(entity.type[0] == '_') { + LogError("Invalid custom entity type \"%s\"", entity.type); + return; + } + GetVector(entityData, "origin", entity.origin); + GetVector(entityData, "angles", entity.angles); + GetVector(entityData, "scale", entity.scale); + GetColor(entityData, "color", entity.color); + list.PushArray(entity); +} + +void GetVector(JSON_Object obj, const char[] key, float out[3]) { + JSON_Array vecArray = view_as(obj.GetObject(key)); + if(vecArray != null) { + out[0] = vecArray.GetFloat(0); + out[1] = vecArray.GetFloat(1); + out[2] = vecArray.GetFloat(2); + } +} + +void GetColor(JSON_Object obj, const char[] key, int out[4]) { + JSON_Array vecArray = view_as(obj.GetObject(key)); + if(vecArray != null) { + out[0] = vecArray.GetInt(0); + out[1] = vecArray.GetInt(1); + out[2] = vecArray.GetInt(2); + if(vecArray.Length == 4) + out[3] = vecArray.GetInt(3); + else + out[3] = 255; + } else { + out[0] = 255; + out[1] = 255; + out[2] = 255; + out[3] = 255; + } +} + +void selectScenes(int flags = 0) { + SceneData scene; + StringMap groups = new StringMap(); + ArrayList list; + for(int i = 0; i < g_MapData.scenes.Length; i++) { + g_MapData.scenes.GetArray(i, scene); + // TODO: Exclusions + // Select scene if not in group, or add to list of groups + if(scene.group[0] == '\0') { + selectScene(scene, flags); + } else { + if(!groups.GetValue(scene.group, list)) { + list = new ArrayList(); + } + list.Push(i); + groups.SetValue(scene.group, list); + } + } + + StringMapSnapshot snapshot = groups.Snapshot(); + char key[MAX_SCENE_NAME_LENGTH]; + for(int i = 0; i < snapshot.Length; i++) { + snapshot.GetKey(i, key, sizeof(key)); + groups.GetValue(key, list); + int index = GetURandomInt() % list.Length; + index = list.Get(index); + g_MapData.scenes.GetArray(index, scene); + Debug("Selected scene \"%s\" for group %s (%d members)", scene.name, key, list.Length); + selectScene(scene, flags); + delete list; + } + delete snapshot; + delete groups; +} + +void selectScene(SceneData scene, int flags) { + // Use the .chance field unless FLAG_ALL_SCENES is set + if(~flags & view_as(FLAG_ALL_SCENES) && GetURandomFloat() > scene.chance) { + return; + } + + if(scene.variants.Length == 0) { + LogError("Warn: No variants were found for scene \"%s\"", scene.name); + return; + } + + ArrayList choices = new ArrayList(); + SceneVariantData choice; + int index; + // Weighted random: Push N times dependent on weight + for(int i = 0; i < scene.variants.Length; i++) { + scene.variants.GetArray(i, choice); + if(flags & view_as(FLAG_ALL_VARIANTS)) { + spawnVariant(choice); + } else { + for(int c = 0; c < choice.weight; c++) { + choices.Push(i); + } + } + } + if(flags & view_as(FLAG_ALL_VARIANTS)) { + delete choices; + } else { + index = GetURandomInt() % choices.Length; + index = choices.Get(index); + delete choices; + Log("Spawned scene \"%s\" with variant #%d", scene.name, index); + scene.variants.GetArray(index, choice); + spawnVariant(choice); + } + + ActiveSceneData aScene; + strcopy(aScene.name, sizeof(aScene.name), scene.name); + aScene.variantIndex = index; + g_MapData.activeScenes.PushArray(aScene); +} + +void spawnVariant(SceneVariantData choice) { + VariantEntityData entity; + for(int i = 0; i < choice.entities.Length; i++) { + choice.entities.GetArray(i, entity); + spawnEntity(entity); + } + + if(choice.inputsList.Length > 0) { + VariantInputData input; + for(int i = 0; i < choice.inputsList.Length; i++) { + choice.inputsList.GetArray(i, input); + input.Trigger(); + } + } +} + +void spawnEntity(VariantEntityData entity) { + if(StrEqual(entity.type, "env_fire")) { + Debug("spawning \"%s\" at (%.1f %.1f %.1f) rot (%.0f %.0f %.0f)", entity.type, entity.origin[0], entity.origin[1], entity.origin[2], entity.angles[0], entity.angles[1], entity.angles[2]); + CreateFire(entity.origin, 20.0, 100.0, 0.0); + } else if(StrEqual(entity.type, "env_physics_blocker") || StrEqual(entity.type, "env_player_blocker")) { + CreateEnvBlockerScaled(entity.type, entity.origin, entity.scale); + } else if(StrEqual(entity.type, "infodecal")) { + CreateDecal(entity.model, entity.origin); + } else if(StrContains(entity.type, "prop_") == 0) { + if(entity.model[0] == '\0') { + LogError("Missing model for entity with type \"%s\"", entity.type); + return; + } + PrecacheModel(entity.model); + int prop = CreateProp(entity.type, entity.model, entity.origin, entity.angles); + SetEntityRenderColor(prop, entity.color[0], entity.color[1], entity.color[2], entity.color[3]); + } else if(StrEqual(entity.type, "hammerid")) { + int targetId = StringToInt(entity.model); + if(targetId > 0) { + int ent = -1; + while((ent = FindEntityByClassname(ent, "*")) != INVALID_ENT_REFERENCE) { + int hammerId = GetEntProp(ent, Prop_Data, "m_iHammerID"); + if(hammerId == targetId) { + Debug("moved entity (hammerid=%d) to %.0f %.0f %.0f rot %.0f %.0f %.0f", targetId, entity.origin[0], entity.origin[1], entity.origin[2], entity.angles[0], entity.angles[1], entity.angles[2]); + TeleportEntity(ent, entity.origin, entity.angles, NULL_VECTOR); + return; + } + } + } + Debug("Warn: Could not find entity (hammerid=%d) (model=%s)", targetId, entity.model); + } else if(StrEqual(entity.type, "targetname")) { + int ent = -1; + char targetname[64]; + bool found = false; + while((ent = FindEntityByClassname(ent, "*")) != INVALID_ENT_REFERENCE) { + GetEntPropString(ent, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(entity.model, targetname)) { + Debug("moved entity (targetname=%s) to %.0f %.0f %.0f rot %.0f %.0f %.0f", entity.model, entity.origin[0], entity.origin[1], entity.origin[2], entity.angles[0], entity.angles[1], entity.angles[2]); + TeleportEntity(ent, entity.origin, entity.angles, NULL_VECTOR); + found = true; + } + } + if(!found) + Debug("Warn: Could not find entity (targetname=%s)", entity.model); + } else if(StrEqual(entity.type, "classname")) { + int ent = -1; + char classname[64]; + bool found; + while((ent = FindEntityByClassname(ent, classname)) != INVALID_ENT_REFERENCE) { + Debug("moved entity (classname=%s) to %.0f %.0f %.0f rot %.0f %.0f %.0f", entity.model, entity.origin[0], entity.origin[1], entity.origin[2], entity.angles[0], entity.angles[1], entity.angles[2]); + TeleportEntity(ent, entity.origin, entity.angles, NULL_VECTOR); + found = true; + } + if(!found) + Debug("Warn: Could not find entity (classname=%s)", entity.model); + } else { + LogError("Unknown entity type \"%s\"", entity.type); + } +} + +void Debug(const char[] format, any ...) { + #if defined DEBUG_SCENE_PARSE + char buffer[192]; + + VFormat(buffer, sizeof(buffer), format, 2); + + PrintToServer("[Randomizer::Debug] %s", buffer); + PrintToConsoleAll("[Randomizer::Debug] %s", buffer); + + #endif +} + +void Log(const char[] format, any ...) { + char buffer[192]; + + VFormat(buffer, sizeof(buffer), format, 2); + + PrintToServer("[Randomizer] %s", buffer); +} + +void Cleanup() { + if(g_MapData.scenes != null) { + SceneData scene; + for(int i = 0; i < g_MapData.scenes.Length; i++) { + g_MapData.scenes.GetArray(i, scene); + scene.Cleanup(); + } + delete g_MapData.scenes; + } + delete g_MapData.lumpEdits; + + DeleteCustomEnts(); + g_MapData.activeScenes.Clear(); +} \ No newline at end of file diff --git a/scripting/l4d2_rollback.sp b/scripting/l4d2_rollback.sp new file mode 100644 index 0000000..31598a1 --- /dev/null +++ b/scripting/l4d2_rollback.sp @@ -0,0 +1,398 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define MAXIMUM_STAGES_STORED 3 //The maximum amount of ages to store +#define LAST_FF_TIME_THRESHOLD 100.0 +#define LAST_PLAYER_JOIN_THRESHOLD 120.0 + +#include +#include +#include +#include + +static Handle hRoundRespawn; + +public Plugin myinfo = +{ + name = "L4D2 Rollback", + author = "jackzmc", + description = "System to save and rollback to states in the game, usually pre-troll", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +enum struct PlayerInventory { + char primarySlot[64]; + char secondarySlot[32]; + char throwableSlot[32]; + char usableSlot[32]; + char consumableSlot[32]; +} + +enum struct PlayerState { + int incapState; //0 -> Not incapped, # -> # of incap + bool isAlive; + PlayerInventory inventory; + + int permHealth; + float tempHealth; + + float position[3]; + float angles[3]; + + char recordReason[32]; + int timestamp; +} + +static PlayerState playerStatesList[MAXIMUM_STAGES_STORED][MAXPLAYERS+1]; //Newest -> Oldest + +static bool isHealing[MAXPLAYERS+1], bMapStarted; //Is player healing (self, or other) +static ConVar hMaxIncapCount, hDecayRate; +static Handle hAutoSaveTimer; + +static float ZERO_VECTOR[3] = {0.0, 0.0, 0.0}, lastDamageTime, lastSpawnTime; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + Handle hGameConf = LoadGameConfigFile("left4dhooks.l4d2"); + if (hGameConf != INVALID_HANDLE) { + StartPrepSDKCall(SDKCall_Player); + PrepSDKCall_SetFromConf(hGameConf, SDKConf_Signature, "RoundRespawn"); + hRoundRespawn = EndPrepSDKCall(); + if (hRoundRespawn == INVALID_HANDLE) SetFailState("L4D2_Rollback: RoundRespawn Signature broken"); + + } else { + SetFailState("Could not find gamedata: l4d2_rollback.txt."); + } + + hMaxIncapCount = FindConVar("survivor_max_incapacitated_count"); + hDecayRate = FindConVar("pain_pills_decay_rate"); + + HookEvent("heal_begin", Event_HealBegin); + HookEvent("heal_end", Event_HealStop); + + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + HookEvent("player_hurt", Event_PlayerHurt); + HookEvent("revive_begin", Event_ReviveBegin); + + RegAdminCmd("sm_save", Command_SaveGlobalState, ADMFLAG_ROOT, "Saves all players state"); + RegAdminCmd("sm_state", Command_ViewStateInfo, ADMFLAG_ROOT, "Views the current state info"); + RegAdminCmd("sm_restore", Command_RestoreState, ADMFLAG_ROOT, "Restores a certain player's state"); + +} + +// ///////////////////////////////////////////////////////////////////////////// +// COMMANDS +// ///////////////////////////////////////////////////////////////////////////// + +public Action Command_SaveGlobalState(int client, int args) { + RecordGlobalState("MANUAL"); + ReplyToCommand(client, "Saved global state"); + return Plugin_Handled; +} +public Action Command_ViewStateInfo(int client, int args) { + int time = GetTime(), index; + for(int state = 0; state < MAXIMUM_STAGES_STORED; state++) { + if(state == 0 || playerStatesList[state][0].timestamp > 0) + ReplyToCommand(client, "---== Recorded Player States ==--- [Age: %d]", state); + for(int i = 1; i <= MaxClients; i++) { + if(playerStatesList[state][i].timestamp > 0) { + int minutes = RoundToNearest((time - playerStatesList[state][i].timestamp) / 60.0); + ReplyToCommand(client, "%2.d. %-16.16N | %-16.20s | %3d min. ago", ++index, i, playerStatesList[state][i].recordReason, minutes); + } + } + index = 0; + } + return Plugin_Handled; +} +public Action Command_RestoreState(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_restore [age=0]"); + }else{ + char arg1[32], arg2[4]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + int index = StringToInt(arg2); + if(index > MAXIMUM_STAGES_STORED) { + ReplyToCommand(client, "Age is above the maximum amount of ages saved of %d.", MAXIMUM_STAGES_STORED); + return Plugin_Handled; + } else if(index < 0) { + ReplyToCommand(client, "Age is invalid. Must be between 0 and %d", MAXIMUM_STAGES_STORED); + return Plugin_Handled; + } + + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_CONNECTED, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int target = target_list[i]; + if(IsClientConnected(target) && IsClientInGame(target) && GetClientTeam(target) == 2) { + RestoreState(target); + if(playerStatesList[index][target].timestamp == 0) { + ReplyToCommand(client, "%N does not have a state, using bare state."); + }else{ + ReplyToCommand(client, "Restored %N's state to age %d", target, index); + } + } + } + } + return Plugin_Handled; +} + +// ///////////////////////////////////////////////////////////////////////////// +// EVENTS +// ///////////////////////////////////////////////////////////////////////////// + +public void OnMapStart() { + CreateTimer(180.0, Timer_AutoRecord, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); +} + +public void OnClientPutInServer(int client) { + if(bMapStarted) { + RecordGlobalState("MAP_START"); + bMapStarted = false; + } +} + +public void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + //Ignore admins + if(!IsFakeClient(client) && GetClientTeam(client) == 2 && GetUserAdmin(client) == INVALID_ADMIN_ID) { + float time = GetGameTime(); + if(time - lastSpawnTime >= LAST_PLAYER_JOIN_THRESHOLD) { + RecordGlobalState("JOIN"); + lastSpawnTime = time; + } + } +} + +public void OnClientDisconnect(int client) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && !IsFakeClient(i)) { + ResetStates(i); + } + } +} + +public void Event_PlayerHurt(Event event, const char[] name, bool dontBroadcast) { + float currentTime = GetGameTime(); + if(currentTime - lastDamageTime >= LAST_FF_TIME_THRESHOLD) { + int client = GetClientOfUserId(event.GetInt("userid")); + int attackerID = event.GetInt("attacker"); + int damage = event.GetInt("dmg_health"); + if(client && GetClientTeam(client) == 2 && attackerID > 0 && damage > 0) { + int attacker = GetClientOfUserId(attackerID); + if(GetClientTeam(attacker) == 2) { + lastDamageTime = GetGameTime(); + RecordGlobalState("FRIENDLY_FIRE"); + } + } + + } +} + +public void Event_HealBegin(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + isHealing[client] = true; +} +public void Event_HealStop(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + isHealing[client] = false; +} + +public void Event_ReviveBegin(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int subject = GetClientOfUserId(event.GetInt("subject")); + if(client && subject) { + AdminId revived = GetUserAdmin(subject); + if(revived == INVALID_ADMIN_ID && !IsFakeClient(subject)) { + RecordGlobalState("REVIVED_NON_ADMIN"); + } + } +} + +public void FTT_OnClientMarked(int troll, int marker) { + RecordGlobalState("FTT_MARKED"); +} +// ///////////////////////////////////////////////////////////////////////////// +// TIMERS +// ///////////////////////////////////////////////////////////////////////////// +public Action Timer_AutoRecord(Handle h) { + RecordGlobalState("AUTO_TIMER", 50000); + return Plugin_Continue; +} +// ///////////////////////////////////////////////////////////////////////////// +// METHODS +// ///////////////////////////////////////////////////////////////////////////// +void RecordGlobalState(const char[] type, int skipTime = 0) { + int time = GetTime(); + for(int i = MAXIMUM_STAGES_STORED - 2; i >= 0; i--) { + TransferArray(i, i+1); + } + + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + //If skipTime set, do not record if last recording was <= skipTime ms ago + if(skipTime > 0 && playerStatesList[0][i].timestamp > 0 && time - playerStatesList[0][i].timestamp <= skipTime) continue; + + playerStatesList[0][i].incapState = GetEntProp(i, Prop_Send, "m_currentReviveCount"); + playerStatesList[0][i].isAlive = IsPlayerAlive(i); + _RecordInventory(i, playerStatesList[0][i].inventory); + + playerStatesList[0][i].permHealth = GetClientHealth(i); + playerStatesList[0][i].tempHealth = GetClientHealthBuffer(i); + + GetClientAbsOrigin(i, playerStatesList[0][i].position); + GetClientAbsAngles(i, playerStatesList[0][i].angles); + + strcopy(playerStatesList[0][i].recordReason, 32, type); + playerStatesList[0][i].timestamp = time; + } + playerStatesList[0][0].timestamp = time; + } + //PrintToConsoleAll("[Rollback] Recorded all player states for: %s", type); +} + +void _RecordInventory(int client, PlayerInventory inventory) { + GetClientWeaponName(client, 0, inventory.primarySlot, sizeof(inventory.primarySlot)); + GetClientWeaponName(client, 1, inventory.secondarySlot, sizeof(inventory.secondarySlot)); + GetClientWeaponName(client, 2, inventory.throwableSlot, sizeof(inventory.throwableSlot)); + GetClientWeaponName(client, 3, inventory.usableSlot, sizeof(inventory.usableSlot)); + GetClientWeaponName(client, 4, inventory.consumableSlot, sizeof(inventory.consumableSlot)); +} + +void _RestoreInventory(PlayerInventory inventory, int client) { + if(inventory.primarySlot[0] != '\0') + CheatCommand(client, "give", inventory.primarySlot, ""); + if(inventory.secondarySlot[0] != '\0') + CheatCommand(client, "give", inventory.secondarySlot, ""); + if(inventory.throwableSlot[0] != '\0') + CheatCommand(client, "give", inventory.throwableSlot, ""); + if(inventory.usableSlot[0] != '\0') + CheatCommand(client, "give", inventory.usableSlot, ""); + if(inventory.consumableSlot[0] != '\0') + CheatCommand(client, "give", inventory.consumableSlot, ""); +} + +void _ClearInventory(PlayerInventory inventory) { + inventory.primarySlot[0] = '\0'; + inventory.secondarySlot[0] = '\0'; + inventory.throwableSlot[0] = '\0'; + inventory.usableSlot[0] = '\0'; + inventory.consumableSlot[0] = '\0'; +} + + +void TransferArray(int oldIndex, int newIndex) { + for(int i = 1; i <= MaxClients; i++) { + playerStatesList[newIndex][i].incapState = playerStatesList[oldIndex][i].incapState; + playerStatesList[newIndex][i].isAlive = playerStatesList[oldIndex][i].isAlive; + playerStatesList[newIndex][i].inventory = playerStatesList[oldIndex][i].inventory; + _ClearInventory(playerStatesList[oldIndex][i].inventory); + + playerStatesList[newIndex][i].permHealth = playerStatesList[oldIndex][i].permHealth; + playerStatesList[newIndex][i].tempHealth = playerStatesList[oldIndex][i].tempHealth; + + playerStatesList[newIndex][i].position = playerStatesList[oldIndex][i].position; + playerStatesList[newIndex][i].angles = playerStatesList[oldIndex][i].angles; + + strcopy(playerStatesList[newIndex][i].recordReason, 32, playerStatesList[oldIndex][i].recordReason); + playerStatesList[newIndex][i].timestamp = playerStatesList[oldIndex][i].timestamp; + } + playerStatesList[newIndex][0].timestamp = playerStatesList[oldIndex][0].timestamp; +} + +void RestoreState(int client, int index = 0) { + char item[32]; + bool isIncapped = GetEntProp(client, Prop_Send, "m_isIncapacitated") == 1; + + bool respawned = false; + if(!IsPlayerAlive(client) && playerStatesList[index][client].isAlive) { + SDKCall(hRoundRespawn, client); + DataPack pack = CreateDataPack(); + pack.WriteCell(GetClientUserId(client)); + for(int i = 0; i < 3; i++) { + pack.WriteFloat(playerStatesList[index][client].position[i]); + } + for(int i = 0; i < 3; i++) { + pack.WriteFloat(playerStatesList[index][client].angles[i]); + } + CreateDataTimer(0.1, Timer_Teleport, pack); + respawned = true; + }else if(isIncapped) { + CheatCommand(client, "give", "health", ""); + TeleportEntity(client, playerStatesList[index][client].position, playerStatesList[index][client].angles, ZERO_VECTOR); + } + SetEntProp(client, Prop_Send, "m_currentReviveCount", playerStatesList[index][client].incapState); + SetEntProp(client, Prop_Send, "m_bIsOnThirdStrike", playerStatesList[index][client].incapState >= hMaxIncapCount.IntValue); + SetEntProp(client, Prop_Send, "m_isGoingToDie", playerStatesList[index][client].incapState >= hMaxIncapCount.IntValue); + + if(!respawned) { + GetClientWeaponName(client, 3, item, sizeof(item)); + _RestoreInventory(playerStatesList[index][client].inventory, client); + } + SetEntProp(client, Prop_Send, "m_iHealth", playerStatesList[index][client].permHealth > 0 ? playerStatesList[index][client].permHealth : 10); + SetEntPropFloat(client, Prop_Send, "m_healthBuffer", playerStatesList[index][client].tempHealth); + SetEntPropFloat(client, Prop_Send, "m_healthBufferTime", GetGameTime()); +} + + + +void ResetStates(int client) { + for(int stage = 0; stage < MAXIMUM_STAGES_STORED; stage++) { + playerStatesList[stage][client].incapState = 0; + playerStatesList[stage][client].permHealth = 0; + playerStatesList[stage][client].tempHealth = 0.0; + playerStatesList[stage][client].timestamp = 0; + playerStatesList[stage][client].recordReason[0] = '\0'; + _ClearInventory(playerStatesList[stage][client].inventory); + } +} + + +float GetClientHealthBuffer(int client, float defaultVal=0.0) { + // https://forums.alliedmods.net/showpost.php?p=1365630&postcount=1 + static float healthBuffer, healthBufferTime, tempHealth; + healthBuffer = GetEntPropFloat(client, Prop_Send, "m_healthBuffer"); + healthBufferTime = GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime"); + tempHealth = healthBuffer - (healthBufferTime / (1.0 / hDecayRate.FloatValue)); + return tempHealth < 0.0 ? defaultVal : tempHealth; +} + +// Teleports player to position after a tick. Index, pos[3], ang[3] +public Action Timer_Teleport(Handle handle, DataPack pack) { + pack.Reset(); + int client = pack.ReadCell(); + float position[3], angles[3]; + + for(int i = 0; i < 3; i++) { + position[i] = pack.ReadFloat(); + } + for(int i = 0; i < 3; i++) { + angles[i] = pack.ReadFloat(); + } + + TeleportEntity(client, position, angles, ZERO_VECTOR); + return Plugin_Handled; +} \ No newline at end of file diff --git a/scripting/l4d2_sb_fix.sp b/scripting/l4d2_sb_fix.sp new file mode 100644 index 0000000..1fe9f4b --- /dev/null +++ b/scripting/l4d2_sb_fix.sp @@ -0,0 +1,2259 @@ +#pragma newdecls required + +#include +#include +#include + +public Plugin myinfo = +{ + name = "L4D2 Survivor Bot Fix", + author = "DingbatFlat", + description = "Survivor Bot Fix. Improve Survivor Bot", + version = "1.00", + url = "https://github.com/Jackzmc/sourcemod-plugins" +} + +/* +// ==================================================================================================== + +About: + +- Main items that can be improve bots by introducing this plugin. + +Help a pinning Survivor. +Attack a Common Infected. +Attack a Special Infected. +Attack a Tank. +Bash a flying Hunter and Jockey. +Shoot a tank rock. +Shoot a Witch (Contronls the attack timing when have a shotgun). +Restrict switching to the sub weapon. + +And the action during incapacitated. + + +- Sourcemod ver 1.10 is required. + + + +// ==================================================================================================== + +How to use: + +Make sure "sb_fix_enabled" in the CVars is 1. + + +- Select the improved bot with the following CVar. + +If "sb_fix_select_type" is 0, It is always enabled. + +If "sb_fix_select_type" is 1, the number of people set in "sb_fix_select_number" will be randomly select. + +If "sb_fix_select_type" is 2, Select the bot of the character entered in "sb_fix_select_character_name". + + +- For 1 and 2, bots that improve after left the safe room are selected. + + + +// ==================================================================================================== + +Change Log: + +1.00 (09-September-2021) + - Initial release. + + + +// ==================================================================================================== + + +// It is difficult to improve the movement operation. +// This is the limit of my power and I can't add any further improvement points maybe... so arrange as you like. +*/ + +#define SOUND_SELECT "level/gnomeftw.wav" +#define SOUND_SWING "ui/pickup_guitarriff10.wav" + +#define BUFSIZE (1 << 12) // 4k + +#define ZC_SMOKER 1 +#define ZC_BOOMER 2 +#define ZC_HUNTER 3 +#define ZC_SPITTER 4 +#define ZC_JOCKEY 5 +#define ZC_CHARGER 6 +#define ZC_TANK 8 + +#define MAXPLAYERS1 (MAXPLAYERS+1) +#define MAXENTITIES 2048 + +#define WITCH_INCAPACITATED 1 +#define WITCH_KILLED 2 + +/****************************************************************************************************/ + +// ==================================================================================================== +// Handle +// ==================================================================================================== +ConVar sb_fix_enabled; +ConVar sb_fix_select_type; +ConVar sb_fix_select_number; +ConVar sb_fix_select_character_name; + +ConVar sb_fix_dont_switch_secondary; + +ConVar sb_fix_help_enabled; +ConVar sb_fix_help_range; +ConVar sb_fix_help_shove_type; +ConVar sb_fix_help_shove_reloading; + +ConVar sb_fix_ci_enabled; +ConVar sb_fix_ci_range; +ConVar sb_fix_ci_melee_allow; +ConVar sb_fix_ci_melee_range; + +ConVar sb_fix_si_enabled; +ConVar sb_fix_si_range; +ConVar sb_fix_si_ignore_boomer; +ConVar sb_fix_si_ignore_boomer_range; + +ConVar sb_fix_tank_enabled; +ConVar sb_fix_tank_range; + +ConVar sb_fix_si_tank_priority_type; + +ConVar sb_fix_bash_enabled; +ConVar sb_fix_bash_hunter_chance; +ConVar sb_fix_bash_hunter_range; +ConVar sb_fix_bash_jockey_chance; +ConVar sb_fix_bash_jockey_range; + +ConVar sb_fix_rock_enabled; +ConVar sb_fix_rock_range; + +ConVar sb_fix_witch_enabled; +ConVar sb_fix_witch_range; +ConVar sb_fix_witch_range_incapacitated; +ConVar sb_fix_witch_range_killed; +ConVar sb_fix_witch_shotgun_control; +ConVar sb_fix_witch_shotgun_range_max; +ConVar sb_fix_witch_shotgun_range_min; + +ConVar sb_fix_prioritize_ownersmoker; + +ConVar sb_fix_incapacitated_enabled; + +ConVar sb_fix_debug; + +// ==================================================================================================== +// SendProp +// ==================================================================================================== +int g_Velo = -1; +int g_ActiveWeapon = -1; +int g_iAmmoOffset = -1; + +// ==================================================================================================== +// Variables +// ==================================================================================================== +bool g_hEnabled; +int c_iSelectType; +int c_iSelectNumber; + +bool c_bDontSwitchSecondary; + +bool c_bHelp_Enabled; +float c_fHelp_Range; +int c_iHelp_ShoveType; +bool c_bHelp_ShoveOnlyReloading; + +bool c_bCI_Enabled; +float c_fCI_Range; +bool c_bCI_MeleeEnabled; +float c_fCI_MeleeRange; + +bool c_bSI_Enabled; +float c_fSI_Range; +bool c_bSI_IgnoreBoomer; +float c_fSI_IgnoreBoomerRange; + +bool c_bTank_Enabled; +float c_fTank_Range; + +int c_iSITank_PriorityType; + +bool c_bBash_Enabled; +int c_iBash_HunterChance; +float c_fBash_HunterRange; +int c_iBash_JockeyChance; +float c_fBash_JockeyRange; + +bool c_bRock_Enabled; +float c_fRock_Range; + +bool c_bWitch_Enabled; +float c_fWitch_Range; +float c_fWitch_Range_Incapacitated; +float c_fWitch_Range_Killed; +bool c_bWitch_Shotgun_Control; +float c_fWitch_Shotgun_Range_Max; +float c_fWitch_Shotgun_Range_Min; + +bool c_bPrioritize_OwnerSmoker; + +bool c_bIncapacitated_Enabled; + +bool c_bDebug_Enabled; + +// ==================================================================================================== +// Int Array +// ==================================================================================================== +int g_iWitch_Process[MAXENTITIES]; + +int g_Stock_NextThinkTick[MAXPLAYERS1]; + +// ==================================================================================================== +// Bool Array +// ==================================================================================================== +bool g_bFixTarget[MAXPLAYERS1]; + +bool g_bDanger[MAXPLAYERS1]; + +bool g_bWitchActive = false; + +bool g_bCommonWithinMelee[MAXPLAYERS1]; +bool g_bShove[MAXPLAYERS1][MAXPLAYERS1]; + +// ==================================================================================================== +// Round +// ==================================================================================================== +bool LeftSafeRoom = false; +bool TimerAlreadyWorking = false; + +/****************************************************************************************************/ + +bool bLateLoad = false; + +public APLRes AskPluginLoad2(Handle plugin, bool late, char[] error, int errMax) +{ + bLateLoad = late; + return APLRes_Success; +} + +public void OnPluginStart() +{ + // Notes: + // If "~_enabled" of the group is not set to 1, other Cvars in that group will not work. + // If the plugin is too heavy, Try disable searching for "Entities" other than Client. (CI, Witch and tank rock) + + // --------------------------------- + sb_fix_enabled = CreateConVar("sb_fix_enabled", "1", "Enable the plugin. <0: Disable, 1: Enable>", FCVAR_NONE, true, 0.0, true, 1.0); + // --------------------------------- + sb_fix_select_type = CreateConVar("sb_fix_select_type", "0", "Which survivor bots to improved. <0: All, 1: Randomly select X people when left the safe area, 2: Enter the character name of the survivor bot to improve in \"sb_fix_select_character_name\">", FCVAR_NONE, true, 0.0, true, 2.0); + sb_fix_select_number = CreateConVar("sb_fix_select_number", "1", "If \"sb_fix_select_type\" is 1, Enter the number of survivor bots. <0 ~ 4>", FCVAR_NONE, true, 0.0); + sb_fix_select_character_name = CreateConVar("sb_fix_select_character_name", "", "If \"sb_fix_select_type\" is 4, Enter the character name to improved. Separate with spaces. Example: \"nick francis bill\"", FCVAR_NONE); // "coach ellis rochelle nick louis francis zoey bill" + // --------------------------------- + sb_fix_dont_switch_secondary = CreateConVar("sb_fix_dont_switch_secondary", "1", "Disallow switching to the secondary weapon until the primary weapon is out of ammo. <0:No, 1:Yes | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + // --------------------------------- + sb_fix_help_enabled = CreateConVar("sb_fix_help_enabled", "1", "Help a pinning survivor. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_help_range = CreateConVar("sb_fix_help_range", "1200", "Range to shoot/search a pinning survivor. <1 ~ 3000 | def: 1200>", FCVAR_NONE, true, 1.0, true, 3000.0); + sb_fix_help_shove_type = CreateConVar("sb_fix_help_shove_type", "2", "Whether to help by shove. <0: Not help by shove, 1: Smoker only, 2: Smoker and Jockey, 3: Smoker, Jockey and Hunter | def: 2>", FCVAR_NONE, true, 0.0, true, 3.0); + sb_fix_help_shove_reloading = CreateConVar("sb_fix_help_shove_reloading", "0", "If \"sb_fix_help_shove_type\" is 2 or more, it is shove only while reloading. <0: No, 1: Yes | def: 0>", FCVAR_NONE, true, 0.0, true, 1.0); + // --------------------------------- + sb_fix_ci_enabled = CreateConVar("sb_fix_ci_enabled", "1", "Deal with Common Infecteds. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_ci_range = CreateConVar("sb_fix_ci_range", "500", "Range to shoot/search a Common Infected. <1 ~ 2000 | def: 500>", FCVAR_NONE, true, 1.0, true, 2000.0); + sb_fix_ci_melee_allow = CreateConVar("sb_fix_ci_melee_allow", "1", "Allow to deal with the melee weapon. <0: Disable 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_ci_melee_range = CreateConVar("sb_fix_ci_melee_range", "160", "If \"sb_fix_ci_melee_allow\" is enabled, range to deal with the melee weapon. <1 ~ 500 | def: 160>", FCVAR_NONE, true, 1.0, true, 500.0); + // --------------------------------- + sb_fix_si_enabled = CreateConVar("sb_fix_si_enabled", "1", "Deal with Special Infecteds. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_si_range = CreateConVar("sb_fix_si_range", "500", "Range to shoot/search a Special Infected. <1 ~ 3000 | def: 500>", FCVAR_NONE, true, 1.0, true, 3000.0); + sb_fix_si_ignore_boomer = CreateConVar("sb_fix_si_ignore_boomer", "1", "Ignore a Boomer near Survivors (and shove a Boomer). <0: No, 1: Yes | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_si_ignore_boomer_range = CreateConVar("sb_fix_si_ignore_boomer_range", "200", "Range to ignore a Boomer. <1 ~ 900 | def: 200>", FCVAR_NONE, true, 1.0, true, 500.0); + // --------------------------------- + sb_fix_tank_enabled = CreateConVar("sb_fix_tank_enabled", "1", "Deal with Tanks. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_tank_range = CreateConVar("sb_fix_tank_range", "1200", "Range to shoot/search a Tank. <1 ~ 3000 | def: 1200>", FCVAR_NONE, true, 1.0, true, 3000.0); + // --------------------------------- + sb_fix_si_tank_priority_type = CreateConVar("sb_fix_si_tank_priority_type", "0", "When a Special Infected and a Tank is together within the specified range, which to prioritize. <0: Nearest, 1: Special Infected, 2: Tank | def: 0>", FCVAR_NONE, true, 0.0, true, 2.0); + // --------------------------------- + sb_fix_bash_enabled = CreateConVar("sb_fix_bash_enabled", "1", "Bash a flying Hunter or Jockey. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_bash_hunter_chance = CreateConVar("sb_fix_bash_hunter_chance", "60", "Chance of bash a flying Hunter. (Even 100 doesn't can perfectly shove). <1 ~ 100 | def: 100>", FCVAR_NONE, true, 0.0, true, 100.0); + sb_fix_bash_hunter_range = CreateConVar("sb_fix_bash_hunter_range", "145", "Range to bash/search a flying Hunter. <1 ~ 500 | def: 145>", FCVAR_NONE, true, 1.0, true, 500.0); + sb_fix_bash_jockey_chance = CreateConVar("sb_fix_bash_jockey_chance", "60", "Chance of bash a flying Jockey. (Even 100 doesn't can perfectly shove). <1 ~ 100 | def: 100>", FCVAR_NONE, true, 0.0, true, 100.0); + sb_fix_bash_jockey_range = CreateConVar("sb_fix_bash_jockey_range", "125", "Range to bash/search a flying Jockey. <1 ~ 500 | def: 125>", FCVAR_NONE, true, 1.0, true, 500.0); + // --------------------------------- + sb_fix_rock_enabled = CreateConVar("sb_fix_rock_enabled", "1", "Shoot a tank rock. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_rock_range = CreateConVar("sb_fix_rock_range", "500", "Range to shoot/search a tank rock. <1 ~ 2000 | def: 700>", FCVAR_NONE, true, 1.0, true, 2000.0); + // --------------------------------- + sb_fix_witch_enabled = CreateConVar("sb_fix_witch_enabled", "1", "Shoot a rage Witch. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_witch_range = CreateConVar("sb_fix_witch_range", "1500", "Range to shoot/search a rage Witch. <1 ~ 2000 | def: 1500>", FCVAR_NONE, true, 1.0, true, 2000.0); + sb_fix_witch_range_incapacitated = CreateConVar("sb_fix_witch_range_incapacitated", "1000", "Range to shoot/search a Witch that incapacitated a survivor. <0 ~ 2000 | def: 1000>", FCVAR_NONE, true, 0.0, true, 2000.0); + sb_fix_witch_range_killed = CreateConVar("sb_fix_witch_range_killed", "0", "Range to shoot/search a Witch that killed a survivor. <0 ~ 2000 | def: 0>", FCVAR_NONE, true, 0.0, true, 2000.0); + sb_fix_witch_shotgun_control = CreateConVar("sb_fix_witch_shotgun_control", "1", "[Witch] If have the shotgun, controls the attack timing. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + sb_fix_witch_shotgun_range_max = CreateConVar("sb_fix_witch_shotgun_range_max", "300", "If a Witch is within distance of the values, stop the attack. <1 ~ 1000 | def: 300>", FCVAR_NONE, true, 1.0, true, 1000.0); + sb_fix_witch_shotgun_range_min = CreateConVar("sb_fix_witch_shotgun_range_min", "70", "If a Witch is at distance of the values or more, stop the attack. <1 ~ 500 | def: 70>", FCVAR_NONE, true, 1.0, true, 500.0); + // --------------------------------- + sb_fix_prioritize_ownersmoker = CreateConVar("sb_fix_prioritize_ownersmoker", "1", "Priority given to dealt a Smoker that is try to pinning self. <0: No, 1: Yes | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + // --------------------------------- + sb_fix_incapacitated_enabled = CreateConVar("sb_fix_incapacitated_enabled", "1", "Enable Incapacitated Cmd. <0: Disable, 1: Enable | def: 1>", FCVAR_NONE, true, 0.0, true, 1.0); + // --------------------------------- + sb_fix_debug = CreateConVar("sb_fix_debug", "0", "[For debug] Print the action status. <0:Disable, 1:Enable>", FCVAR_NONE, true, 0.0, true, 1.0); + + + HookConVarChange(sb_fix_help_enabled, SBHelp_ChangeConvar); + HookConVarChange(sb_fix_help_range, SBHelp_ChangeConvar); + HookConVarChange(sb_fix_help_shove_type, SBHelp_ChangeConvar); + HookConVarChange(sb_fix_help_shove_reloading, SBHelp_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_ci_enabled, SBCI_ChangeConvar); + HookConVarChange(sb_fix_ci_range, SBCI_ChangeConvar); + HookConVarChange(sb_fix_ci_melee_allow, SBCI_ChangeConvar); + HookConVarChange(sb_fix_ci_melee_range, SBCI_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_si_enabled, SBSI_ChangeConvar); + HookConVarChange(sb_fix_si_range, SBSI_ChangeConvar); + HookConVarChange(sb_fix_si_ignore_boomer, SBSI_ChangeConvar); + HookConVarChange(sb_fix_si_ignore_boomer_range, SBSI_ChangeConvar) + // --------------------------------- + HookConVarChange(sb_fix_tank_enabled, SBTank_ChangeConvar); + HookConVarChange(sb_fix_tank_range, SBTank_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_si_tank_priority_type, SBTank_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_bash_enabled, SBBash_ChangeConvar); + HookConVarChange(sb_fix_bash_hunter_chance, SBBash_ChangeConvar); + HookConVarChange(sb_fix_bash_hunter_range, SBBash_ChangeConvar); + HookConVarChange(sb_fix_bash_jockey_chance, SBBash_ChangeConvar); + HookConVarChange(sb_fix_bash_jockey_range, SBBash_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_rock_enabled, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_rock_range, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_enabled, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_range, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_range_incapacitated, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_range_killed, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_shotgun_control, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_shotgun_range_max, SBEnt_ChangeConvar); + HookConVarChange(sb_fix_witch_shotgun_range_min, SBEnt_ChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_enabled, SBConfigChangeConvar); + HookConVarChange(sb_fix_select_type, SBConfigChangeConvar); + HookConVarChange(sb_fix_select_number, SBConfigChangeConvar); + HookConVarChange(sb_fix_dont_switch_secondary, SBConfigChangeConvar); + HookConVarChange(sb_fix_prioritize_ownersmoker, SBConfigChangeConvar); + HookConVarChange(sb_fix_incapacitated_enabled, SBConfigChangeConvar); + HookConVarChange(sb_fix_debug, SBConfigChangeConvar); + // --------------------------------- + HookConVarChange(sb_fix_select_type, SBSelectChangeConvar); + HookConVarChange(sb_fix_select_number, SBSelectChangeConvar); + HookConVarChange(sb_fix_select_character_name, SBSelectChangeConvar); + + if (bLateLoad) { + for (int x = 1; x <= MaxClients; x++) { + if (x > 0 && x <= MaxClients && IsClientInGame(x)) { + SDKHook(x, SDKHook_WeaponSwitch, WeaponSwitch); + } + } + } + + AutoExecConfig(false, "l4d2_sb_fix"); + + PrecacheSound(SOUND_SWING); + + HookEvent("round_start", Event_RoundStart); + HookEvent("bot_player_replace", Event_BotAndPlayerReplace, EventHookMode_Pre); // SelectImprovedTarget + + HookEvent("player_incapacitated", Event_PlayerIncapacitated); // Witch Event + HookEvent("player_death", Event_PlayerDeath); // Witch Event + + HookEvent("witch_harasser_set", Event_WitchRage); + + g_Velo = FindSendPropInfo("CBasePlayer", "m_vecVelocity[0]"); + g_ActiveWeapon = FindSendPropInfo("CBasePlayer", "m_hActiveWeapon"); + g_iAmmoOffset = FindSendPropInfo("CTerrorPlayer", "m_iAmmo"); + + CreateTimer(3.0, Timer_ShoveChance, _, TIMER_REPEAT); + + InitTimers(); // Safe Room Check +} + +public void OnMapStart() +{ + input_Help(); + input_CI(); + input_SI(); + input_Tank(); + input_Bash(); + input_Entity(); + inputConfig(); +} + +public void OnAllPluginsLoaded() +{ + input_Help(); + input_CI(); + input_SI(); + input_Tank(); + input_Bash(); + input_Entity(); + inputConfig(); +} + +public void SBHelp_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_Help(); } +public void SBCI_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_CI(); } +public void SBSI_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_SI(); } +public void SBTank_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_Tank(); } +public void SBBash_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_Bash(); } +public void SBEnt_ChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { input_Entity(); } + +public void SBConfigChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { inputConfig(); } + +public void SBSelectChangeConvar(Handle convar, const char[] oldValue, const char[] intValue) { SelectImprovedTarget(); } + +// all _range cvars are squared for optimized distance check +void input_Help() +{ + c_bHelp_Enabled = GetConVarBool(sb_fix_help_enabled); + c_fHelp_Range = Pow(sb_fix_help_range.FloatValue, 2.0); + c_iHelp_ShoveType = GetConVarInt(sb_fix_help_shove_type); + c_bHelp_ShoveOnlyReloading = GetConVarBool(sb_fix_help_shove_reloading); +} +void input_CI() +{ + c_bCI_Enabled = GetConVarBool(sb_fix_ci_enabled); + c_fCI_Range = Pow(sb_fix_ci_range.FloatValue, 2.0); + c_bCI_MeleeEnabled = GetConVarBool(sb_fix_ci_melee_allow); + c_fCI_MeleeRange = Pow(sb_fix_ci_melee_range.FloatValue, 2.0); +} +void input_SI() +{ + c_bSI_Enabled = GetConVarBool(sb_fix_si_enabled); + c_fSI_Range = Pow(sb_fix_si_range.FloatValue, 2.0); + c_bSI_IgnoreBoomer = GetConVarBool(sb_fix_si_ignore_boomer); + c_fSI_IgnoreBoomerRange = Pow(sb_fix_si_ignore_boomer_range.FloatValue, 2.0); +} +void input_Tank() +{ + c_bTank_Enabled = GetConVarBool(sb_fix_tank_enabled); + c_fTank_Range = Pow(sb_fix_tank_range.FloatValue, 2.0); + + c_iSITank_PriorityType = GetConVarInt(sb_fix_si_tank_priority_type); +} +void input_Bash() +{ + c_bBash_Enabled = GetConVarBool(sb_fix_bash_enabled); + c_iBash_HunterChance = GetConVarInt(sb_fix_bash_hunter_chance); + c_fBash_HunterRange = Pow(sb_fix_bash_hunter_range.FloatValue, 2.0); + c_iBash_JockeyChance = GetConVarInt(sb_fix_bash_jockey_chance); + c_fBash_JockeyRange = Pow(sb_fix_bash_jockey_range.FloatValue, 2.0); +} +void input_Entity() +{ + c_bRock_Enabled = GetConVarBool(sb_fix_rock_enabled); + c_fRock_Range = Pow(sb_fix_rock_range.FloatValue, 2.0); + + c_bWitch_Enabled = GetConVarBool(sb_fix_witch_enabled); + c_fWitch_Range = Pow(sb_fix_witch_range.FloatValue, 2.0); + c_fWitch_Range_Incapacitated = Pow(sb_fix_witch_range_incapacitated.FloatValue, 2.0); + c_fWitch_Range_Killed = Pow(sb_fix_witch_range_killed.FloatValue, 2.0); + c_bWitch_Shotgun_Control = GetConVarBool(sb_fix_witch_shotgun_control); + c_fWitch_Shotgun_Range_Max = Pow(sb_fix_witch_shotgun_range_max.FloatValue, 2.0); + c_fWitch_Shotgun_Range_Min = Pow(sb_fix_witch_shotgun_range_min.FloatValue, 2.0); +} + +void inputConfig() +{ + g_hEnabled = GetConVarBool(sb_fix_enabled); + c_iSelectType = GetConVarInt(sb_fix_select_type); + c_iSelectNumber = GetConVarInt(sb_fix_select_number); + + c_bDontSwitchSecondary = GetConVarBool(sb_fix_dont_switch_secondary); + + c_bPrioritize_OwnerSmoker = GetConVarBool(sb_fix_prioritize_ownersmoker); + + c_bIncapacitated_Enabled = GetConVarBool(sb_fix_incapacitated_enabled); + + c_bDebug_Enabled = GetConVarBool(sb_fix_debug); +} + + +/****************************************************************************************************/ + + +/* ================================================================================================ +*= +*= Round / Start Ready / Select Improved Targets +*= +================================================================================================ */ +public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) +{ + for (int x = 1; x <= MAXPLAYERS; x++) g_bFixTarget[x] = false; // RESET + + LeftSafeRoom = false; + + + if (!TimerAlreadyWorking) { + CreateTimer(1.0, Timer_PlayerLeftCheck); + TimerAlreadyWorking = true; + } + + InitTimers(); +} + +public void Event_BotAndPlayerReplace(Handle event, const char[] name, bool dontBroadcast) +{ + if (!LeftSafeRoom) return; + + int bot = GetClientOfUserId(GetEventInt(event, "bot")); + if (g_bFixTarget[bot]) { + SelectImprovedTarget(); + } +} + +void InitTimers() +{ + if (LeftSafeRoom) + SelectImprovedTarget(); + else if (!TimerAlreadyWorking) + { + TimerAlreadyWorking = true; + CreateTimer(1.0, Timer_PlayerLeftCheck); + } +} + +public Action Timer_PlayerLeftCheck(Handle Timer) +{ + if (LeftStartArea()) + { + if (!LeftSafeRoom) { + LeftSafeRoom = true; + SelectImprovedTarget(); + // PrintToChatAll("[sb_fix] Survivors left the safe area."); + } + + TimerAlreadyWorking = false; + } + else + { + CreateTimer(1.0, Timer_PlayerLeftCheck); + } + return Plugin_Continue; +} + +bool LeftStartArea() +{ + int ent = -1, maxents = GetMaxEntities(); + for (int i = MaxClients+1; i <= maxents; i++) + { + if (IsValidEntity(i)) + { + static char netclass[32]; + GetEntityNetClass(i, netclass, sizeof(netclass)); + + if (StrEqual(netclass, "CTerrorPlayerResource")) + { + ent = i; + break; + } + } + } + + if (ent > -1) + { + int offset = FindSendPropInfo("CTerrorPlayerResource", "m_hasAnySurvivorLeftSafeArea"); + if (offset > 0) + { + if (GetEntData(ent, offset)) + { + if (GetEntData(ent, offset) == 1) return true; + } + } + } + return false; +} + +void SelectImprovedTarget() +{ + if (!g_hEnabled || !LeftSafeRoom) return; // Select targets when left the safe area. + else if (c_iSelectType == 1) { + int count; + for (int x = 1; x <= MaxClients; x++) { + if (isSurvivorBot(x)) { + g_bFixTarget[x] = true; + count++ + } + + if (count >= c_iSelectNumber) { break; } + } + } + else if (c_iSelectType == 2) + { + static char sSelectName[256]; + GetConVarString(sb_fix_select_character_name, sSelectName, sizeof(sSelectName)); + + int count; + for (int x = 1; x <= MaxClients; x++) { + if (isSurvivorBot(x)) { + static char sName[128]; + GetClientName(x, sName, sizeof(sName)); + + if (StrContains(sSelectName, sName, false) != -1) { + g_bFixTarget[x] = true; + count++; + //PrintToChatAll("\x04%d\x05. %N", count, x); + } else { + g_bFixTarget[x] = false; + } + } + + } + } +} + +public Action Timer_ShoveChance(Handle Timer) +{ + // ----------------------- Bash Chance ----------------------- + if (c_iBash_HunterChance < 100 || c_iBash_JockeyChance < 100) { + for (int sb = 1; sb <= MaxClients; sb++) { + if (isSurvivorBot(sb) && IsPlayerAlive(sb)) { + for (int x = 1; x <= MaxClients; x++) { + if (isInfected(x) && IsPlayerAlive(x)) { + int zombieClass = getZombieClass(x); + if (zombieClass == ZC_HUNTER) { + if (GetRandomInt(0, 100) <= c_iBash_HunterChance) g_bShove[sb][x] = true; + else g_bShove[sb][x] = false; + + // PrintToChatAll("%N's Shove to %N: %b", sb, x, g_bShove[sb][x]); + } + else if (zombieClass == ZC_JOCKEY) { + if (GetRandomInt(0, 100) <= c_iBash_JockeyChance) g_bShove[sb][x] = true; + else g_bShove[sb][x] = false; + + // PrintToChatAll("%N's Shove to %N: %b", sb, x, g_bShove[sb][x]); + } + } + } + } + } + } + return Plugin_Continue; +} + + +/****************************************************************************************************/ + + +/* Client key input processing + * + * buttons: Entered keys (enum��include/entity_prop_stock.inc�Q��) + + * angles: + * [0]: pitch(UP-DOWN) -89~+89 + * [1]: yaw(360) -180~+180 + */ + + /* + * OnPlayerRunCmd is Runs 30 times per second. (every 0.03333... seconds) + */ +public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, + float vel[3], float angles[3], int &weapon) +{ + if(GetTickInterval() < 0.03333) return Plugin_Continue; //Stop running on lag + if (g_hEnabled) { + if (isSurvivorBot(client) && IsPlayerAlive(client)) { + if ((c_iSelectType == 0) || (c_iSelectType >= 1 && g_bFixTarget[client])) { + Action ret = Plugin_Continue; + ret = onSBRunCmd(client, buttons, vel, angles); + if (c_bIncapacitated_Enabled) ret = onSBRunCmd_Incapacitated(client, buttons, vel, angles); + ret = onSBSlotActionCmd(client, buttons, vel, angles); + + return ret; + } + } + } + return Plugin_Continue; +} + + +/****************************************************************************************************/ + + +/* ================================================================================================ +*= +*= Weapon Switch +*= +================================================================================================ */ +public void OnClientPutInServer(int client) +{ + SDKHook(client, SDKHook_WeaponSwitch, WeaponSwitch); +} +public void OnClientDisconnect(int client) +{ + SDKUnhook(client, SDKHook_WeaponSwitch, WeaponSwitch); +} +public Action WeaponSwitch(int client, int weapon) +{ + if (!g_hEnabled) return Plugin_Continue; + if (!isSurvivor(client) || !IsFakeClient(client) || !IsValidEntity(weapon)) return Plugin_Continue; + if (isIncapacitated(client) || GetPlayerWeaponSlot(client, 0) == -1) return Plugin_Continue; + + static char classname[128]; + GetEntityClassname(weapon, classname, sizeof(classname)); + + if (isHaveItem(classname, "weapon_melee") + || isHaveItem(classname, "weapon_pistol") // Includes Magnum ("weapon_pistol_magnum") + || isHaveItem(classname, "weapon_dual_pistol")) + { + if (c_bDontSwitchSecondary) { + int slot0 = GetPlayerWeaponSlot(client, 0); + int clip, extra_ammo; + clip = GetEntProp(slot0, Prop_Send, "m_iClip1"); + extra_ammo = PrimaryExtraAmmoCheck(client, slot0); // check + + //PrintToChatAll("[%N's] clip: %d, extra_ammo: %d", client, clip, extra_ammo); + + //if (!g_bCommonWithinMelee[client] && (clip != 0 || extra_ammo != 0)) PrintToChatAll("switch Stoped"); + + + if (!g_bCommonWithinMelee[client] && (clip != 0 || extra_ammo != 0)) return Plugin_Handled; + } + } + else if (StrContains(classname, "first_aid_kit", false) > -1 + || StrContains(classname, "defibrillator", false) > -1) + { + if (g_bDanger[client]) return Plugin_Handled; + } + + return Plugin_Continue; +} + +// TODO: optimize it + +stock Action onSBSlotActionCmd(int client, int &buttons, float vel[3], float angles[3]) +{ + if (!isIncapacitated(client) && GetPlayerWeaponSlot(client, 0) > -1) { + int weapon = GetEntDataEnt2(client, g_ActiveWeapon); + + if (weapon <= 0) return Plugin_Continue; + + static char classname[32]; + GetEntityClassname(weapon, classname, sizeof(classname)); + + if (StrEqual(classname, "weapon_melee", false) + || StrContains(classname, "pistol", false) > -1) + { + if (!g_bCommonWithinMelee[client]) { + static char main_weapon[32]; + GetEntityClassname(GetPlayerWeaponSlot(client, 0), main_weapon, sizeof(main_weapon)); + FakeClientCommand(client, "use %s", main_weapon); + } + } else if (StrEqual(classname, "weapon_first_aid_kit", false) + || StrContains(classname, "weapon_defibrillator", false)) + { + if (g_bDanger[client]) { + static char main_weapon[32]; + GetEntityClassname(GetPlayerWeaponSlot(client, 0), main_weapon, sizeof(main_weapon)); + FakeClientCommand(client, "use %s", main_weapon); + } + } + } + return Plugin_Continue; +} + + +/****************************************************************************************************/ + + +/* ================================================================================================ +*= +*= SB Run Cmd +*= +================================================================================================ */ +stock Action onSBRunCmd(int client, int &buttons, float vel[3], float angles[3]) +{ + if (!isIncapacitated(client) + && GetEntityMoveType(client) != MOVETYPE_LADDER) + { + // Find a nearest visible Special Infected + int int_target = -1; + float min_dist = 100000.0; + float self_pos[3], target_pos[3]; + + if ((c_bSI_Enabled || c_bTank_Enabled) && !NeedsTeammateHelp_ExceptSmoker(client)) { + GetClientAbsOrigin(client, self_pos); + for (int x = 1; x <= MaxClients; ++x) { + if (isInfected(x) + && IsPlayerAlive(x) + && !isIncapacitated(x) + && isVisibleTo(client, x)) + { + GetClientAbsOrigin(x, target_pos); + float dist = GetVectorDistance(self_pos, target_pos, true); + + int zombieClass = getZombieClass(x); + if ((c_bSI_Enabled && zombieClass != ZC_TANK && dist <= c_fSI_Range) + || (c_bTank_Enabled && zombieClass == ZC_TANK && dist <= c_fTank_Range)) + { + if ((c_iSITank_PriorityType == 1 && zombieClass != ZC_TANK) + || (c_iSITank_PriorityType == 2 && zombieClass == ZC_TANK)) { + if (dist < min_dist) { + min_dist = dist; + int_target = x; + continue; + } + } + + if (dist < min_dist) { + min_dist = dist; + int_target = x; + } + } + + } + } + } + + int aCap_Survivor = -1; + float min_dist_CapSur = 10000000000.0; //org was 100,000, we square here + float target_pos_CapSur[3]; + + int aCap_Infected = -1; + float min_dist_CapInf = 10000000000.0; + float target_pos_CapInf[3]; + + if (c_bHelp_Enabled && !NeedsTeammateHelp_ExceptSmoker(client)) { + // Find a Survivor who are pinned + for (int x = 1; x <= MaxClients; ++x) { + if (isSurvivor(x) + && NeedsTeammateHelp(x) + && (x != client) + && (isVisibleTo(client, x) || isVisibleTo(x, client))) + { + float dist; + + GetClientAbsOrigin(x, target_pos_CapSur); + dist = GetVectorDistance(self_pos, target_pos_CapSur, true); + if (dist < c_fHelp_Range) { + if (dist < min_dist_CapSur) { + min_dist_CapSur = dist; + aCap_Survivor = x; + } + } + } + } + + // Find a Special Infected who are pinning + for (int x = 1; x <= MaxClients; ++x) { + if (isInfected(x) + && CappingSuvivor(x) + && (isVisibleTo(client, x) || isVisibleTo(x, client))) + { + float dist; + + GetClientAbsOrigin(x, target_pos_CapInf); + dist = GetVectorDistance(self_pos, target_pos_CapInf, true); + if (dist < c_fHelp_Range) { + if (dist < min_dist_CapInf) { + min_dist_CapInf = dist; + aCap_Infected = x; + } + } + } + } + } + + /* + // Find aCapSmoker + int aCapSmoker = -1; + float min_dist_CapSmo = 100000.0; + float target_pos_CapSmo[3]; + + for (int x = 1; x <= MaxClients; ++x) { + if (isSpecialInfectedBot(x) + && IsPlayerAlive(x) + && HasValidEnt(x, "m_tongueVictim") + && isVisibleTo(int client, x)) + { + float dist; + + GetClientAbsOrigin(x, target_pos_CapSmo); + dist = GetVectorDistance(self_pos, target_pos_CapSmo); + if (dist < 700.0) { + if (dist < min_dist_CapSmo) { + min_dist_CapSmo = dist; + aCapSmoker = x; + } + } + } + } + */ + + // Find a Smoker who is tongued self + int aCapSmoker = -1; + + if (c_bPrioritize_OwnerSmoker) { + float min_dist_CapSmo = 100000.0; + float target_pos_CapSmo[3]; + + for (int x = 1; x <= MaxClients; ++x) { + if (isInfected(x) + && IsPlayerAlive(x) + && HasValidEnt(x, "m_tongueVictim")) + { + if (GetEntPropEnt(x, Prop_Send, "m_tongueVictim") == client) { + float dist; + + GetClientAbsOrigin(x, target_pos_CapSmo); + dist = GetVectorDistance(self_pos, target_pos_CapSmo, true); + if (dist < 750.0) { + if (dist < min_dist_CapSmo) { + min_dist_CapSmo = dist; + aCapSmoker = x; + } + } + } + } + } + } + + // Find a flying Hunter and Jockey + int aHunterJockey = -1; + float hunjoc_pos[3]; + float min_dist_HunJoc = 100000.0; + + if (c_bBash_Enabled && !NeedsTeammateHelp_ExceptSmoker(client)) { + for (int x = 1; x <= MaxClients; ++x) { + if (isInfected(x) + && IsPlayerAlive(x) + && !isStagger(x) + && isVisibleTo(client, x)) + { + if (getZombieClass(x) == ZC_HUNTER) { + if (c_iBash_HunterChance == 100 || (c_iBash_HunterChance < 100 && g_bShove[client][x])) { + float hunterVelocity[3]; + GetEntDataVector(x, g_Velo, hunterVelocity); + if ((GetClientButtons(x) & IN_DUCK) && hunterVelocity[2] != 0.0) { + GetClientAbsOrigin(x, hunjoc_pos); + + float hundist; + hundist = GetVectorDistance(self_pos, hunjoc_pos, true); + + if (hundist < c_fBash_HunterRange) { // 145.0 best + if (hundist < min_dist_HunJoc) { + min_dist_HunJoc = hundist; + aHunterJockey = x; + } + } + } + } + } + else if (getZombieClass(x) == ZC_JOCKEY) { + if (c_iBash_JockeyChance == 100 || (c_iBash_JockeyChance < 100 && g_bShove[client][x])) { + float jockeyVelocity[3]; + GetEntDataVector(x, g_Velo, jockeyVelocity); + if (jockeyVelocity[2] != 0.0) { + GetClientAbsOrigin(x, hunjoc_pos); + + float jocdist; + jocdist = GetVectorDistance(self_pos, hunjoc_pos, true); + + if (jocdist < c_fBash_JockeyRange) { // 125.0 best + if (jocdist < min_dist_HunJoc) { + min_dist_HunJoc = jocdist; + aHunterJockey = x; + } + } + } + } + } + } + } + } + + // Find a Common Infected + //int iMaxEntities = GetMaxEntities(); + int aCommonInfected = -1; + int iCI_MeleeCount = 0; + float min_dist_CI = 10000000000.0; + float ci_pos[3]; + + if (c_bCI_Enabled && !NeedsTeammateHelp(client)) { + for (int iEntity = MaxClients+1; iEntity <= MAXENTITIES; ++iEntity) { + if (IsCommonInfected(iEntity) + && GetEntProp(iEntity, Prop_Data, "m_iHealth") > 0 + && isVisibleToEntity(iEntity, client)) + { + float dist; + GetEntPropVector(iEntity, Prop_Data, "m_vecAbsOrigin", ci_pos); + dist = GetVectorDistance(self_pos, ci_pos, true); + + if (dist < c_fCI_Range) { + int iSeq = GetEntProp(iEntity, Prop_Send, "m_nSequence", 2); + // Stagger 122, 123, 126, 127, 128, 133, 134 + // Down Stagger 128, 129, 130, 131 + // Object Climb (Very Low) 182, 183, 184, 185 + // Object Climb (Low) 190, 191, 192, 193, 194, 195, 196, 197, 198, 199 + // Object Climb (High) 206, 207, 208, 209, 210, 211, 218, 219, 220, 221, 222, 223 + + if ((iSeq <= 121) || (iSeq >= 135 && iSeq <= 189) || (iSeq >= 200 && iSeq <= 205) || (iSeq >= 224)) { + if (dist < min_dist_CI) { + min_dist_CI = dist; + aCommonInfected = iEntity; + } + } + } + + if (dist <= c_fCI_MeleeRange) { // ��낯�ĂĂ� MeleeCount �ɂ͓���� + iCI_MeleeCount += 1; + } + + } + } + } + + // Fina a rage Witch + int aWitch = -1; + float min_dist_Witch = 10000000000.0; + float witch_pos[3]; + if (g_bWitchActive && c_bWitch_Enabled && !NeedsTeammateHelp(client)) { + for (int iEntity = MaxClients+1; iEntity <= MAXENTITIES; ++iEntity) + { + if (IsWitch(iEntity) + && GetEntProp(iEntity, Prop_Data, "m_iHealth") > 0 + && IsWitchRage(iEntity) + && isVisibleToEntity(iEntity, client)) + { + float witch_dist; + GetEntPropVector(iEntity, Prop_Data, "m_vecAbsOrigin", witch_pos); + witch_dist = GetVectorDistance(self_pos, witch_pos, true); + + if ((g_iWitch_Process[iEntity] == 0 && witch_dist < c_fWitch_Range) + || (g_iWitch_Process[iEntity] == WITCH_INCAPACITATED && witch_dist < c_fWitch_Range_Incapacitated) + || (g_iWitch_Process[iEntity] == WITCH_KILLED && witch_dist < c_fWitch_Range_Killed)) { + if (witch_dist < min_dist_Witch) { + min_dist_Witch = witch_dist; + aWitch = iEntity; + } + } + } + } + } + + // Find a tank rock + int aTankRock = -1; + float rock_min_dist = 10000000000.0; + float rock_pos[3]; + if (c_bRock_Enabled && !NeedsTeammateHelp(client)) { + for (int iEntity = MaxClients+1; iEntity <= MAXENTITIES; ++iEntity) + { + if (IsTankRock(iEntity) + && isVisibleToEntity(iEntity, client)) + { + float rock_dist; + GetEntPropVector(iEntity, Prop_Data, "m_vecAbsOrigin", rock_pos); + rock_dist = GetVectorDistance(self_pos, rock_pos, true); + + if (rock_dist < c_fRock_Range) { + if (rock_dist < rock_min_dist) { + rock_min_dist = rock_dist; + aTankRock = iEntity; + } + } + } + } + } + + + + /* -------------------------------------------------------------------------------------------------------------------------------------------------------------- + ***************************** + * Get The Weapon * + ***************************** + --------------------------------------------------------------------------------------------------------------------------------------------------------------- */ + + int weapon = GetEntDataEnt2(client, g_ActiveWeapon); + + static char AW_Classname[32]; + if (weapon > MAXPLAYERS) GetEntityClassname(weapon, AW_Classname, sizeof(AW_Classname)); // Exception reported: Entity -1 (-1) is invalid + + static char main_weapon[32]; + int slot0 = GetPlayerWeaponSlot(client, 0); + if (slot0 > -1) { + GetEntityClassname(slot0, main_weapon, sizeof(main_weapon)); + } + + /* -------------------------------------------------------------------------------------------------------------------------------------------------------------- + ********************** + * Action * + ********************** + --------------------------------------------------------------------------------------------------------------------------------------------------------------- */ + + /* ==================================================================================================== + * + * Other Adjustment + * + ==================================================================================================== */ + if (g_bDanger[client]) { // If have the medkit even though it is dangerous, switch to the main weapon + if (isHaveItem(AW_Classname, "weapon_first_aid_kit")) { + if (main_weapon[1] != 0) { + FakeClientCommand(client, "use %s", main_weapon); + } else { + static char sub_weapon[32]; + int slot1 = GetPlayerWeaponSlot(client, 1); + if (slot1 > -1) { + GetEntityClassname(slot1, sub_weapon, sizeof(sub_weapon)); // SubWeapon + } + + FakeClientCommand(client, "use %s", main_weapon); + } + } + } + + if (g_bCommonWithinMelee[client]) { + if (aCommonInfected < 1) g_bCommonWithinMelee[client] = false; + if (aCommonInfected > 0) { + float c_pos[3], common_e_pos[3]; + + GetClientAbsOrigin(client, c_pos); + GetEntPropVector(aCommonInfected, Prop_Data, "m_vecOrigin", common_e_pos); + + float aimdist = GetVectorDistance(c_pos, common_e_pos, true); + + if (aimdist > c_fCI_MeleeRange) g_bCommonWithinMelee[client] = false; + } + } + + + + /* ==================================================================================================== + * + * �D��xA : Bash | flying Hunter, Jockey + * + ==================================================================================================== */ + if (aHunterJockey > 0) { + if (!g_bDanger[client]) g_bDanger[client] = true; + + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientAbsOrigin(client, c_pos); + GetClientAbsOrigin(aHunterJockey, e_pos); + e_pos[2] += -10.0; + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + buttons |= IN_ATTACK2; + if (c_bDebug_Enabled) { + PrintToChatAll("\x01[%.2f] \x05%N \x01shoved: \x04flying %N (%d)", GetGameTime(), client, aHunterJockey, aHunterJockey); + EmitSoundToAll(SOUND_SWING, client); + } + return Plugin_Changed; + } + + + /* ==================================================================================================== + * + * �D��xB : Self Smoker | aCapSmoker + * + ==================================================================================================== */ + if (aCapSmoker > 0) { // Shoot even if client invisible the smoker + if (!g_bDanger[client]) g_bDanger[client] = true; + + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientAbsOrigin(client, c_pos); + GetEntPropVector(aCapSmoker, Prop_Data, "m_vecOrigin", e_pos); + e_pos[2] += 5.0; + + //PrintToChatAll("c_pos[0] %.1f | [1] %.1f | [2] %.1f", c_pos[0], c_pos[1], c_pos[2]); + //PrintToChatAll("e_pos[0] %.1f | [1] %.1f | [2] %.1f", e_pos[0], e_pos[1], e_pos[2]); + + // GetClientEyePosition(client, c_pos); + // GetClientEyePosition(aCapSmoker, e_pos); + // e_pos[2] += -10.0; + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N \x01Cap Smoker: \x04%N (%d)", GetGameTime(), client, aCapSmoker, aCapSmoker); + + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + float aimdist = GetVectorDistance(c_pos, e_pos, true); + + if (aimdist < 100.0) buttons |= IN_ATTACK2; + else { + buttons &= ~IN_ATTACK2; + buttons |= IN_DUCK; + } + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + + + /* ==================================================================================================== + * + * �D��xC : Help | aCap_Infected, aCap_Survivor + * + ==================================================================================================== */ + if (aCap_Survivor > 0) { // Pass if the client and target are "visible" to each other. so aCap Smoker doesn't pass + if (!g_bDanger[client]) g_bDanger[client] = true; + + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetClientEyePosition(aCap_Survivor, e_pos); + + if (HasValidEnt(aCap_Survivor, "m_pounceAttacker")) e_pos[2] += 5.0; + else if (aCapSmoker > 0) { // ���������Ă���Smoker + GetClientEyePosition(aCapSmoker, e_pos); + e_pos[2] += -10.0; + } + + float aimdist = GetVectorDistance(c_pos, e_pos, true); + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N \x01Cap Survivor: \x04%N (%d)", GetGameTime(), client, aCap_Survivor, aCap_Survivor); + + /****************************************************************************************************/ + + // If any of the following are active, Switch to the main weapon + if (isHaveItem(AW_Classname, "weapon_first_aid_kit") + || isHaveItem(AW_Classname, "weapon_defibrillator") + || HasValidEnt(client, "m_reviveTarget")) { + UseItem(client, main_weapon); + } + + // If the melee weapon is active and the dist from the target is 110 or more, switch to the main weapon + if (isHaveItem(AW_Classname, "weapon_melee") && aimdist > 11000.0) { + if (g_bCommonWithinMelee[client]) g_bCommonWithinMelee[client] = false; + UseItem(client, main_weapon); + } + + /****************************************************************************************************/ + + if (!isHaveItem(AW_Classname, "weapon_melee") || aimdist < 11000.0) { + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (((c_iHelp_ShoveType >= 1 && HasValidEnt(aCap_Survivor, "m_tongueOwner") && aimdist < 12100.0) + || (c_iHelp_ShoveType >= 2 && HasValidEnt(aCap_Survivor, "m_jockeyAttacker") && aimdist < 10000.0) + || (c_iHelp_ShoveType >= 3 && HasValidEnt(aCap_Survivor, "m_pounceAttacker") && aimdist < 10000.0))) + { + if ((!c_bHelp_ShoveOnlyReloading) || (c_bHelp_ShoveOnlyReloading && isReloading(client))) + buttons |= IN_ATTACK2; // ���� + } + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + } + else if (aCap_Infected > 0 && aCap_Survivor < 1) { + if (!g_bDanger[client]) g_bDanger[client] = true; + + int zombieClass = getZombieClass(aCap_Infected); + + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + + if (aCapSmoker > 0) { // Prioritize aCapSmoker + GetClientEyePosition(aCapSmoker, e_pos); + e_pos[2] += -10.0; + } else { + GetClientEyePosition(aCap_Infected, e_pos); + + if (zombieClass == ZC_SMOKER || zombieClass == ZC_CHARGER) e_pos[2] += -9.0; + else if (zombieClass == ZC_HUNTER) e_pos[2] += -14.0; + } + + float aimdist = GetVectorDistance(c_pos, e_pos, true); + + if (zombieClass == ZC_CHARGER && aimdist < 300.0) e_pos[2] += 10.0; + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N \x01Cap Infected: \x04%N (%d)", GetGameTime(), client, aCap_Infected, aCap_Infected); + + /****************************************************************************************************/ + + // If any of the following are active, Switch to the main weapon + if (isHaveItem(AW_Classname, "weapon_first_aid_kit") + || isHaveItem(AW_Classname, "weapon_defibrillator") + || HasValidEnt(client, "m_reviveTarget")) + { + UseItem(client, main_weapon); + } + + // If the melee weapon is active and the dist from the target is 110 or more, switch to the main weapon + if (isHaveItem(AW_Classname, "weapon_melee") && aimdist > 11000.0) + { + if (g_bCommonWithinMelee[client]) g_bCommonWithinMelee[client] = false; + UseItem(client, main_weapon); + } + + /****************************************************************************************************/ + + if (!isHaveItem(AW_Classname, "weapon_melee") || aimdist < 11000.0) { + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (aimdist < 10000.0 + && ((c_iHelp_ShoveType >= 1 && zombieClass == ZC_SMOKER) + || (c_iHelp_ShoveType >= 2 && zombieClass == ZC_JOCKEY) + || (c_iHelp_ShoveType >= 3 && zombieClass == ZC_HUNTER))) + { + if ((!c_bHelp_ShoveOnlyReloading) || (c_bHelp_ShoveOnlyReloading && isReloading(client))) + buttons |= IN_ATTACK2; // Shove + } + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + } + + + + /* ==================================================================================================== + * + * �D��xD : Tank Rock, Witch + * + ==================================================================================================== */ + if (aTankRock > 1 && !HasValidEnt(client, "m_reviveTarget")) { + float c_pos[3], rock_e_pos[3]; + float lookat[3]; + + GetClientAbsOrigin(client, c_pos); + GetEntPropVector(aTankRock, Prop_Data, "m_vecAbsOrigin", rock_e_pos); + rock_e_pos[2] += -50.0; + + MakeVectorFromPoints(c_pos, rock_e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) { + // PrintToChatAll("\x01rock : \x01[0] - \x04%.2f \x01, [1] - \x04%.2f \x01, [2] - \x04%.2f", rock_e_pos[0], rock_e_pos[1], rock_e_pos[2]); + // PrintToChatAll("\x01client(%N) : \x01[0] - \x04%.2f \x01, [1] - \x04%.2f \x01, [2] - \x04%.2f", client, c_pos[0], c_pos[1], c_pos[2]); + // PrintToChatAll("---"); + } + + float aimdist = GetVectorDistance(c_pos, rock_e_pos, true); + + if (aimdist > 1600.0 && !isHaveItem(AW_Classname, "weapon_melee")) { //�ߐڂ������Ă��Ȃ��ꍇ + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + } + + return Plugin_Changed; + } + + if (aWitch > 1) { + float c_pos[3], witch_e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetEntPropVector(aWitch, Prop_Data, "m_vecAbsOrigin", witch_e_pos); + witch_e_pos[2] += 40.0; + + MakeVectorFromPoints(c_pos, witch_e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N \x01Witch: \x05(%d)", GetGameTime(), client, aWitch); + + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + float aimdist = GetVectorDistance(c_pos, witch_e_pos, true); + + if (c_bWitch_Shotgun_Control && StrContains(AW_Classname, "shotgun") != -1) { + if (aimdist < 22500.0) buttons |= IN_DUCK; + + if (aimdist < c_fWitch_Shotgun_Range_Min || aimdist > c_fWitch_Shotgun_Range_Max) { // 70 ~ 300 + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + //PrintToChatAll("\x05%N %.2f", client, aimdist); + } else { + buttons &= ~IN_ATTACK; + //PrintToChatAll("\x04%N Attack Stop %.2f", client, aimdist); + } + return Plugin_Changed; + } + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + + + + /* ==================================================================================================== + * + * �D��xE : Common Infected + * + ==================================================================================================== */ + if (aCommonInfected > 0) { + if (!HasValidEnt(client, "m_reviveTarget") && StrEqual(AW_Classname, "weapon_first_aid_kit", false)) { + // Even if aCommonInfected dies and disappears, the Entity may not disappear for a while.(Bot keeps shooting the place)�B Even with InValidEntity(), true appears... + // When the entity disappears, m_nNextThinkTick will not advance, so skip that if NextThinkTick has the same value as before. + + int iNextThinkTick = GetEntProp(aCommonInfected, Prop_Data, "m_nNextThinkTick"); + + if (g_Stock_NextThinkTick[client] != iNextThinkTick) // If visible aCommonInfected + { + float c_pos[3], common_e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetEntPropVector(aCommonInfected, Prop_Data, "m_vecOrigin", common_e_pos); + + //float height_difference = (c_pos[2] - common_e_pos[2]) - 60.0; + + common_e_pos[2] += 40.0; + + float aimdist = GetVectorDistance(c_pos, common_e_pos, true); + + //common_e_pos[2] += (25.0 + (aimdist * 0.05) - (height_difference * 0.1)); + + // GetClientAbsOrigin(client, c_pos); + // GetEntPropVector(aCommonInfected, Prop_Data, "m_vecOrigin", common_e_pos); + // common_e_pos[2] += -30.0; + + int iSeq = GetEntProp(aCommonInfected, Prop_Send, "m_nSequence", 2); + // Stagger 122, 123, 126, 127, 128, 133, 134 + // Down Stagger 128, 129, 130, 131 + // Object Climb (Very Low) 182, 183, 184, 185 + // Object Climb (Low) 190, 191, 192, 193, 194, 195, 196, 197, 198, 199 + // Object Climb (High) 206, 207, 208, 209, 210, 211, 218, 219, 220, 221, 222, 223 + if (iSeq >= 182 && iSeq <= 189) common_e_pos[2] += -10.0; + + MakeVectorFromPoints(c_pos, common_e_pos, lookat); + GetVectorAngles(lookat, angles); + + /****************************************************************************************************/ + + g_Stock_NextThinkTick[client] = iNextThinkTick; // Set the current m_nNextThinkTick + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N\x01 Commons: \x04(%d)\x01 | Dist: \x04%.1f\x01 | Melee Count: \x04%d", GetGameTime(), client, aCommonInfected, aimdist, iCI_MeleeCount); + + // iCI_MeleeCount is from ci_melee_range + if (c_bCI_MeleeEnabled + && aimdist <= c_fCI_MeleeRange + && iCI_MeleeCount > 2) { + g_bCommonWithinMelee[client] = true; + + static char sub_weapon[16]; + int slot1 = GetPlayerWeaponSlot(client, 1); + if (slot1 > -1) { + GetEntityClassname(slot1, sub_weapon, sizeof(sub_weapon)); // SubWeapon + } + + if (isHaveItem(sub_weapon, "weapon_melee")) { + if (!isHaveItem(AW_Classname, "weapon_melee")) { + FakeClientCommand(client, "use %s", sub_weapon); + } + } + } + + if (int_target > 0) { + if (aimdist <= 90.0) TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + } else { + if (isHaveItem(AW_Classname, "weapon_melee")) { + if (aimdist <= 90.0) TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + } else { + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + } + } + + if (int_target < 1 || (int_target > 0 && aimdist <= 90.0)) { // If int_target and common at the same time, prioritize to int_target. Attack only when within 90.0 dist. + if (isHaveItem(AW_Classname, "weapon_melee")) { + if (GetRandomInt(0, 6) == 0) { + if (aimdist <= 50.0) buttons |= IN_ATTACK2; + else if (aimdist > 50.0 && aimdist <= 90.0) buttons |= IN_ATTACK; + } else { + if (aimdist <= 90.0) buttons |= IN_ATTACK; // 90.0 + } + + // if (GetRandomInt(0, 6) == 0) { + // if (aimdist < 50.0) { + // buttons |= IN_ATTACK2; + // } + // } else { + // if (aimdist < 90.0) buttons |= IN_ATTACK; + // } + } else { + if (aimdist > 3600.0) { + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + } else { + if (GetRandomInt(0, 8) == 0) { + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + } else { + buttons |= IN_ATTACK2; + } + + if (isReloading(client)) { + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK2; + else buttons |= IN_ATTACK2; + } + } + } + return Plugin_Changed; + } + } + else // Skip if aCommonInfected is not visible + { + // PrintToChatAll("stock %i | next %i", g_Stock_NextThinkTick[client], iNextThinkTick); + } + } + } + + + + /* ==================================================================================================== + * + * �D��xF : Special Infected and Tank (int_target) + * + ==================================================================================================== */ + if (int_target > 0) { + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientAbsOrigin(client, c_pos); + + int zombieClass = getZombieClass(int_target); + + if (aCapSmoker > 0) { // Prioritize aCapSmoker + GetClientAbsOrigin(aCapSmoker, e_pos); + e_pos[2] += -10.0; + } else { + GetClientAbsOrigin(int_target, e_pos); + if (zombieClass == ZC_HUNTER + && (GetClientButtons(int_target) & IN_DUCK)) { + if (GetVectorDistance(c_pos, e_pos, true) > 6250.0) e_pos[2] += -30.0; + else e_pos[2] += -35.0; + } else if (zombieClass == ZC_JOCKEY) { + e_pos[2] += -30.0; + } else { + e_pos[2] += -10.0; + } + } + + if (zombieClass == ZC_TANK && aTankRock > 0) return Plugin_Continue; // If the Tank and tank rock are visible at the same time, prioritize the tank rock + + float aimdist = GetVectorDistance(c_pos, e_pos, true); + + if (aimdist < 40000.0) {if (!g_bDanger[client]) g_bDanger[client] = true;} + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + /****************************************************************************************************/ + + if(isHaveItem(AW_Classname, "first_aid_kit") + || isHaveItem(AW_Classname, "defibrillator") + || HasValidEnt(client, "m_reviveTarget")) { + if (aimdist > 6250.0) return Plugin_Continue; + else { UseItem(client, main_weapon); } + } + + if (isHaveItem(AW_Classname, "weapon_shotgun_chrome") + || isHaveItem(AW_Classname, "weapon_shotgun_spas") + || isHaveItem(AW_Classname, "weapon_pumpshotgun") + || isHaveItem(AW_Classname, "weapon_autoshotgun")) { + if (aimdist > 1000000.0) return Plugin_Continue; + } + + if (isHaveItem(AW_Classname, "weapon_melee") && aCommonInfected < 1) { + if (aimdist > 1000000.0) UseItem(client, main_weapon); + } + + /****************************************************************************************************/ + + bool isTargetBoomer = false; + bool isBoomer_Shoot_OK = false; + + if (c_bSI_IgnoreBoomer && zombieClass == ZC_BOOMER) { + float voS_pos[3]; + for (int s = 1; s <= MaxClients; ++s) { + if (isSurvivor(s) + && IsPlayerAlive(s)) + { + float fVomit = GetEntPropFloat(s, Prop_Send, "m_vomitStart"); + if (GetGameTime() - fVomit > 10.0) { // Survivors without vomit + GetClientAbsOrigin(s, voS_pos); + + float dist = GetVectorDistance(voS_pos, e_pos, true); // Distance between the Survivor without vomit and the Boomer + if (dist >= c_fSI_IgnoreBoomerRange) { isBoomer_Shoot_OK = true; } // If the survivor without vomit is farther than dist "c_fSI_IgnoreBoomerRange (def: 200)" + else { isBoomer_Shoot_OK = false; break; } // If False appears even once, break + } + } + } + isTargetBoomer = true; + } + + if ((zombieClass == ZC_JOCKEY && g_bShove[client][int_target]) + || zombieClass == ZC_SMOKER + || (isTargetBoomer && !isBoomer_Shoot_OK)) + { + if (aimdist < 8100.0 && !isStagger(int_target)) { + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + buttons |= IN_ATTACK2; + if (c_bDebug_Enabled) { + PrintToChatAll("\x01[%.2f] \x05%N\x01 int_target shoved: \x04%N (%d)", GetGameTime(), client, int_target, int_target); + EmitSoundToAll(SOUND_SWING, client); + } + return Plugin_Changed; + } + } + + if (!isHaveItem(AW_Classname, "weapon_melee") || aimdist < 10000.0) + { + if (c_bDebug_Enabled) { + if (!isTargetBoomer) PrintToChatAll("\x01[%.2f] \x05%N\x01 int_target: \x04%N (%d)", GetGameTime(), client, int_target, int_target); + else PrintToChatAll("\x01[%.2f] \x05%N\x01 int_target: \x04%N (%d) (Shoot: %s)", GetGameTime(), client, int_target, int_target, (isBoomer_Shoot_OK) ? "OK" : "NO"); + } + + if (!isTargetBoomer || (isTargetBoomer && isBoomer_Shoot_OK)) { + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + } + + return Plugin_Changed; + } + } + + // if there is no danger, false + if (g_bDanger[client]) g_bDanger[client] = false; + } + + return Plugin_Continue; +} + + + +/* ================================================================================================ +*= +*= Incapacitated Run Cmd +*= +================================================================================================ */ +stock Action onSBRunCmd_Incapacitated(int client, int &buttons, float vel[3], float angles[3]) +{ + if (isIncapacitated(client)) { + int aCapper = -1; + float min_dist_Cap = 10000000000.0; + float self_pos[3], target_pos[3]; + + GetClientEyePosition(client, self_pos); + if (!NeedsTeammateHelp(client)) { + for (int x = 1; x <= MaxClients; ++x) { + // �S������Ă��鐶���҂�T�� + if (isSurvivor(x) + && NeedsTeammateHelp(x) + && (x != client) + && (isVisibleTo(client, x) || isVisibleTo(x, client))) + { + GetClientAbsOrigin(x, target_pos); + float dist = GetVectorDistance(self_pos, target_pos, true); + if (dist < min_dist_Cap) { + min_dist_Cap = dist; + aCapper = x; + } + } + + // �S�����Ă�����ꊴ���҂�T�� + if (isInfected(x) + && CappingSuvivor(x) + && (isVisibleTo(client, x) || isVisibleTo(x, client))) + { + GetClientAbsOrigin(x, target_pos); + float dist = GetVectorDistance(self_pos, target_pos, true); + if (dist < min_dist_Cap) { + min_dist_Cap = dist; + aCapper = x; + } + } + } + } + + if (aCapper > 0) { + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetClientEyePosition(aCapper, e_pos); + + e_pos[2] += -15.0; + + if ((isSurvivor(aCapper) && HasValidEnt(aCapper, "m_pounceAttacker"))) { + e_pos[2] += 18.0; + // Raise angles if near + } + if ((isInfected(aCapper) && getZombieClass(aCapper) == ZC_HUNTER)) { + e_pos[2] += -15.0; + } + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) { + if (isSurvivor(aCapper)) PrintToChatAll("\x01[%.2f] \x05%N \x01Cap Survivor Incapacitated: \x04%N", GetGameTime(), client, aCapper); + else PrintToChatAll("\x01[%.2f] \x05%N \x01Cap Infected Incapacitated: \x04%N", GetGameTime(), client, aCapper); + } + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + + + int int_target = -1; + int aCommonInfected = -1; + if (aCapper < 1 && !NeedsTeammateHelp(client)) { + float min_dist = 10000000000.0; + float ci_pos[3]; + + for (int x = 1; x <= MaxClients; ++x){ + if (isInfected(x) + && IsPlayerAlive(x) + && (isVisibleTo(client, x) || isVisibleTo(x, client))) + { + GetClientAbsOrigin(x, target_pos); + float dist = GetVectorDistance(self_pos, target_pos, true); + if (dist < min_dist) { + min_dist = dist; + int_target = x; + aCommonInfected = -1; + } + } + } + + if (c_bCI_Enabled) { + for (int iEntity = MaxClients+1; iEntity <= MAXENTITIES; ++iEntity) { + if (IsCommonInfected(iEntity) + && GetEntProp(iEntity, Prop_Data, "m_iHealth") > 0 + && isVisibleToEntity(iEntity, client)) + { + GetEntPropVector(iEntity, Prop_Data, "m_vecAbsOrigin", ci_pos); + float dist = GetVectorDistance(self_pos, ci_pos, true); + + if (dist < min_dist) { + min_dist = dist; + aCommonInfected = iEntity; + int_target = -1; + } + } + } + } + } + + if (aCommonInfected > 0) { + float c_pos[3], common_e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetEntPropVector(aCommonInfected, Prop_Data, "m_vecOrigin", common_e_pos); + common_e_pos[2] += 35.0; + + MakeVectorFromPoints(c_pos, common_e_pos, lookat); + GetVectorAngles(lookat, angles); + + float aimdist = GetVectorDistance(c_pos, common_e_pos, true); + + /****************************************************************************************************/ + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N\x01 Commons Incapacitated Dist: %.1f", GetGameTime(), client, aimdist); + + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + + if (int_target > 0) { + float c_pos[3], e_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, c_pos); + GetClientEyePosition(int_target, e_pos); + + e_pos[2] += -15.0 + + int zombieClass = getZombieClass(int_target); + if (zombieClass == ZC_JOCKEY) { + e_pos[2] += -30.0; + } else if (zombieClass == ZC_HUNTER) { + if ((GetClientButtons(int_target) & IN_DUCK) || HasValidEnt(int_target, "m_pounceVictim")) e_pos[2] += -25.0; + } + + MakeVectorFromPoints(c_pos, e_pos, lookat); + GetVectorAngles(lookat, angles); + + if (c_bDebug_Enabled) PrintToChatAll("\x01[%.2f] \x05%N \x01int target Incapacitated: \x04%N", GetGameTime(), client, int_target); + + TeleportEntity(client, NULL_VECTOR, angles, NULL_VECTOR); + + if (GetRandomInt(0, 4) == 0) buttons &= ~IN_ATTACK; + else buttons |= IN_ATTACK; + + return Plugin_Changed; + } + } + + return Plugin_Continue; +} + + +/* ================================================================================================ +*= +*= Events +*= +================================================================================================ */ +public Action Event_PlayerIncapacitated(Handle event, const char[] name, bool dontBroadcast) +{ + if (!g_hEnabled) return Plugin_Handled; + + int victim = GetClientOfUserId(GetEventInt(event, "userid")); + int attackerentid = GetEventInt(event, "attackerentid"); + + // int type = GetEventInt(event, "type"); + // PrintToChatAll("\x04PlayerIncapacitated"); + // PrintToChatAll("type %i", type); + + if (isSurvivor(victim) && IsWitch(attackerentid)) + { + g_iWitch_Process[attackerentid] = WITCH_INCAPACITATED; + + // PrintToChatAll("attackerentid %i attacked %N", attackerentid, victim); + // int health = GetEventInt(event, "health"); + // int dmg_health = GetEventInt(event, "dmg_health"); + // PrintToChatAll("health: %i, damage: %i", health, dmg_health); + } + + return Plugin_Handled; +} + +public Action Event_PlayerDeath(Handle event, const char[] name, bool dontBroadcast) +{ + if (!g_hEnabled) return Plugin_Handled; + + int victim = GetClientOfUserId(GetEventInt(event, "userid")); + int attackerentid = GetEventInt(event, "attackerentid"); + + // int type = GetEventInt(event, "type"); + // PrintToChatAll("\x04PlayerDeath"); + // PrintToChatAll("type %i", type); + + if (isSurvivor(victim) && IsWitch(attackerentid)) + { + g_iWitch_Process[attackerentid] = WITCH_KILLED; + + // PrintToChatAll("attackerentid %i attacked %N", attackerentid, victim); + // int health = GetEventInt(event, "health"); + // int dmg_health = GetEventInt(event, "dmg_health"); + // PrintToChatAll("health: %i, damage: %i", health, dmg_health); + } + + // Witch Damage type: 4 + // Witch Incapacitated type: 32772 + + return Plugin_Handled; +} + +public void Event_WitchRage(Handle event, const char[] name, bool dontBroadcast) +{ + int attacker = GetClientOfUserId(GetEventInt(event, "userid")); + + if (isSurvivor(attacker)) { + // CallBotstoWitch(attacker); + g_bWitchActive = true; + } +} + +public void OnEntityCreated(int entity, const char[] classname) +{ + if (entity >= MaxClients && g_hEnabled && strcmp(classname, "witch") == 0) + { + g_iWitch_Process[entity] = 0; + } +} + +public void OnEntityDestroyed(int entity) { + if(entity == -1) return; + static char classname[32]; + GetEntityClassname(entity, classname, sizeof(classname)); + + if (StrEqual(classname, "witch", false)) { + if (g_bWitchActive) { + int iWitch_Count = 0; + for (int iEntity = MaxClients+1; iEntity <= MAXENTITIES; ++iEntity) + { + if (IsWitch(iEntity) && GetEntProp(iEntity, Prop_Data, "m_iHealth") > 0 && IsWitchRage(iEntity)) + { + iWitch_Count++; + } + + //PrintToChatAll("witch count %d", iWitch_Count); + + if (iWitch_Count == 0) {g_bWitchActive = false;} + } + } + } +} + + +/* ================================================================================================ +*= +*= Stock any +*= +================================================================================================ */ +stock void ScriptCommand(int client, const char[] command, const char[] arguments, any ...) +{ + static char vscript[PLATFORM_MAX_PATH]; + VFormat(vscript, sizeof(vscript), arguments, 4); + + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", command, vscript); + SetCommandFlags(command, flags); +} + +stock void L4D2_RunScript(const char[] sCode, any ...) +{ + static int iScriptLogic = INVALID_ENT_REFERENCE; + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) { + iScriptLogic = EntIndexToEntRef(CreateEntityByName("logic_script")); + if(iScriptLogic == INVALID_ENT_REFERENCE || !IsValidEntity(iScriptLogic)) + SetFailState("Could not create 'logic_script'"); + + DispatchSpawn(iScriptLogic); + } + + static char sBuffer[512]; + VFormat(sBuffer, sizeof(sBuffer), sCode, 2); + + SetVariantString(sBuffer); + AcceptEntityInput(iScriptLogic, "RunScriptCode"); +} + + +/* +* +* Bool +* +*/ +stock bool NeedsTeammateHelp(int client) +{ + if (HasValidEnt(client, "m_tongueOwner") + || HasValidEnt(client, "m_pounceAttacker") + || HasValidEnt(client, "m_jockeyAttacker") + || HasValidEnt(client, "m_carryAttacker") + || HasValidEnt(client, "m_pummelAttacker")) + { + return true; + } + + return false; +} + +stock bool NeedsTeammateHelp_ExceptSmoker(int client) +{ + if (HasValidEnt(client, "m_pounceAttacker") + || HasValidEnt(client, "m_jockeyAttacker") + || HasValidEnt(client, "m_carryAttacker") + || HasValidEnt(client, "m_pummelAttacker")) + { + return true; + } + + return false; +} + +stock bool CappingSuvivor(int client) +{ + if (HasValidEnt(client, "m_tongueVictim") + || HasValidEnt(client, "m_pounceVictim") + || HasValidEnt(client, "m_jockeyVictim") + || HasValidEnt(client, "m_carryVictim") + || HasValidEnt(client, "m_pummelVictim")) + { + return true; + } + + return false; +} + +stock bool HasValidEnt(int client, const char[] entprop) +{ + int ent = GetEntPropEnt(client, Prop_Send, entprop); + + return (ent > 0 + && IsClientInGame(ent)); +} + +stock bool IsWitchRage(int id) { + if (GetEntPropFloat(id, Prop_Send, "m_rage") >= 1.0) return true; + return false; +} + +stock bool IsCommonInfected(int iEntity) +{ + if (iEntity && IsValidEntity(iEntity)) + { + static char strClassName[16]; + GetEntityClassname(iEntity, strClassName, sizeof(strClassName)); + + if (strcmp(strClassName[7], "infected", false) == 0) + return true; + } + return false; +} + +stock bool IsWitch(int iEntity) +{ + if (iEntity && IsValidEntity(iEntity)) + { + static char strClassName[8]; + GetEntityClassname(iEntity, strClassName, sizeof(strClassName)); + if (StrEqual(strClassName, "witch")) + return true; + } + return false; +} + +stock bool IsTankRock(int iEntity) +{ + if (iEntity && IsValidEntity(iEntity)) + { + static char strClassName[16]; + GetEntityClassname(iEntity, strClassName, sizeof(strClassName)); + if (StrEqual(strClassName, "tank_rock")) + return true; + } + return false; +} + +stock bool isGhost(int i) +{ + return GetEntProp(i, Prop_Send, "m_isGhost") != 0; +} + +stock bool isSpecialInfectedBot(int i) +{ + return i > 0 && i <= MaxClients && IsClientInGame(i) && IsFakeClient(i) && GetClientTeam(i) == 3; +} + +stock bool isSurvivorBot(int i) +{ + return isSurvivor(i) && IsFakeClient(i); +} + +stock bool isInfected(int i) +{ + return i > 0 && i <= MaxClients && IsClientInGame(i) && GetClientTeam(i) == 3 && !isGhost(i); +} + +stock bool isSurvivor(int i) +{ + return i > 0 && i <= MaxClients && IsClientInGame(i) && GetClientTeam(i) == 2; +} + +stock any getZombieClass(int client) +{ + return GetEntProp(client, Prop_Send, "m_zombieClass"); +} + +stock bool isIncapacitated(int client) +{ + return GetEntProp(client, Prop_Send, "m_isIncapacitated", 1) == 1; +} + +stock bool isReloading(int client) +{ + int slot0 = GetPlayerWeaponSlot(client, 0); + if (slot0 > -1) { + return GetEntProp(slot0, Prop_Data, "m_bInReload") > 0; + } + return false; +} + +stock bool isStagger(int client) // Client Only +{ + float staggerPos[3]; + GetEntPropVector(client, Prop_Send, "m_staggerStart", staggerPos); + + if (staggerPos[0] != 0.0 && staggerPos[1] != 0.0 && staggerPos[2] != 0.0) return true; + + return false; +} + +stock bool isJockeyLeaping(int client) +{ + float jockeyVelocity[3]; + GetEntDataVector(client, g_Velo, jockeyVelocity); + if (jockeyVelocity[2] != 0.0) return true; + return false; +} + +stock bool isHaveItem(const char[] FItem, const char[] SItem) +{ + return StrEqual(FItem, SItem, false); +} + +stock void UseItem(int client, const char[] FItem) +{ + FakeClientCommand(client, "use %s", FItem); +} + +stock any PrimaryExtraAmmoCheck(int client, int weapon_index) +{ + // Offset: + // 12: Rifle ALL (Other than M60) + // 20: SMG ALL + // 28: Chrome, Pump + // 32: SPAS, Auto + // 36: Hunting + // 40: Sniper + // 68: Granade Launcher + // NONE: Rifle M60 is only Clip1 + int offset; + + static char sWeaponName[32]; + GetEdictClassname(weapon_index, sWeaponName, sizeof(sWeaponName)); + if (isHaveItem(sWeaponName, "weapon_rifle")) offset = 12; + else if (isHaveItem(sWeaponName, "weapon_smg")) offset = 20; + else if (isHaveItem(sWeaponName, "weapon_shotgun_chrome") || isHaveItem(sWeaponName, "weapon_pumpshotgun")) offset = 28; + else if (isHaveItem(sWeaponName, "weapon_shotgun_spas") || isHaveItem(sWeaponName, "weapon_autoshotgun")) offset = 32; + else if (isHaveItem(sWeaponName, "weapon_hunting_")) offset = 36; + else if (isHaveItem(sWeaponName, "weapon_sniper")) offset = 40; + else if (isHaveItem(sWeaponName, "weapon_grenade_launcher")) offset = 68; + + int extra_ammo = GetEntData(client, (g_iAmmoOffset + offset)); + //PrintToChatAll("%N Gun Name: %s, Offset: %i, ExtraAmmo: %i:", client, sWeaponName, offset, extra_ammo); + + return extra_ammo; +} + +/* -------------------------------------------------------------------------------------------------------------------------------------------------------------- + +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ + +public bool traceFilter(int entity, int mask, any self) +{ + return entity != self; +} + +public bool TraceRayDontHitPlayers(int entity, int mask) +{ + // Check if the beam hit a player and tell it to keep tracing if it did + return (entity <= 0 || entity > MaxClients); +} + +// Determine if the head of the target can be seen from the client +stock bool isVisibleTo(int client, int target) +{ + bool ret = false; + float aim_angles[3]; + float self_pos[3]; + + GetClientEyePosition(client, self_pos); + computeAimAngles(client, target, aim_angles); + + Handle trace = TR_TraceRayFilterEx(self_pos, aim_angles, MASK_VISIBLE, RayType_Infinite, traceFilter, client); + if (TR_DidHit(trace)) { + int hit = TR_GetEntityIndex(trace); + if (hit == target) { + ret = true; + } + } + delete trace; + return ret; +} + +/* Determine if the head of the entity can be seen from the client */ +stock bool isVisibleToEntity(int target, int client) +{ + bool ret = false; + float aim_angles[3]; + float self_pos[3], target_pos[3]; + float lookat[3]; + + GetEntPropVector(target, Prop_Data, "m_vecAbsOrigin", target_pos); + GetClientEyePosition(client, self_pos); + + MakeVectorFromPoints(target_pos, self_pos, lookat); + GetVectorAngles(lookat, aim_angles); + + Handle trace = TR_TraceRayFilterEx(target_pos, aim_angles, MASK_VISIBLE, RayType_Infinite, traceFilter, target); + if (TR_DidHit(trace)) { + int hit = TR_GetEntityIndex(trace); + if (hit == client) { + ret = true; + } + } + delete trace; + return ret; +} + +/* From the client to the target's head, whether it is blocked by mesh */ +stock bool isInterruptTo(int client, int target) +{ + bool ret = false; + float aim_angles[3]; + float self_pos[3]; + + GetClientEyePosition(client, self_pos); + computeAimAngles(client, target, aim_angles); + Handle trace = TR_TraceRayFilterEx(self_pos, aim_angles, MASK_SOLID, RayType_Infinite, traceFilter, client); + if (TR_DidHit(trace)) { + int hit = TR_GetEntityIndex(trace); + if (hit == target) { + ret = true; + } + } + delete trace; + return ret; +} + +// Calculate the angles from client to target +stock void computeAimAngles(int client, int target, float angles[3], int type = 1) +{ + float target_pos[3]; + float self_pos[3]; + float lookat[3]; + + GetClientEyePosition(client, self_pos); + switch (type) { + case 1: { // Eye (Default) + GetClientEyePosition(target, target_pos); + } + case 2: { // Body + GetEntPropVector(target, Prop_Data, "m_vecAbsOrigin", target_pos); + } + case 3: { // Chest + GetClientAbsOrigin(target, target_pos); + target_pos[2] += 45.0; + } + } + MakeVectorFromPoints(self_pos, target_pos, lookat); + GetVectorAngles(lookat, angles); +} diff --git a/scripting/l4d2_skill_detect.sp b/scripting/l4d2_skill_detect.sp new file mode 100644 index 0000000..4cc88d2 --- /dev/null +++ b/scripting/l4d2_skill_detect.sp @@ -0,0 +1,3125 @@ +/** + * L4D2_skill_detect + * + * Plugin to detect and forward reports about 'skill'-actions, + * such as skeets, crowns, levels, dp's. + * Works in campaign and versus modes. + * + * m_isAttemptingToPounce can only be trusted for + * AI hunters -- for human hunters this gets cleared + * instantly on taking killing damage + * + * Shotgun skeets and teamskeets are only counted if the + * added up damage to pounce_interrupt is done by shotguns + * only. 'Skeeting' chipped hunters shouldn't count, IMO. + * + * This performs global forward calls to: + * OnSkeet( survivor, hunter ) + * OnSkeetMelee( survivor, hunter ) + * OnSkeetGL( survivor, hunter ) + * OnSkeetSniper( survivor, hunter ) + * OnSkeetHurt( survivor, hunter, damage, isOverkill ) + * OnSkeetMeleeHurt( survivor, hunter, damage, isOverkill ) + * OnSkeetSniperHurt( survivor, hunter, damage, isOverkill ) + * OnHunterDeadstop( survivor, hunter ) + * OnBoomerPop( survivor, boomer, shoveCount, Float:timeAlive ) + * OnChargerLevel( survivor, charger ) + * OnChargerLevelHurt( survivor, charger, damage ) + * OnWitchCrown( survivor, damage ) + * OnWitchCrownHurt( survivor, damage, chipdamage ) + * OnTongueCut( survivor, smoker ) + * OnSmokerSelfClear( survivor, smoker, withShove ) + * OnTankRockSkeeted( survivor, tank ) + * OnTankRockEaten( tank, survivor ) + * OnHunterHighPounce( hunter, victim, actualDamage, Float:calculatedDamage, Float:height, bool:bReportedHigh, bool:bPlayerIncapped ) + * OnJockeyHighPounce( jockey, victim, Float:height, bool:bReportedHigh ) + * OnDeathCharge( charger, victim, Float: height, Float: distance, wasCarried ) + * OnSpecialShoved( survivor, infected, zombieClass ) + * OnSpecialClear( clearer, pinner, pinvictim, zombieClass, Float:timeA, Float:timeB, withShove ) + * OnBoomerVomitLanded( boomer, amount ) + * OnBunnyHopStreak( survivor, streak, Float:maxVelocity ) + * OnCarAlarmTriggered( survivor, infected, reason ) + * + * OnDeathChargeAssist( assister, charger, victim ) [ not done yet ] + * OnBHop( player, isInfected, speed, streak ) [ not done yet ] + * + * Where survivor == -2 if it was a team effort, -1 or 0 if unknown or invalid client. + * damage is the amount of damage done (that didn't add up to skeeting damage), + * and isOverkill indicates whether the shot would've been a skeet if the hunter + * had not been chipped. + * + * @author Tabun + * @libraryname skill_detect + */ + +#pragma semicolon 1 + +#include +#include +#include +#include + +#define PLUGIN_VERSION "1.0" + +#define IS_VALID_CLIENT(%1) (%1 > 0 && %1 <= MaxClients) +#define IS_SURVIVOR(%1) (GetClientTeam(%1) == 2) +#define IS_INFECTED(%1) (GetClientTeam(%1) == 3) +#define IS_VALID_INGAME(%1) (IS_VALID_CLIENT(%1) && IsClientInGame(%1)) +#define IS_VALID_SURVIVOR(%1) (IS_VALID_INGAME(%1) && IS_SURVIVOR(%1)) +#define IS_VALID_INFECTED(%1) (IS_VALID_INGAME(%1) && IS_INFECTED(%1)) +#define IS_SURVIVOR_ALIVE(%1) (IS_VALID_SURVIVOR(%1) && IsPlayerAlive(%1)) +#define IS_INFECTED_ALIVE(%1) (IS_VALID_INFECTED(%1) && IsPlayerAlive(%1)) +#define QUOTES(%1) (%1) + +#define SHOTGUN_BLAST_TIME 0.1 +#define POUNCE_CHECK_TIME 0.1 +#define HOP_CHECK_TIME 0.1 +#define HOPEND_CHECK_TIME 0.1 // after streak end (potentially) detected, to check for realz? +#define SHOVE_TIME 0.05 +#define MAX_CHARGE_TIME 12.0 // maximum time to pass before charge checking ends +#define CHARGE_CHECK_TIME 0.25 // check interval for survivors flying from impacts +#define CHARGE_END_CHECK 2.5 // after client hits ground after getting impact-charged: when to check whether it was a death +#define CHARGE_END_RECHECK 3.0 // safeguard wait to recheck on someone getting incapped out of bounds +#define VOMIT_DURATION_TIME 2.25 // how long the boomer vomit stream lasts -- when to check for boom count +#define ROCK_CHECK_TIME 0.34 // how long to wait after rock entity is destroyed before checking for skeet/eat (high to avoid lag issues) +#define CARALARM_MIN_TIME 0.11 // maximum time after touch/shot => alarm to connect the two events (test this for LAG) + +#define WITCH_CHECK_TIME 0.1 // time to wait before checking for witch crown after shoots fired +#define WITCH_DELETE_TIME 0.15 // time to wait before deleting entry from witch trie after entity is destroyed + +#define MIN_DC_TRIGGER_DMG 300 // minimum amount a 'trigger' / drown must do before counted as a death action +#define MIN_DC_FALL_DMG 175 // minimum amount of fall damage counts as death-falling for a deathcharge +#define WEIRD_FLOW_THRESH 900.0 // -9999 seems to be break flow.. but meh +#define MIN_FLOWDROPHEIGHT 350.0 // minimum height a survivor has to have dropped before a WEIRD_FLOW value is treated as a DC spot +#define MIN_DC_RECHECK_DMG 100 // minimum damage from map to have taken on first check, to warrant recheck + +#define HOP_ACCEL_THRESH 0.01 // bhop speed increase must be higher than this for it to count as part of a hop streak + +#define ZC_SMOKER 1 +#define ZC_BOOMER 2 +#define ZC_HUNTER 3 +#define ZC_JOCKEY 5 +#define ZC_CHARGER 6 +#define ZC_TANK 8 +#define HITGROUP_HEAD 1 + +#define DMG_CRUSH (1 << 0) // crushed by falling or moving object. +#define DMG_BULLET (1 << 1) // shot +#define DMG_SLASH (1 << 2) // cut, clawed, stabbed +#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt +#define DMG_BUCKSHOT (1 << 29) // not quite a bullet. Little, rounder, different. + +#define DMGARRAYEXT 7 // MAXPLAYERS+# -- extra indices in witch_dmg_array + 1 + +#define CUT_SHOVED 1 // smoker got shoved +#define CUT_SHOVEDSURV 2 // survivor got shoved +#define CUT_KILL 3 // reason for tongue break (release_type) +#define CUT_SLASH 4 // this is used for others shoving a survivor free too, don't trust .. it involves tongue damage? + +#define VICFLG_CARRIED (1 << 0) // was the one that the charger carried (not impacted) +#define VICFLG_FALL (1 << 1) // flags stored per charge victim, to check for deathchargeroony -- fallen +#define VICFLG_DROWN (1 << 2) // drowned +#define VICFLG_HURTLOTS (1 << 3) // whether the victim was hurt by 400 dmg+ at once +#define VICFLG_TRIGGER (1 << 4) // killed by trigger_hurt +#define VICFLG_AIRDEATH (1 << 5) // died before they hit the ground (impact check) +#define VICFLG_KILLEDBYOTHER (1 << 6) // if the survivor was killed by an SI other than the charger +#define VICFLG_WEIRDFLOW (1 << 7) // when survivors get out of the map and such +#define VICFLG_WEIRDFLOWDONE (1 << 8) // checked, don't recheck for this + +#define REP_SKEET (1 << 0) +#define REP_HURTSKEET (1 << 1) +#define REP_LEVEL (1 << 2) +#define REP_HURTLEVEL (1 << 3) +#define REP_CROWN (1 << 4) +#define REP_DRAWCROWN (1 << 5) +#define REP_TONGUECUT (1 << 6) +#define REP_SELFCLEAR (1 << 7) +#define REP_SELFCLEARSHOVE (1 << 8) +#define REP_ROCKSKEET (1 << 9) +#define REP_DEADSTOP (1 << 10) +#define REP_POP (1 << 11) +#define REP_SHOVE (1 << 12) +#define REP_HUNTERDP (1 << 13) +#define REP_JOCKEYDP (1 << 14) +#define REP_DEATHCHARGE (1 << 15) +#define REP_DC_ASSIST (1 << 16) +#define REP_INSTACLEAR (1 << 17) // 131072 +#define REP_BHOPSTREAK (1 << 18) // 262144 +#define REP_CARALARM (1 << 19) // 524288 + +#define REP_DEFAULT "581685" // (REP_SKEET | REP_LEVEL | REP_CROWN | REP_DRAWCROWN | REP_HUNTERDP | REP_JOCKEYDP | REP_DEATHCHARGE | REP_CARALARM) + // 1 4 16 32 8192 16384 32768 65536 (122933 with ASSIST, 57397 without); 131072 for instaclears + 524288 for car alarm + + +// trie values: weapon type +enum strWeaponType +{ + WPTYPE_SNIPER, + WPTYPE_MAGNUM, + WPTYPE_GL +}; + +// trie values: OnEntityCreated classname +enum strOEC +{ + OEC_WITCH, + OEC_TANKROCK, + OEC_TRIGGER, + OEC_CARALARM, + OEC_CARGLASS +}; + +// trie values: special abilities +enum strAbility +{ + ABL_HUNTERLUNGE, + ABL_ROCKTHROW +}; + +enum +{ + rckDamage, + rckTank, + rckSkeeter, + strRockData +}; + +// witch array entries (maxplayers+index) +enum +{ + WTCH_NONE, + WTCH_HEALTH, + WTCH_GOTSLASH, + WTCH_STARTLED, + WTCH_CROWNER, + WTCH_CROWNSHOT, + WTCH_CROWNTYPE, + strWitchArray +}; + +enum +{ + CALARM_UNKNOWN, + CALARM_HIT, + CALARM_TOUCHED, + CALARM_EXPLOSION, + CALARM_BOOMER, + enAlarmReasons +}; + +new const String: g_csSIClassName[][] = +{ + "", + "smoker", + "boomer", + "hunter", + "spitter", + "jockey", + "charger", + "witch", + "tank" +}; + +new bool: g_bLateLoad = false; + +new Handle: g_hForwardSkeet = INVALID_HANDLE; +new Handle: g_hForwardSkeetHurt = INVALID_HANDLE; +new Handle: g_hForwardSkeetMelee = INVALID_HANDLE; +new Handle: g_hForwardSkeetMeleeHurt = INVALID_HANDLE; +new Handle: g_hForwardSkeetSniper = INVALID_HANDLE; +new Handle: g_hForwardSkeetSniperHurt = INVALID_HANDLE; +new Handle: g_hForwardSkeetGL = INVALID_HANDLE; +new Handle: g_hForwardHunterDeadstop = INVALID_HANDLE; +new Handle: g_hForwardSIShove = INVALID_HANDLE; +new Handle: g_hForwardBoomerPop = INVALID_HANDLE; +new Handle: g_hForwardLevel = INVALID_HANDLE; +new Handle: g_hForwardLevelHurt = INVALID_HANDLE; +new Handle: g_hForwardCrown = INVALID_HANDLE; +new Handle: g_hForwardDrawCrown = INVALID_HANDLE; +new Handle: g_hForwardTongueCut = INVALID_HANDLE; +new Handle: g_hForwardSmokerSelfClear = INVALID_HANDLE; +new Handle: g_hForwardRockSkeeted = INVALID_HANDLE; +new Handle: g_hForwardRockEaten = INVALID_HANDLE; +new Handle: g_hForwardHunterDP = INVALID_HANDLE; +new Handle: g_hForwardJockeyDP = INVALID_HANDLE; +new Handle: g_hForwardDeathCharge = INVALID_HANDLE; +new Handle: g_hForwardClear = INVALID_HANDLE; +new Handle: g_hForwardVomitLanded = INVALID_HANDLE; +new Handle: g_hForwardBHopStreak = INVALID_HANDLE; +new Handle: g_hForwardAlarmTriggered = INVALID_HANDLE; + +new Handle: g_hTrieWeapons = INVALID_HANDLE; // weapon check +new Handle: g_hTrieEntityCreated = INVALID_HANDLE; // getting classname of entity created +new Handle: g_hTrieAbility = INVALID_HANDLE; // ability check +new Handle: g_hWitchTrie = INVALID_HANDLE; // witch tracking (Crox) +new Handle: g_hRockTrie = INVALID_HANDLE; // tank rock tracking +new Handle: g_hCarTrie = INVALID_HANDLE; // car alarm tracking + +// all SI / pinners +new Float: g_fSpawnTime [MAXPLAYERS + 1]; // time the SI spawned up +new Float: g_fPinTime [MAXPLAYERS + 1][2]; // time the SI pinned a target: 0 = start of pin (tongue pull, charger carry); 1 = carry end / tongue reigned in +new g_iSpecialVictim [MAXPLAYERS + 1]; // current victim (set in traceattack, so we can check on death) + +// hunters: skeets/pounces +new g_iHunterShotDmgTeam [MAXPLAYERS + 1]; // counting shotgun blast damage for hunter, counting entire survivor team's damage +new g_iHunterShotDmg [MAXPLAYERS + 1][MAXPLAYERS + 1]; // counting shotgun blast damage for hunter / skeeter combo +new Float: g_fHunterShotStart [MAXPLAYERS + 1][MAXPLAYERS + 1]; // when the last shotgun blast on hunter started (if at any time) by an attacker +new Float: g_fHunterTracePouncing [MAXPLAYERS + 1]; // time when the hunter was still pouncing (in traceattack) -- used to detect pouncing status +new Float: g_fHunterLastShot [MAXPLAYERS + 1]; // when the last shotgun damage was done (by anyone) on a hunter +new g_iHunterLastHealth [MAXPLAYERS + 1]; // last time hunter took any damage, how much health did it have left? +new g_iHunterOverkill [MAXPLAYERS + 1]; // how much more damage a hunter would've taken if it wasn't already dead +new bool: g_bHunterKilledPouncing [MAXPLAYERS + 1]; // whether the hunter was killed when actually pouncing +new g_iPounceDamage [MAXPLAYERS + 1]; // how much damage on last 'highpounce' done +new Float: g_fPouncePosition [MAXPLAYERS + 1][3]; // position that a hunter (jockey?) pounced from (or charger started his carry) + +// deadstops +new Float: g_fVictimLastShove [MAXPLAYERS + 1][MAXPLAYERS + 1]; // when was the player shoved last by attacker? (to prevent doubles) + +// levels / charges +new g_iChargerHealth [MAXPLAYERS + 1]; // how much health the charger had the last time it was seen taking damage +new Float: g_fChargeTime [MAXPLAYERS + 1]; // time the charger's charge last started, or if victim, when impact started +new g_iChargeVictim [MAXPLAYERS + 1]; // who got charged +new Float: g_fChargeVictimPos [MAXPLAYERS + 1][3]; // location of each survivor when it got hit by the charger +new g_iVictimCharger [MAXPLAYERS + 1]; // for a victim, by whom they got charge(impacted) +new g_iVictimFlags [MAXPLAYERS + 1]; // flags stored per charge victim: VICFLAGS_ +new g_iVictimMapDmg [MAXPLAYERS + 1]; // for a victim, how much the cumulative map damage is so far (trigger hurt / drowning) + +// pops +new bool: g_bBoomerHitSomebody [MAXPLAYERS + 1]; // false if boomer didn't puke/exploded on anybody +new g_iBoomerGotShoved [MAXPLAYERS + 1]; // count boomer was shoved at any point +new g_iBoomerVomitHits [MAXPLAYERS + 1]; // how many booms in one vomit so far + +// crowns +new Float: g_fWitchShotStart [MAXPLAYERS + 1]; // when the last shotgun blast from a survivor started (on any witch) + +// smoker clears +new bool: g_bSmokerClearCheck [MAXPLAYERS + 1]; // [smoker] smoker dies and this is set, it's a self-clear if g_iSmokerVictim is the killer +new g_iSmokerVictim [MAXPLAYERS + 1]; // [smoker] the one that's being pulled +new g_iSmokerVictimDamage [MAXPLAYERS + 1]; // [smoker] amount of damage done to a smoker by the one he pulled +new bool: g_bSmokerShoved [MAXPLAYERS + 1]; // [smoker] set if the victim of a pull manages to shove the smoker + +// rocks +new g_iTankRock [MAXPLAYERS + 1]; // rock entity per tank +new g_iRocksBeingThrown [10]; // 10 tanks max simultanously throwing rocks should be ok (this stores the tank client) +new g_iRocksBeingThrownCount = 0; // so we can do a push/pop type check for who is throwing a created rock + +// hops +new bool: g_bIsHopping [MAXPLAYERS + 1]; // currently in a hop streak +new bool: g_bHopCheck [MAXPLAYERS + 1]; // flag to check whether a hopstreak has ended (if on ground for too long.. ends) +new g_iHops [MAXPLAYERS + 1]; // amount of hops in streak +new Float: g_fLastHop [MAXPLAYERS + 1][3]; // velocity vector of last jump +new Float: g_fHopTopVelocity [MAXPLAYERS + 1]; // maximum velocity in hopping streak + +// alarms +new Float: g_fLastCarAlarm = 0.0; // time when last car alarm went off +new g_iLastCarAlarmReason [MAXPLAYERS + 1]; // what this survivor did to set the last alarm off +new g_iLastCarAlarmBoomer; // if a boomer triggered an alarm, remember it + +// cvars +new Handle: g_hCvarReport = INVALID_HANDLE; // cvar whether to report at all +new Handle: g_hCvarReportFlags = INVALID_HANDLE; // cvar what to report + +new Handle: g_hCvarAllowMelee = INVALID_HANDLE; // cvar whether to count melee skeets +new Handle: g_hCvarAllowSniper = INVALID_HANDLE; // cvar whether to count sniper headshot skeets +new Handle: g_hCvarAllowGLSkeet = INVALID_HANDLE; // cvar whether to count direct hit GL skeets +new Handle: g_hCvarDrawCrownThresh = INVALID_HANDLE; // cvar damage in final shot for drawcrown-req. +new Handle: g_hCvarSelfClearThresh = INVALID_HANDLE; // cvar damage while self-clearing from smokers +new Handle: g_hCvarHunterDPThresh = INVALID_HANDLE; // cvar damage for hunter highpounce +new Handle: g_hCvarJockeyDPThresh = INVALID_HANDLE; // cvar distance for jockey highpounce +new Handle: g_hCvarHideFakeDamage = INVALID_HANDLE; // cvar damage while self-clearing from smokers +new Handle: g_hCvarDeathChargeHeight = INVALID_HANDLE; // cvar how high a charger must have come in order for a DC to count +new Handle: g_hCvarInstaTime = INVALID_HANDLE; // cvar clear within this time or lower for instaclear +new Handle: g_hCvarBHopMinStreak = INVALID_HANDLE; // cvar this many hops in a row+ = streak +new Handle: g_hCvarBHopMinInitSpeed = INVALID_HANDLE; // cvar lower than this and the first jump won't be seen as the start of a streak +new Handle: g_hCvarBHopContSpeed = INVALID_HANDLE; // cvar + +new Handle: g_hCvarPounceInterrupt = INVALID_HANDLE; // z_pounce_damage_interrupt +new g_iPounceInterrupt = 150; +new Handle: g_hCvarChargerHealth = INVALID_HANDLE; // z_charger_health +new Handle: g_hCvarWitchHealth = INVALID_HANDLE; // z_witch_health +new Handle: g_hCvarMaxPounceDistance = INVALID_HANDLE; // z_pounce_damage_range_max +new Handle: g_hCvarMinPounceDistance = INVALID_HANDLE; // z_pounce_damage_range_min +new Handle: g_hCvarMaxPounceDamage = INVALID_HANDLE; // z_hunter_max_pounce_bonus_damage; + + +/* + Reports: + -------- + Damage shown is damage done in the last shot/slash. So for crowns, this means + that the 'damage' value is one shotgun blast + + + Quirks: + ------- + Does not report people cutting smoker tongues that target players other + than themselves. Could be done, but would require (too much) tracking. + + Actual damage done, on Hunter DPs, is low when the survivor gets incapped + by (a fraction of) the total pounce damage. + + + Fake Damage + ----------- + Hiding of fake damage has the following consequences: + - Drawcrowns are less likely to be registered: if a witch takes too + much chip before the crowning shot, the final shot will be considered + as doing too little damage for a crown (even if it would have been a crown + had the witch had more health). + - Charger levels are harder to get on chipped chargers. Any charger that + has taken (600 - 390 =) 210 damage or more cannot be leveled (even if + the melee swing would've killed the charger (1559 damage) if it'd have + had full health). + I strongly recommend leaving fakedamage visible: it will offer more feedback on + the survivor's action and reward survivors doing (what would be) full crowns and + levels on chipped targets. + + + To Do + ----- + + - fix: tank rock owner is not reliable for the RockEaten forward + - fix: tank rock skeets still unreliable detection (often triggers a 'skeet' when actually landed on someone) + + - fix: apparently some HR4 cars generate car alarm messages when shot, even when no alarm goes off + (combination with car equalize plugin?) + - see below: the single hook might also fix this.. -- if not, hook for sound + - do a hookoutput on prop_car_alarm's and use that to track the actual alarm + going off (might help in the case 2 alarms go off exactly at the same time?) + - fix: double prints on car alarms (sometimes? epi + m60) + + - fix: sometimes instaclear reports double for single clear (0.16s / 0.19s) epi saw this, was for hunter + - fix: deadstops and m2s don't always register .. no idea why.. + - fix: sometimes a (first?) round doesn't work for skeet detection.. no hurt/full skeets are reported or counted + + - make forwards fire for every potential action, + - include the relevant values, so other plugins can decide for themselves what to consider it + + - test chargers getting dislodged with boomer pops? + + - add commonhop check + - add deathcharge assist check + - smoker + - jockey + + - add deathcharge coordinates for some areas + - DT4 next to saferoom + - DA1 near the lower roof, on sidewalk next to fence (no hurttrigger there) + - DA2 next to crane roof to the right of window + DA2 charge down into start area, after everyone's jumped the fence + + - count rock hits even if they do no damage [epi request] + - sir + - make separate teamskeet forward, with (for now, up to) 4 skeeters + the damage each did + - xan + - add detection/display of unsuccesful witch crowns (witch death + info) + + detect... + - ? add jockey deadstops (and change forward to reflect type) + - ? speedcrown detection? + - ? spit-on-cap detection + + --- + done: + - applied sanity bounds to calculated damage for hunter dps + - removed tank's name from rock skeet print + - 300+ speed hops are considered hops even if no increase +*/ + +public Plugin:myinfo = +{ + name = "Skill Detection (skeets, crowns, levels)", + author = "Tabun", + description = "Detects and reports skeets, crowns, levels, highpounces, etc.", + version = PLUGIN_VERSION, + url = "https://github.com/Tabbernaut/L4D2-Plugins" +} + +public APLRes:AskPluginLoad2(Handle:myself, bool:late, String:error[], err_max) +{ + RegPluginLibrary("skill_detect"); + + g_hForwardSkeet = CreateGlobalForward("OnSkeet", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardSkeetHurt = CreateGlobalForward("OnSkeetHurt", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardSkeetMelee = CreateGlobalForward("OnSkeetMelee", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardSkeetMeleeHurt = CreateGlobalForward("OnSkeetMeleeHurt", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardSkeetSniper = CreateGlobalForward("OnSkeetSniper", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardSkeetSniperHurt = CreateGlobalForward("OnSkeetSniperHurt", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardSkeetGL = CreateGlobalForward("OnSkeetGL", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardSIShove = CreateGlobalForward("OnSpecialShoved", ET_Ignore, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardHunterDeadstop = CreateGlobalForward("OnHunterDeadstop", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardBoomerPop = CreateGlobalForward("OnBoomerPop", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Float ); + g_hForwardLevel = CreateGlobalForward("OnChargerLevel", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardLevelHurt = CreateGlobalForward("OnChargerLevelHurt", ET_Ignore, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardCrown = CreateGlobalForward("OnWitchCrown", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardDrawCrown = CreateGlobalForward("OnWitchDrawCrown", ET_Ignore, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardTongueCut = CreateGlobalForward("OnTongueCut", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardSmokerSelfClear = CreateGlobalForward("OnSmokerSelfClear", ET_Ignore, Param_Cell, Param_Cell, Param_Cell ); + g_hForwardRockSkeeted = CreateGlobalForward("OnTankRockSkeeted", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardRockEaten = CreateGlobalForward("OnTankRockEaten", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardHunterDP = CreateGlobalForward("OnHunterHighPounce", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Float, Param_Float, Param_Cell, Param_Cell ); + g_hForwardJockeyDP = CreateGlobalForward("OnJockeyHighPounce", ET_Ignore, Param_Cell, Param_Cell, Param_Float, Param_Cell ); + g_hForwardDeathCharge = CreateGlobalForward("OnDeathCharge", ET_Ignore, Param_Cell, Param_Cell, Param_Float, Param_Float, Param_Cell ); + g_hForwardClear = CreateGlobalForward("OnSpecialClear", ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell, Param_Float, Param_Float, Param_Cell ); + g_hForwardVomitLanded = CreateGlobalForward("OnBoomerVomitLanded", ET_Ignore, Param_Cell, Param_Cell ); + g_hForwardBHopStreak = CreateGlobalForward("OnBunnyHopStreak", ET_Ignore, Param_Cell, Param_Cell, Param_Float ); + g_hForwardAlarmTriggered = CreateGlobalForward("OnCarAlarmTriggered", ET_Ignore, Param_Cell, Param_Cell, Param_Cell ); + g_bLateLoad = late; + + return APLRes_Success; +} + +public OnPluginStart() +{ + // hooks + HookEvent("round_start", Event_RoundStart, EventHookMode_PostNoCopy); + HookEvent("scavenge_round_start", Event_RoundStart, EventHookMode_PostNoCopy); + HookEvent("round_end", Event_RoundEnd, EventHookMode_PostNoCopy); + + HookEvent("player_spawn", Event_PlayerSpawn, EventHookMode_Post); + HookEvent("player_hurt", Event_PlayerHurt, EventHookMode_Pre); + HookEvent("player_death", Event_PlayerDeath, EventHookMode_Pre); + HookEvent("ability_use", Event_AbilityUse, EventHookMode_Post); + HookEvent("lunge_pounce", Event_LungePounce, EventHookMode_Post); + HookEvent("player_shoved", Event_PlayerShoved, EventHookMode_Post); + HookEvent("player_jump", Event_PlayerJumped, EventHookMode_Post); + HookEvent("player_jump_apex", Event_PlayerJumpApex, EventHookMode_Post); + + HookEvent("player_now_it", Event_PlayerBoomed, EventHookMode_Post); + HookEvent("boomer_exploded", Event_BoomerExploded, EventHookMode_Post); + + //HookEvent("infected_hurt", Event_InfectedHurt, EventHookMode_Post); + HookEvent("witch_spawn", Event_WitchSpawned, EventHookMode_Post); + HookEvent("witch_killed", Event_WitchKilled, EventHookMode_Post); + HookEvent("witch_harasser_set", Event_WitchHarasserSet, EventHookMode_Post); + + HookEvent("tongue_grab", Event_TongueGrab, EventHookMode_Post); + HookEvent("tongue_pull_stopped", Event_TonguePullStopped, EventHookMode_Post); + HookEvent("choke_start", Event_ChokeStart, EventHookMode_Post); + HookEvent("choke_stopped", Event_ChokeStop, EventHookMode_Post); + HookEvent("jockey_ride", Event_JockeyRide, EventHookMode_Post); + HookEvent("charger_carry_start", Event_ChargeCarryStart, EventHookMode_Post); + HookEvent("charger_carry_end", Event_ChargeCarryEnd, EventHookMode_Post); + HookEvent("charger_impact", Event_ChargeImpact, EventHookMode_Post); + HookEvent("charger_pummel_start", Event_ChargePummelStart, EventHookMode_Post); + + HookEvent("player_incapacitated_start", Event_IncapStart, EventHookMode_Post); + HookEvent("triggered_car_alarm", Event_CarAlarmGoesOff, EventHookMode_Post); + + + // version cvar + CreateConVar( "sm_skill_detect_version", PLUGIN_VERSION, "Skill detect plugin version.", FCVAR_NONE|FCVAR_NOTIFY|FCVAR_REPLICATED|FCVAR_DONTRECORD ); + + // cvars: config + + g_hCvarReport = CreateConVar( "sm_skill_report_enable" , "0", "Whether to report in chat (see sm_skill_report_flags).", FCVAR_NONE, true, 0.0, true, 1.0 ); + g_hCvarReportFlags = CreateConVar( "sm_skill_report_flags" , REP_DEFAULT, "What to report skeets in chat (bitflags: 1,2:skeets/hurt; 4,8:level/chip; 16,32:crown/draw; 64,128:cut/selfclear, ... ).", FCVAR_NONE, true, 0.0 ); + + g_hCvarAllowMelee = CreateConVar( "sm_skill_skeet_allowmelee", "1", "Whether to count/forward melee skeets.", FCVAR_NONE, true, 0.0, true, 1.0 ); + g_hCvarAllowSniper = CreateConVar( "sm_skill_skeet_allowsniper", "1", "Whether to count/forward sniper/magnum headshots as skeets.", FCVAR_NONE, true, 0.0, true, 1.0 ); + g_hCvarAllowGLSkeet = CreateConVar( "sm_skill_skeet_allowgl", "1", "Whether to count/forward direct GL hits as skeets.", FCVAR_NONE, true, 0.0, true, 1.0 ); + g_hCvarDrawCrownThresh = CreateConVar( "sm_skill_drawcrown_damage", "500", "How much damage a survivor must at least do in the final shot for it to count as a drawcrown.", FCVAR_NONE, true, 0.0, false ); + g_hCvarSelfClearThresh = CreateConVar( "sm_skill_selfclear_damage", "200", "How much damage a survivor must at least do to a smoker for him to count as self-clearing.", FCVAR_NONE, true, 0.0, false ); + g_hCvarHunterDPThresh = CreateConVar( "sm_skill_hunterdp_height", "400", "Minimum height of hunter pounce for it to count as a DP.", FCVAR_NONE, true, 0.0, false ); + g_hCvarJockeyDPThresh = CreateConVar( "sm_skill_jockeydp_height", "300", "How much height distance a jockey must make for his 'DP' to count as a reportable highpounce.", FCVAR_NONE, true, 0.0, false ); + g_hCvarHideFakeDamage = CreateConVar( "sm_skill_hidefakedamage", "0", "If set, any damage done that exceeds the health of a victim is hidden in reports.", FCVAR_NONE, true, 0.0, true, 1.0 ); + g_hCvarDeathChargeHeight = CreateConVar("sm_skill_deathcharge_height","400", "How much height distance a charger must take its victim for a deathcharge to be reported.", FCVAR_NONE, true, 0.0, false ); + g_hCvarInstaTime = CreateConVar( "sm_skill_instaclear_time", "0.75", "A clear within this time (in seconds) counts as an insta-clear.", FCVAR_NONE, true, 0.0, false ); + g_hCvarBHopMinStreak = CreateConVar( "sm_skill_bhopstreak", "3", "The lowest bunnyhop streak that will be reported.", FCVAR_NONE, true, 0.0, false ); + g_hCvarBHopMinInitSpeed = CreateConVar( "sm_skill_bhopinitspeed", "150", "The minimal speed of the first jump of a bunnyhopstreak (0 to allow 'hops' from standstill).", FCVAR_NONE, true, 0.0, false ); + g_hCvarBHopContSpeed = CreateConVar( "sm_skill_bhopkeepspeed", "300", "The minimal speed at which hops are considered succesful even if not speed increase is made.", FCVAR_NONE, true, 0.0, false ); + + // cvars: built in + g_hCvarPounceInterrupt = FindConVar("z_pounce_damage_interrupt"); + HookConVarChange(g_hCvarPounceInterrupt, CvarChange_PounceInterrupt); + g_iPounceInterrupt = GetConVarInt(g_hCvarPounceInterrupt); + + g_hCvarChargerHealth = FindConVar("z_charger_health"); + g_hCvarWitchHealth = FindConVar("z_witch_health"); + + g_hCvarMaxPounceDistance = FindConVar("z_pounce_damage_range_max"); + g_hCvarMinPounceDistance = FindConVar("z_pounce_damage_range_min"); + g_hCvarMaxPounceDamage = FindConVar("z_hunter_max_pounce_bonus_damage"); + if ( g_hCvarMaxPounceDistance == INVALID_HANDLE ) { g_hCvarMaxPounceDistance = CreateConVar( "z_pounce_damage_range_max", "1000.0", "Not available on this server, added by l4d2_skill_detect.", FCVAR_NONE, true, 0.0, false ); } + if ( g_hCvarMinPounceDistance == INVALID_HANDLE ) { g_hCvarMinPounceDistance = CreateConVar( "z_pounce_damage_range_min", "300.0", "Not available on this server, added by l4d2_skill_detect.", FCVAR_NONE, true, 0.0, false ); } + if ( g_hCvarMaxPounceDamage == INVALID_HANDLE ) { g_hCvarMaxPounceDamage = CreateConVar( "z_hunter_max_pounce_bonus_damage", "49", "Not available on this server, added by l4d2_skill_detect.", FCVAR_NONE, true, 0.0, false ); } + + + // tries + g_hTrieWeapons = CreateTrie(); + SetTrieValue(g_hTrieWeapons, "hunting_rifle", WPTYPE_SNIPER); + SetTrieValue(g_hTrieWeapons, "sniper_military", WPTYPE_SNIPER); + SetTrieValue(g_hTrieWeapons, "sniper_awp", WPTYPE_SNIPER); + SetTrieValue(g_hTrieWeapons, "sniper_scout", WPTYPE_SNIPER); + SetTrieValue(g_hTrieWeapons, "pistol_magnum", WPTYPE_MAGNUM); + SetTrieValue(g_hTrieWeapons, "grenade_launcher_projectile", WPTYPE_GL); + + g_hTrieEntityCreated = CreateTrie(); + SetTrieValue(g_hTrieEntityCreated, "tank_rock", OEC_TANKROCK); + SetTrieValue(g_hTrieEntityCreated, "witch", OEC_WITCH); + SetTrieValue(g_hTrieEntityCreated, "trigger_hurt", OEC_TRIGGER); + SetTrieValue(g_hTrieEntityCreated, "prop_car_alarm", OEC_CARALARM); + SetTrieValue(g_hTrieEntityCreated, "prop_car_glass", OEC_CARGLASS); + + g_hTrieAbility = CreateTrie(); + SetTrieValue(g_hTrieAbility, "ability_lunge", ABL_HUNTERLUNGE); + SetTrieValue(g_hTrieAbility, "ability_throw", ABL_ROCKTHROW); + + g_hWitchTrie = CreateTrie(); + g_hRockTrie = CreateTrie(); + g_hCarTrie = CreateTrie(); + + if ( g_bLateLoad ) + { + for ( new client = 1; client <= MaxClients; client++ ) + { + if ( IS_VALID_INGAME(client) ) + { + SDKHook( client, SDKHook_OnTakeDamage, OnTakeDamageByWitch ); + } + } + } + + AutoExecConfig(true, "l4d2_skill_detect"); +} + +public CvarChange_PounceInterrupt( Handle:convar, const String:oldValue[], const String:newValue[] ) +{ + g_iPounceInterrupt = GetConVarInt(convar); +} + +public OnClientPostAdminCheck(client) +{ + SDKHook(client, SDKHook_OnTakeDamage, OnTakeDamageByWitch); +} + +public OnClientDisconnect(client) +{ + SDKUnhook(client, SDKHook_OnTakeDamage, OnTakeDamageByWitch); +} + + + +/* + Tracking + -------- +*/ + +public Action: Event_RoundStart( Handle:event, const String:name[], bool:dontBroadcast ) +{ + g_iRocksBeingThrownCount = 0; + + for ( new i = 1; i <= MaxClients; i++ ) + { + g_bIsHopping[i] = false; + + for ( new j = 1; j <= MaxClients; j++ ) + { + g_fVictimLastShove[i][j] = 0.0; + } + } +} + +public Action: Event_RoundEnd( Handle:event, const String:name[], bool:dontBroadcast ) +{ + // clean trie, new cars will be created + ClearTrie(g_hCarTrie); +} + +public Action: Event_PlayerHurt( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new victim = GetClientOfUserId(GetEventInt(event, "userid")); + new attacker = GetClientOfUserId(GetEventInt(event, "attacker")); + new zClass; + + new damage = GetEventInt(event, "dmg_health"); + new damagetype = GetEventInt(event, "type"); + + if ( IS_VALID_INFECTED(victim) ) + { + zClass = GetEntProp(victim, Prop_Send, "m_zombieClass"); + new health = GetEventInt(event, "health"); + new hitgroup = GetEventInt(event, "hitgroup"); + + if ( damage < 1 ) { return Plugin_Continue; } + + switch ( zClass ) + { + case ZC_HUNTER: + { + // if it's not a survivor doing the work, only get the remaining health + if ( !IS_VALID_SURVIVOR(attacker) ) + { + g_iHunterLastHealth[victim] = health; + return Plugin_Continue; + } + + // if the damage done is greater than the health we know the hunter to have remaining, reduce the damage done + if ( g_iHunterLastHealth[victim] > 0 && damage > g_iHunterLastHealth[victim] ) + { + damage = g_iHunterLastHealth[victim]; + g_iHunterOverkill[victim] = g_iHunterLastHealth[victim] - damage; + g_iHunterLastHealth[victim] = 0; + } + + /* + handle old shotgun blast: too long ago? not the same blast + */ + if ( g_iHunterShotDmg[victim][attacker] > 0 && (GetGameTime() - g_fHunterShotStart[victim][attacker]) > SHOTGUN_BLAST_TIME ) + { + g_fHunterShotStart[victim][attacker] = 0.0; + } + + /* + m_isAttemptingToPounce is set to 0 here if the hunter is actually skeeted + so the g_fHunterTracePouncing[victim] value indicates when the hunter was last seen pouncing in traceattack + (should be DIRECTLY before this event for every shot). + */ + new bool: isPouncing = bool:( + GetEntProp(victim, Prop_Send, "m_isAttemptingToPounce") || + g_fHunterTracePouncing[victim] != 0.0 && ( GetGameTime() - g_fHunterTracePouncing[victim] ) < 0.001 + ); + + if ( isPouncing ) + { + if ( damagetype & DMG_BUCKSHOT ) + { + // first pellet hit? + if ( g_fHunterShotStart[victim][attacker] == 0.0 ) + { + // new shotgun blast + g_fHunterShotStart[victim][attacker] = GetGameTime(); + g_fHunterLastShot[victim] = g_fHunterShotStart[victim][attacker]; + } + g_iHunterShotDmg[victim][attacker] += damage; + g_iHunterShotDmgTeam[victim] += damage; + + if ( health == 0 ) { + g_bHunterKilledPouncing[victim] = true; + } + } + else if ( damagetype & (DMG_BLAST | DMG_PLASMA) && health == 0 ) + { + // direct GL hit? + /* + direct hit is DMG_BLAST | DMG_PLASMA + indirect hit is DMG_AIRBOAT + */ + + decl String: weaponB[32]; + new strWeaponType: weaponTypeB; + GetEventString(event, "weapon", weaponB, sizeof(weaponB)); + + if ( GetTrieValue(g_hTrieWeapons, weaponB, weaponTypeB) && weaponTypeB == WPTYPE_GL ) + { + if ( GetConVarBool(g_hCvarAllowGLSkeet) ) { + HandleSkeet( attacker, victim, false, false, true ); + } + } + } + else if ( damagetype & DMG_BULLET && + health == 0 && + hitgroup == HITGROUP_HEAD + ) { + // headshot with bullet based weapon (only single shots) -- only snipers + decl String: weaponA[32]; + new strWeaponType: weaponTypeA; + GetEventString(event, "weapon", weaponA, sizeof(weaponA)); + + if ( GetTrieValue(g_hTrieWeapons, weaponA, weaponTypeA) && + ( weaponTypeA == WPTYPE_SNIPER || + weaponTypeA == WPTYPE_MAGNUM ) + ) { + if ( damage >= g_iPounceInterrupt ) + { + g_iHunterShotDmgTeam[victim] = 0; + if ( GetConVarBool(g_hCvarAllowSniper) ) { + HandleSkeet( attacker, victim, false, true ); + } + ResetHunter(victim); + } + else + { + // hurt skeet + if ( GetConVarBool(g_hCvarAllowSniper) ) { + HandleNonSkeet( attacker, victim, damage, ( g_iHunterOverkill[victim] + g_iHunterShotDmgTeam[victim] > g_iPounceInterrupt ), false, true ); + } + ResetHunter(victim); + } + } + + // already handled hurt skeet above + //g_bHunterKilledPouncing[victim] = true; + } + else if ( damagetype & DMG_SLASH || damagetype & DMG_CLUB ) + { + // melee skeet + if ( damage >= g_iPounceInterrupt ) + { + g_iHunterShotDmgTeam[victim] = 0; + if ( GetConVarBool(g_hCvarAllowMelee) ) { + HandleSkeet( attacker, victim, true ); + } + ResetHunter(victim); + //g_bHunterKilledPouncing[victim] = true; + } + else if ( health == 0 ) + { + // hurt skeet (always overkill) + if ( GetConVarBool(g_hCvarAllowMelee) ) { + HandleNonSkeet( attacker, victim, damage, true, true, false ); + } + ResetHunter(victim); + } + } + } + else if ( health == 0 ) + { + // make sure we don't mistake non-pouncing hunters as 'not skeeted'-warnable + g_bHunterKilledPouncing[victim] = false; + } + + // store last health seen for next damage event + g_iHunterLastHealth[victim] = health; + } + + case ZC_CHARGER: + { + if ( IS_VALID_SURVIVOR(attacker) ) + { + // check for levels + if ( health == 0 && ( damagetype & DMG_CLUB || damagetype & DMG_SLASH ) ) + { + new iChargeHealth = GetConVarInt(g_hCvarChargerHealth); + new abilityEnt = GetEntPropEnt( victim, Prop_Send, "m_customAbility" ); + if ( IsValidEntity(abilityEnt) && GetEntProp(abilityEnt, Prop_Send, "m_isCharging") ) + { + // fix fake damage? + if ( GetConVarBool(g_hCvarHideFakeDamage) ) + { + damage = iChargeHealth - g_iChargerHealth[victim]; + } + + // charger was killed, was it a full level? + if ( damage > (iChargeHealth * 0.65) ) { + HandleLevel( attacker, victim ); + } + else { + HandleLevelHurt( attacker, victim, damage ); + } + } + } + } + + // store health for next damage it takes + if ( health > 0 ) + { + g_iChargerHealth[victim] = health; + } + } + + case ZC_SMOKER: + { + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + g_iSmokerVictimDamage[victim] += damage; + } + + } + } + else if ( IS_VALID_INFECTED(attacker) ) + { + zClass = GetEntProp(attacker, Prop_Send, "m_zombieClass"); + + switch ( zClass ) + { + case ZC_HUNTER: + { + // a hunter pounce landing is DMG_CRUSH + if ( damagetype & DMG_CRUSH ) { + g_iPounceDamage[attacker] = damage; + } + } + + case ZC_TANK: + { + new String: weapon[10]; + GetEventString(event, "weapon", weapon, sizeof(weapon)); + + if ( StrEqual(weapon, "tank_rock") ) + { + // find rock entity through tank + if ( g_iTankRock[attacker] ) + { + // remember that the rock wasn't shot + decl String:rock_key[10]; + FormatEx(rock_key, sizeof(rock_key), "%x", g_iTankRock[attacker]); + new rock_array[3]; + rock_array[rckDamage] = -1; + SetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array), true); + } + + if ( IS_VALID_SURVIVOR(victim) ) + { + HandleRockEaten( attacker, victim ); + } + } + + return Plugin_Continue; + } + } + } + + // check for deathcharge flags + if ( IS_VALID_SURVIVOR(victim) ) + { + // debug + if ( damagetype & DMG_DROWN || damagetype & DMG_FALL ) { + g_iVictimMapDmg[victim] += damage; + } + + if ( damagetype & DMG_DROWN && damage >= MIN_DC_TRIGGER_DMG ) + { + g_iVictimFlags[victim] = g_iVictimFlags[victim] | VICFLG_HURTLOTS; + } + else if ( damagetype & DMG_FALL && damage >= MIN_DC_FALL_DMG ) + { + g_iVictimFlags[victim] = g_iVictimFlags[victim] | VICFLG_HURTLOTS; + } + } + + return Plugin_Continue; +} + +public Action: Event_PlayerSpawn( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId(GetEventInt(event, "userid")); + if ( !IS_VALID_INFECTED(client) ) { return Plugin_Continue; } + + new zClass = GetEntProp(client, Prop_Send, "m_zombieClass"); + + g_fSpawnTime[client] = GetGameTime(); + g_fPinTime[client][0] = 0.0; + g_fPinTime[client][1] = 0.0; + + switch ( zClass ) + { + case ZC_BOOMER: + { + g_bBoomerHitSomebody[client] = false; + g_iBoomerGotShoved[client] = 0; + } + case ZC_SMOKER: + { + g_bSmokerClearCheck[client] = false; + g_iSmokerVictim[client] = 0; + g_iSmokerVictimDamage[client] = 0; + } + case ZC_HUNTER: + { + SDKHook(client, SDKHook_TraceAttack, TraceAttack_Hunter); + + g_fPouncePosition[client][0] = 0.0; + g_fPouncePosition[client][1] = 0.0; + g_fPouncePosition[client][2] = 0.0; + } + case ZC_JOCKEY: + { + SDKHook(client, SDKHook_TraceAttack, TraceAttack_Jockey); + + g_fPouncePosition[client][0] = 0.0; + g_fPouncePosition[client][1] = 0.0; + g_fPouncePosition[client][2] = 0.0; + } + case ZC_CHARGER: + { + SDKHook(client, SDKHook_TraceAttack, TraceAttack_Charger); + + g_iChargerHealth[client] = GetConVarInt(g_hCvarChargerHealth); + } + } + + return Plugin_Continue; +} + +// player about to get incapped +public Action: Event_IncapStart( Handle:event, const String:name[], bool:dontBroadcast ) +{ + // test for deathcharges + + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + //new attacker = GetClientOfUserId( GetEventInt(event, "attacker") ); + new attackent = GetEventInt(event, "attackerentid"); + new dmgtype = GetEventInt(event, "type"); + + new String: classname[24]; + new strOEC: classnameOEC; + if ( IsValidEntity(attackent) ) { + GetEdictClassname(attackent, classname, sizeof(classname)); + if ( GetTrieValue(g_hTrieEntityCreated, classname, classnameOEC)) { + g_iVictimFlags[client] = g_iVictimFlags[client] | VICFLG_TRIGGER; + } + } + + new Float: flow = GetSurvivorDistance(client); + + //PrintDebug( 3, "Incap Pre on [%N]: attk: %i / %i (%s) - dmgtype: %i - flow: %.1f", client, attacker, attackent, classname, dmgtype, flow ); + + // drown is damage type + if ( dmgtype & DMG_DROWN ) + { + g_iVictimFlags[client] = g_iVictimFlags[client] | VICFLG_DROWN; + } + if ( flow < WEIRD_FLOW_THRESH ) + { + g_iVictimFlags[client] = g_iVictimFlags[client] | VICFLG_WEIRDFLOW; + } +} + +// trace attacks on hunters +public Action: TraceAttack_Hunter (victim, &attacker, &inflictor, &Float:damage, &damagetype, &ammotype, hitbox, hitgroup) +{ + // track pinning + g_iSpecialVictim[victim] = GetEntPropEnt(victim, Prop_Send, "m_pounceVictim"); + + if ( !IS_VALID_SURVIVOR(attacker) || !IsValidEdict(inflictor) ) { return; } + + // track flight + if ( GetEntProp(victim, Prop_Send, "m_isAttemptingToPounce") ) + { + g_fHunterTracePouncing[victim] = GetGameTime(); + } + else + { + g_fHunterTracePouncing[victim] = 0.0; + } +} +public Action: TraceAttack_Charger (victim, &attacker, &inflictor, &Float:damage, &damagetype, &ammotype, hitbox, hitgroup) +{ + // track pinning + new victimA = GetEntPropEnt(victim, Prop_Send, "m_carryVictim"); + if ( victimA != -1 ) { + g_iSpecialVictim[victim] = victimA; + } else { + g_iSpecialVictim[victim] = GetEntPropEnt(victim, Prop_Send, "m_pummelVictim"); + } + +} +public Action: TraceAttack_Jockey (victim, &attacker, &inflictor, &Float:damage, &damagetype, &ammotype, hitbox, hitgroup) +{ + // track pinning + g_iSpecialVictim[victim] = GetEntPropEnt(victim, Prop_Send, "m_jockeyVictim"); +} + +public Action: Event_PlayerDeath( Handle:hEvent, const String:name[], bool:dontBroadcast ) +{ + new victim = GetClientOfUserId( GetEventInt(hEvent, "userid") ); + new attacker = GetClientOfUserId( GetEventInt(hEvent, "attacker") ); + + if ( IS_VALID_INFECTED(victim) ) + { + new zClass = GetEntProp(victim, Prop_Send, "m_zombieClass"); + + switch ( zClass ) + { + case ZC_HUNTER: + { + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + if ( g_iHunterShotDmgTeam[victim] > 0 && g_bHunterKilledPouncing[victim] ) + { + // skeet? + if ( g_iHunterShotDmgTeam[victim] > g_iHunterShotDmg[victim][attacker] && + g_iHunterShotDmgTeam[victim] >= g_iPounceInterrupt + ) { + // team skeet + HandleSkeet( -2, victim ); + } + else if ( g_iHunterShotDmg[victim][attacker] >= g_iPounceInterrupt ) + { + // single player skeet + HandleSkeet( attacker, victim ); + } + else if ( g_iHunterOverkill[victim] > 0 ) + { + // overkill? might've been a skeet, if it wasn't on a hurt hunter (only for shotguns) + HandleNonSkeet( attacker, victim, g_iHunterShotDmgTeam[victim], ( g_iHunterOverkill[victim] + g_iHunterShotDmgTeam[victim] > g_iPounceInterrupt ) ); + } + else + { + // not a skeet at all + HandleNonSkeet( attacker, victim, g_iHunterShotDmg[victim][attacker] ); + } + } + else { + // check whether it was a clear + if ( g_iSpecialVictim[victim] > 0 ) + { + HandleClear( attacker, victim, g_iSpecialVictim[victim], + ZC_HUNTER, + ( GetGameTime() - g_fPinTime[victim][0]), + -1.0 + ); + } + } + + ResetHunter(victim); + } + + case ZC_SMOKER: + { + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + if ( g_bSmokerClearCheck[victim] && + g_iSmokerVictim[victim] == attacker && + g_iSmokerVictimDamage[victim] >= GetConVarInt(g_hCvarSelfClearThresh) + ) { + HandleSmokerSelfClear( attacker, victim ); + } + else + { + g_bSmokerClearCheck[victim] = false; + g_iSmokerVictim[victim] = 0; + } + } + + case ZC_JOCKEY: + { + // check whether it was a clear + if ( g_iSpecialVictim[victim] > 0 ) + { + HandleClear( attacker, victim, g_iSpecialVictim[victim], + ZC_JOCKEY, + ( GetGameTime() - g_fPinTime[victim][0]), + -1.0 + ); + } + } + + case ZC_CHARGER: + { + // is it someone carrying a survivor (that might be DC'd)? + // switch charge victim to 'impact' check (reset checktime) + if ( IS_VALID_INGAME(g_iChargeVictim[victim]) ) { + g_fChargeTime[ g_iChargeVictim[victim] ] = GetGameTime(); + } + + // check whether it was a clear + if ( g_iSpecialVictim[victim] > 0 ) + { + HandleClear( attacker, victim, g_iSpecialVictim[victim], + ZC_CHARGER, + (g_fPinTime[victim][1] > 0.0) ? ( GetGameTime() - g_fPinTime[victim][1]) : -1.0, + ( GetGameTime() - g_fPinTime[victim][0]) + ); + } + } + } + } + else if ( IS_VALID_SURVIVOR(victim) ) + { + // check for deathcharges + //new atkent = GetEventInt(hEvent, "attackerentid"); + new dmgtype = GetEventInt(hEvent, "type"); + + //PrintDebug( 3, "Died [%N]: attk: %i / %i - dmgtype: %i", victim, attacker, atkent, dmgtype ); + + if ( dmgtype & DMG_FALL) + { + g_iVictimFlags[victim] = g_iVictimFlags[victim] | VICFLG_FALL; + } + else if ( IS_VALID_INFECTED(attacker) && attacker != g_iVictimCharger[victim] ) + { + // if something other than the charger killed them, remember (not a DC) + g_iVictimFlags[victim] = g_iVictimFlags[victim] | VICFLG_KILLEDBYOTHER; + } + } + + return Plugin_Continue; +} + +public Action: Event_PlayerShoved( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new victim = GetClientOfUserId(GetEventInt(event, "userid")); + new attacker = GetClientOfUserId(GetEventInt(event, "attacker")); + + //PrintDebug(1, "Shove from %i on %i", attacker, victim); + + if ( !IS_VALID_SURVIVOR(attacker) || !IS_VALID_INFECTED(victim) ) { return Plugin_Continue; } + + new zClass = GetEntProp(victim, Prop_Send, "m_zombieClass"); + + //PrintDebug(1, " --> Shove from %N on %N (class: %i) -- (last shove time: %.2f / %.2f)", attacker, victim, zClass, g_fVictimLastShove[victim][attacker], ( GetGameTime() - g_fVictimLastShove[victim][attacker] ) ); + + // track on boomers + if ( zClass == ZC_BOOMER ) + { + g_iBoomerGotShoved[victim]++; + } + else { + // check for clears + switch ( zClass ) + { + case ZC_HUNTER: { + if ( GetEntPropEnt(victim, Prop_Send, "m_pounceVictim") > 0 ) + { + HandleClear( attacker, victim, GetEntPropEnt(victim, Prop_Send, "m_pounceVictim"), + ZC_HUNTER, + ( GetGameTime() - g_fPinTime[victim][0]), + -1.0, + true + ); + } + } + case ZC_JOCKEY: { + if ( GetEntPropEnt(victim, Prop_Send, "m_jockeyVictim") > 0 ) + { + HandleClear( attacker, victim, GetEntPropEnt(victim, Prop_Send, "m_jockeyVictim"), + ZC_JOCKEY, + ( GetGameTime() - g_fPinTime[victim][0]), + -1.0, + true + ); + } + } + } + } + + if ( g_fVictimLastShove[victim][attacker] == 0.0 || ( GetGameTime() - g_fVictimLastShove[victim][attacker] ) >= SHOVE_TIME ) + { + if ( GetEntProp(victim, Prop_Send, "m_isAttemptingToPounce") ) + { + HandleDeadstop( attacker, victim ); + } + + HandleShove( attacker, victim, zClass ); + + g_fVictimLastShove[victim][attacker] = GetGameTime(); + } + + // check for shove on smoker by pull victim + if ( g_iSmokerVictim[victim] == attacker ) + { + g_bSmokerShoved[victim] = true; + } + + //PrintDebug(0, "shove by %i on %i", attacker, victim ); + return Plugin_Continue; +} + +public Action: Event_LungePounce( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + + g_fPinTime[client][0] = GetGameTime(); + + // clear hunter-hit stats (not skeeted) + ResetHunter(client); + + // check if it was a DP + // ignore if no real pounce start pos + if ( g_fPouncePosition[client][0] == 0.0 + && g_fPouncePosition[client][1] == 0.0 + && g_fPouncePosition[client][2] == 0.0 + ) { + return Plugin_Continue; + } + + new Float: endPos[3]; + GetClientAbsOrigin( client, endPos ); + new Float: fHeight = g_fPouncePosition[client][2] - endPos[2]; + + // from pounceannounce: + // distance supplied isn't the actual 2d vector distance needed for damage calculation. See more about it at + // http://forums.alliedmods.net/showthread.php?t=93207 + + new Float: fMin = GetConVarFloat(g_hCvarMinPounceDistance); + new Float: fMax = GetConVarFloat(g_hCvarMaxPounceDistance); + new Float: fMaxDmg = GetConVarFloat(g_hCvarMaxPounceDamage); + + // calculate 2d distance between previous position and pounce position + new distance = RoundToNearest( GetVectorDistance(g_fPouncePosition[client], endPos) ); + + // get damage using hunter damage formula + // check if this is accurate, seems to differ from actual damage done! + new Float: fDamage = ( ( (float(distance) - fMin) / (fMax - fMin) ) * fMaxDmg ) + 1.0; + + // apply bounds + if (fDamage < 0.0) { + fDamage = 0.0; + } else if (fDamage > fMaxDmg + 1.0) { + fDamage = fMaxDmg + 1.0; + } + + new Handle: pack = CreateDataPack(); + WritePackCell( pack, client ); + WritePackCell( pack, victim ); + WritePackFloat( pack, fDamage ); + WritePackFloat( pack, fHeight ); + CreateTimer( 0.05, Timer_HunterDP, pack ); + + return Plugin_Continue; +} + +public Action: Timer_HunterDP( Handle:timer, Handle:pack ) +{ + ResetPack( pack ); + new client = ReadPackCell( pack ); + new victim = ReadPackCell( pack ); + new Float: fDamage = ReadPackFloat( pack ); + new Float: fHeight = ReadPackFloat( pack ); + CloseHandle( pack ); + + HandleHunterDP( client, victim, g_iPounceDamage[client], fDamage, fHeight ); +} + +public Action: Event_PlayerJumped( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + + if ( IS_VALID_INFECTED(client) ) + { + new zClass = GetEntProp(client, Prop_Send, "m_zombieClass"); + if ( zClass != ZC_JOCKEY ) { return Plugin_Continue; } + + // where did jockey jump from? + GetClientAbsOrigin( client, g_fPouncePosition[client] ); + } + else if ( IS_VALID_SURVIVOR(client) ) + { + // could be the start or part of a hopping streak + + new Float: fPos[3], Float: fVel[3]; + GetClientAbsOrigin( client, fPos ); + GetEntPropVector(client, Prop_Data, "m_vecVelocity", fVel ); + fVel[2] = 0.0; // safeguard + + new Float: fLengthNew, Float: fLengthOld; + fLengthNew = GetVectorLength(fVel); + + + g_bHopCheck[client] = false; + + if ( !g_bIsHopping[client] ) + { + if ( fLengthNew >= GetConVarFloat(g_hCvarBHopMinInitSpeed) ) + { + // starting potential hop streak + g_fHopTopVelocity[client] = fLengthNew; + g_bIsHopping[client] = true; + g_iHops[client] = 0; + } + } + else + { + // check for hopping streak + fLengthOld = GetVectorLength(g_fLastHop[client]); + + // if they picked up speed, count it as a hop, otherwise, we're done hopping + if ( fLengthNew - fLengthOld > HOP_ACCEL_THRESH || fLengthNew >= GetConVarFloat(g_hCvarBHopContSpeed) ) + { + g_iHops[client]++; + + // this should always be the case... + if ( fLengthNew > g_fHopTopVelocity[client] ) + { + g_fHopTopVelocity[client] = fLengthNew; + } + + //PrintToChat( client, "bunnyhop %i: speed: %.1f / increase: %.1f", g_iHops[client], fLengthNew, fLengthNew - fLengthOld ); + } + else + { + g_bIsHopping[client] = false; + + if ( g_iHops[client] ) + { + HandleBHopStreak( client, g_iHops[client], g_fHopTopVelocity[client] ); + g_iHops[client] = 0; + } + } + } + + g_fLastHop[client][0] = fVel[0]; + g_fLastHop[client][1] = fVel[1]; + g_fLastHop[client][2] = fVel[2]; + + if ( g_iHops[client] != 0 ) + { + // check when the player returns to the ground + CreateTimer( HOP_CHECK_TIME, Timer_CheckHop, client, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE ); + } + } + + return Plugin_Continue; +} + +public Action: Timer_CheckHop (Handle:timer, any:client) +{ + // player back to ground = end of hop (streak)? + + if ( !IS_VALID_INGAME(client) || !IsPlayerAlive(client) ) + { + // streak stopped by dying / teamswitch / disconnect? + return Plugin_Stop; + } + else if ( GetEntityFlags(client) & FL_ONGROUND ) + { + new Float: fVel[3]; + GetEntPropVector(client, Prop_Data, "m_vecVelocity", fVel ); + fVel[2] = 0.0; // safeguard + + //PrintToChatAll("grounded %i: vel length: %.1f", client, GetVectorLength(fVel) ); + + g_bHopCheck[client] = true; + + CreateTimer( HOPEND_CHECK_TIME, Timer_CheckHopStreak, client, TIMER_FLAG_NO_MAPCHANGE ); + + return Plugin_Stop; + } + + return Plugin_Continue; +} + +public Action: Timer_CheckHopStreak (Handle:timer, any:client) +{ + if ( !IS_VALID_INGAME(client) || !IsPlayerAlive(client) ) { return Plugin_Continue; } + + // check if we have any sort of hop streak, and report + if ( g_bHopCheck[client] && g_iHops[client] ) + { + HandleBHopStreak( client, g_iHops[client], g_fHopTopVelocity[client] ); + g_bIsHopping[client] = false; + g_iHops[client] = 0; + g_fHopTopVelocity[client] = 0.0; + } + + g_bHopCheck[client] = false; + + return Plugin_Continue; +} + + +public Action: Event_PlayerJumpApex( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + + if ( g_bIsHopping[client] ) + { + new Float: fVel[3]; + GetEntPropVector(client, Prop_Data, "m_vecVelocity", fVel ); + fVel[2] = 0.0; + new Float: fLength = GetVectorLength(fVel); + + if ( fLength > g_fHopTopVelocity[client] ) + { + g_fHopTopVelocity[client] = fLength; + } + } +} + + +public Action: Event_JockeyRide( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + + if ( !IS_VALID_INFECTED(client) || !IS_VALID_SURVIVOR(victim) ) { return Plugin_Continue; } + + g_fPinTime[client][0] = GetGameTime(); + + // minimum distance travelled? + // ignore if no real pounce start pos + if ( g_fPouncePosition[client][0] == 0.0 && g_fPouncePosition[client][1] == 0.0 && g_fPouncePosition[client][2] == 0.0 ) { return Plugin_Continue; } + + new Float: endPos[3]; + GetClientAbsOrigin( client, endPos ); + new Float: fHeight = g_fPouncePosition[client][2] - endPos[2]; + + //PrintToChatAll("jockey height: %.3f", fHeight); + + // (high) pounce + HandleJockeyDP( client, victim, fHeight ); + + return Plugin_Continue; +} + +public Action: Event_AbilityUse( Handle:event, const String:name[], bool:dontBroadcast ) +{ + // track hunters pouncing + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new String: abilityName[64]; + GetEventString( event, "ability", abilityName, sizeof(abilityName) ); + + if ( !IS_VALID_INGAME(client) ) { return Plugin_Continue; } + + new strAbility: ability; + if ( !GetTrieValue(g_hTrieAbility, abilityName, ability) ) { return Plugin_Continue; } + + switch ( ability ) + { + case ABL_HUNTERLUNGE: + { + // hunter started a pounce + ResetHunter(client); + GetClientAbsOrigin( client, g_fPouncePosition[client] ); + } + + case ABL_ROCKTHROW: + { + // tank throws rock + g_iRocksBeingThrown[g_iRocksBeingThrownCount] = client; + + // safeguard + if ( g_iRocksBeingThrownCount < 9 ) { g_iRocksBeingThrownCount++; } + } + } + + return Plugin_Continue; +} + +// charger carrying +public Action: Event_ChargeCarryStart( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + if ( !IS_VALID_INFECTED(client) ) { return; } + + PrintDebug(0, "Charge carry start: %i - %i -- time: %.2f", client, victim, GetGameTime() ); + + g_fChargeTime[client] = GetGameTime(); + g_fPinTime[client][0] = g_fChargeTime[client]; + g_fPinTime[client][1] = 0.0; + + if ( !IS_VALID_SURVIVOR(victim) ) { return; } + + g_iChargeVictim[client] = victim; // store who we're carrying (as long as this is set, it's not considered an impact charge flight) + g_iVictimCharger[victim] = client; // store who's charging whom + g_iVictimFlags[victim] = VICFLG_CARRIED; // reset flags for checking later - we know only this now + g_fChargeTime[victim] = g_fChargeTime[client]; + g_iVictimMapDmg[victim] = 0; + + GetClientAbsOrigin( victim, g_fChargeVictimPos[victim] ); + + //CreateTimer( CHARGE_CHECK_TIME, Timer_ChargeCheck, client, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE ); + CreateTimer( CHARGE_CHECK_TIME, Timer_ChargeCheck, victim, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE ); +} + +public Action: Event_ChargeImpact( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + if ( !IS_VALID_INFECTED(client) || !IS_VALID_SURVIVOR(victim) ) { return; } + + // remember how many people the charger bumped into, and who, and where they were + GetClientAbsOrigin( victim, g_fChargeVictimPos[victim] ); + + g_iVictimCharger[victim] = client; // store who we've bumped up + g_iVictimFlags[victim] = 0; // reset flags for checking later + g_fChargeTime[victim] = GetGameTime(); // store time per victim, for impacts + g_iVictimMapDmg[victim] = 0; + + CreateTimer( CHARGE_CHECK_TIME, Timer_ChargeCheck, victim, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE ); +} + +public Action: Event_ChargePummelStart( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + + if ( !IS_VALID_INFECTED(client) ) { return; } + + g_fPinTime[client][1] = GetGameTime(); +} + + +public Action: Event_ChargeCarryEnd( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + if ( client < 1 || client > MaxClients ) { return; } + + g_fPinTime[client][1] = GetGameTime(); + + // delay so we can check whether charger died 'mid carry' + CreateTimer( 0.1, Timer_ChargeCarryEnd, client, TIMER_FLAG_NO_MAPCHANGE ); +} + +public Action: Timer_ChargeCarryEnd( Handle:timer, any:client ) +{ + // set charge time to 0 to avoid deathcharge timer continuing + g_iChargeVictim[client] = 0; // unset this so the repeated timer knows to stop for an ongroundcheck +} + +public Action: Timer_ChargeCheck( Handle:timer, any:client ) +{ + // if something went wrong with the survivor or it was too long ago, forget about it + if ( !IS_VALID_SURVIVOR(client) || !g_iVictimCharger[client] || g_fChargeTime[client] == 0.0 || ( GetGameTime() - g_fChargeTime[client]) > MAX_CHARGE_TIME ) + { + return Plugin_Stop; + } + + // we're done checking if either the victim reached the ground, or died + if ( !IsPlayerAlive(client) ) + { + // player died (this was .. probably.. a death charge) + g_iVictimFlags[client] = g_iVictimFlags[client] | VICFLG_AIRDEATH; + + // check conditions now + CreateTimer( 0.0, Timer_DeathChargeCheck, client, TIMER_FLAG_NO_MAPCHANGE ); + + return Plugin_Stop; + } + else if ( GetEntityFlags(client) & FL_ONGROUND && g_iChargeVictim[ g_iVictimCharger[client] ] != client ) + { + // survivor reached the ground and didn't die (yet) + // the client-check condition checks whether the survivor is still being carried by the charger + // (in which case it doesn't matter that they're on the ground) + + // check conditions with small delay (to see if they still die soon) + CreateTimer( CHARGE_END_CHECK, Timer_DeathChargeCheck, client, TIMER_FLAG_NO_MAPCHANGE ); + + return Plugin_Stop; + } + + return Plugin_Continue; +} + +public Action: Timer_DeathChargeCheck( Handle:timer, any:client ) +{ + if ( !IS_VALID_INGAME(client) ) { return; } + + // check conditions.. if flags match up, it's a DC + PrintDebug( 3, "Checking charge victim: %i - %i - flags: %i (alive? %i)", g_iVictimCharger[client], client, g_iVictimFlags[client], IsPlayerAlive(client) ); + + new flags = g_iVictimFlags[client]; + + if ( !IsPlayerAlive(client) ) + { + new Float: pos[3]; + GetClientAbsOrigin( client, pos ); + new Float: fHeight = g_fChargeVictimPos[client][2] - pos[2]; + + /* + it's a deathcharge when: + the survivor is dead AND + they drowned/fell AND took enough damage or died in mid-air + AND not killed by someone else + OR is in an unreachable spot AND dropped at least X height + OR took plenty of map damage + + old.. need? + fHeight > GetConVarFloat(g_hCvarDeathChargeHeight) + */ + if ( ( ( flags & VICFLG_DROWN || flags & VICFLG_FALL ) && + ( flags & VICFLG_HURTLOTS || flags & VICFLG_AIRDEATH ) || + ( flags & VICFLG_WEIRDFLOW && fHeight >= MIN_FLOWDROPHEIGHT ) || + g_iVictimMapDmg[client] >= MIN_DC_TRIGGER_DMG + ) && + !( flags & VICFLG_KILLEDBYOTHER ) + ) { + HandleDeathCharge( g_iVictimCharger[client], client, fHeight, GetVectorDistance(g_fChargeVictimPos[client], pos, false), bool:(flags & VICFLG_CARRIED) ); + } + } + else if ( ( flags & VICFLG_WEIRDFLOW || g_iVictimMapDmg[client] >= MIN_DC_RECHECK_DMG ) && + !(flags & VICFLG_WEIRDFLOWDONE) + ) { + // could be incapped and dying more slowly + // flag only gets set on preincap, so don't need to check for incap + g_iVictimFlags[client] = g_iVictimFlags[client] | VICFLG_WEIRDFLOWDONE; + + CreateTimer( CHARGE_END_RECHECK, Timer_DeathChargeCheck, client, TIMER_FLAG_NO_MAPCHANGE ); + } +} + +stock ResetHunter(client) +{ + g_iHunterShotDmgTeam[client] = 0; + + for ( new i=1; i <= MaxClients; i++ ) + { + g_iHunterShotDmg[client][i] = 0; + g_fHunterShotStart[client][i] = 0.0; + } + g_iHunterOverkill[client] = 0; +} + + +// entity creation +public OnEntityCreated ( entity, const String:classname[] ) +{ + if ( entity < 1 || !IsValidEntity(entity) || !IsValidEdict(entity) ) { return; } + + // track infected / witches, so damage on them counts as hits + + new strOEC: classnameOEC; + if (!GetTrieValue(g_hTrieEntityCreated, classname, classnameOEC)) { return; } + + switch ( classnameOEC ) + { + case OEC_TANKROCK: + { + decl String:rock_key[10]; + FormatEx(rock_key, sizeof(rock_key), "%x", entity); + new rock_array[3]; + + // store which tank is throwing what rock + new tank = ShiftTankThrower(); + + if ( IS_VALID_INGAME(tank) ) + { + g_iTankRock[tank] = entity; + rock_array[rckTank] = tank; + } + SetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array), true); + + SDKHook(entity, SDKHook_TraceAttack, TraceAttack_Rock); + SDKHook(entity, SDKHook_Touch, OnTouch_Rock); + } + + + case OEC_CARALARM: + { + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", entity); + + SDKHook(entity, SDKHook_OnTakeDamage, OnTakeDamage_Car); + SDKHook(entity, SDKHook_Touch, OnTouch_Car); + + SDKHook(entity, SDKHook_Spawn, OnEntitySpawned_CarAlarm); + } + + case OEC_CARGLASS: + { + SDKHook(entity, SDKHook_OnTakeDamage, OnTakeDamage_CarGlass); + SDKHook(entity, SDKHook_Touch, OnTouch_CarGlass); + + //SetTrieValue(g_hCarTrie, car_key, ); + SDKHook(entity, SDKHook_Spawn, OnEntitySpawned_CarAlarmGlass); + } + } +} + +public OnEntitySpawned_CarAlarm ( entity ) +{ + if ( !IsValidEntity(entity) ) { return; } + + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", entity); + + decl String:target[48]; + GetEntPropString(entity, Prop_Data, "m_iName", target, sizeof(target)); + + SetTrieValue( g_hCarTrie, target, entity ); + SetTrieValue( g_hCarTrie, car_key, 0 ); // who shot the car? + + HookSingleEntityOutput( entity, "OnCarAlarmStart", Hook_CarAlarmStart ); +} + +public OnEntitySpawned_CarAlarmGlass ( entity ) +{ + if ( !IsValidEntity(entity) ) { return; } + + // glass is parented to a car, link the two through the trie + // find parent and save both + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", entity); + + decl String:parent[48]; + GetEntPropString(entity, Prop_Data, "m_iParent", parent, sizeof(parent)); + new parentEntity; + + // find targetname in trie + if ( GetTrieValue(g_hCarTrie, parent, parentEntity ) ) + { + // if valid entity, save the parent entity + if ( IsValidEntity(parentEntity) ) + { + SetTrieValue( g_hCarTrie, car_key, parentEntity ); + + decl String:car_key_p[10]; + FormatEx(car_key_p, sizeof(car_key_p), "%x_A", parentEntity); + new testEntity; + + if ( GetTrieValue(g_hCarTrie, car_key_p, testEntity) ) + { + // second glass + FormatEx(car_key_p, sizeof(car_key_p), "%x_B", parentEntity); + } + + SetTrieValue( g_hCarTrie, car_key_p, entity ); + } + } +} + +// entity destruction +public OnEntityDestroyed ( entity ) +{ + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", entity); + + decl rock_array[3]; + if ( GetTrieArray(g_hRockTrie, witch_key, rock_array, sizeof(rock_array)) ) + { + // tank rock + CreateTimer( ROCK_CHECK_TIME, Timer_CheckRockSkeet, entity ); + SDKUnhook(entity, SDKHook_TraceAttack, TraceAttack_Rock); + return; + } + + decl witch_array[MAXPLAYERS+DMGARRAYEXT]; + if ( GetTrieArray(g_hWitchTrie, witch_key, witch_array, sizeof(witch_array)) ) + { + // witch + // delayed deletion, to avoid potential problems with crowns not detecting + CreateTimer( WITCH_DELETE_TIME, Timer_WitchKeyDelete, entity ); + SDKUnhook(entity, SDKHook_OnTakeDamagePost, OnTakeDamagePost_Witch); + return; + } +} + +public Action: Timer_WitchKeyDelete (Handle:timer, any:witch) +{ + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", witch); + RemoveFromTrie(g_hWitchTrie, witch_key); +} + + +public Action: Timer_CheckRockSkeet (Handle:timer, any:rock) +{ + decl rock_array[3]; + decl String: rock_key[10]; + FormatEx(rock_key, sizeof(rock_key), "%x", rock); + if (!GetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array)) ) { return Plugin_Continue; } + + RemoveFromTrie(g_hRockTrie, rock_key); + + // if rock didn't hit anyone / didn't touch anything, it was shot + if ( rock_array[rckDamage] > 0 ) + { + HandleRockSkeeted( rock_array[rckSkeeter], rock_array[rckTank] ); + } + + return Plugin_Continue; +} + +// boomer got somebody +public Action: Event_PlayerBoomed (Handle:event, const String:name[], bool:dontBroadcast) +{ + new attacker = GetClientOfUserId( GetEventInt(event, "attacker") ); + new bool: byBoom = GetEventBool(event, "by_boomer"); + + if ( byBoom && IS_VALID_INFECTED(attacker) ) + { + g_bBoomerHitSomebody[attacker] = true; + + // check if it was vomit spray + new bool: byExplosion = GetEventBool(event, "exploded"); + if ( !byExplosion ) + { + // count amount of booms + if ( !g_iBoomerVomitHits[attacker] ) { + // check for boom count later + CreateTimer( VOMIT_DURATION_TIME, Timer_BoomVomitCheck, attacker, TIMER_FLAG_NO_MAPCHANGE ); + } + g_iBoomerVomitHits[attacker]++; + } + } +} +// check how many booms landed +public Action: Timer_BoomVomitCheck ( Handle:timer, any:client ) +{ + HandleVomitLanded( client, g_iBoomerVomitHits[client] ); + g_iBoomerVomitHits[client] = 0; +} + +// boomers that didn't bile anyone +public Action: Event_BoomerExploded (Handle:event, const String:name[], bool:dontBroadcast) +{ + new client = GetClientOfUserId( GetEventInt(event, "userid") ); + new bool: biled = GetEventBool(event, "splashedbile"); + if ( !biled && !g_bBoomerHitSomebody[client] ) + { + new attacker = GetClientOfUserId( GetEventInt(event, "attacker") ); + if ( IS_VALID_SURVIVOR(attacker) ) + { + HandlePop( attacker, client, g_iBoomerGotShoved[client], (GetGameTime() - g_fSpawnTime[client]) ); + } + } +} + +// crown tracking +public Action: Event_WitchSpawned ( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new witch = GetEventInt(event, "witchid"); + + SDKHook(witch, SDKHook_OnTakeDamagePost, OnTakeDamagePost_Witch); + + new witch_dmg_array[MAXPLAYERS+DMGARRAYEXT]; + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", witch); + witch_dmg_array[MAXPLAYERS+WTCH_HEALTH] = GetConVarInt(g_hCvarWitchHealth); + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, false); +} + +public Action: Event_WitchKilled ( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new witch = GetEventInt(event, "witchid"); + new attacker = GetClientOfUserId( GetEventInt(event, "userid") ); + SDKUnhook(witch, SDKHook_OnTakeDamagePost, OnTakeDamagePost_Witch); + + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + new bool: bOneShot = GetEventBool(event, "oneshot"); + + // is it a crown / drawcrown? + new Handle: pack = CreateDataPack(); + WritePackCell( pack, attacker ); + WritePackCell( pack, witch ); + WritePackCell( pack, (bOneShot) ? 1 : 0 ); + CreateTimer( WITCH_CHECK_TIME, Timer_CheckWitchCrown, pack ); + + return Plugin_Continue; +} +public Action: Event_WitchHarasserSet ( Handle:event, const String:name[], bool:dontBroadcast ) +{ + new witch = GetEventInt(event, "witchid"); + + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", witch); + decl witch_dmg_array[MAXPLAYERS+DMGARRAYEXT]; + + if ( !GetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT) ) + { + for ( new i = 0; i <= MAXPLAYERS; i++ ) + { + witch_dmg_array[i] = 0; + } + witch_dmg_array[MAXPLAYERS+WTCH_HEALTH] = GetConVarInt(g_hCvarWitchHealth); + witch_dmg_array[MAXPLAYERS+WTCH_STARTLED] = 1; // harasser set + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, false); + } + else + { + witch_dmg_array[MAXPLAYERS+WTCH_STARTLED] = 1; // harasser set + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, true); + } +} + +public Action: OnTakeDamageByWitch ( victim, &attacker, &inflictor, &Float:damage, &damagetype ) +{ + // if a survivor is hit by a witch, note it in the witch damage array (maxplayers+2 = 1) + if ( IS_VALID_SURVIVOR(victim) && damage > 0.0 ) + { + + // not a crown if witch hit anyone for > 0 damage + if ( IsWitch(attacker) ) + { + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", attacker); + decl witch_dmg_array[MAXPLAYERS+DMGARRAYEXT]; + + if ( !GetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT) ) + { + for ( new i = 0; i <= MAXPLAYERS; i++ ) + { + witch_dmg_array[i] = 0; + } + witch_dmg_array[MAXPLAYERS+WTCH_HEALTH] = GetConVarInt(g_hCvarWitchHealth); + witch_dmg_array[MAXPLAYERS+WTCH_GOTSLASH] = 1; // failed + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, false); + } + else + { + witch_dmg_array[MAXPLAYERS+WTCH_GOTSLASH] = 1; // failed + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, true); + } + } + } +} + +public OnTakeDamagePost_Witch ( victim, attacker, inflictor, Float:damage, damagetype ) +{ + // only called for witches, so no check required + + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", victim); + decl witch_dmg_array[MAXPLAYERS+DMGARRAYEXT]; + + if ( !GetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT) ) + { + for ( new i = 0; i <= MAXPLAYERS; i++ ) + { + witch_dmg_array[i] = 0; + } + witch_dmg_array[MAXPLAYERS+WTCH_HEALTH] = GetConVarInt(g_hCvarWitchHealth); + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, false); + } + + // store damage done to witch + if ( IS_VALID_SURVIVOR(attacker) ) + { + witch_dmg_array[attacker] += RoundToFloor(damage); + witch_dmg_array[MAXPLAYERS+WTCH_HEALTH] -= RoundToFloor(damage); + + // remember last shot + if ( g_fWitchShotStart[attacker] == 0.0 || (GetGameTime() - g_fWitchShotStart[attacker]) > SHOTGUN_BLAST_TIME ) + { + // reset last shot damage count and attacker + g_fWitchShotStart[attacker] = GetGameTime(); + witch_dmg_array[MAXPLAYERS+WTCH_CROWNER] = attacker; + witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] = 0; + witch_dmg_array[MAXPLAYERS+WTCH_CROWNTYPE] = ( damagetype & DMG_BUCKSHOT ) ? 1 : 0; // only allow shotguns + } + + // continued blast, add up + witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] += RoundToFloor(damage); + + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, true); + } + else + { + // store all chip from other sources than survivor in [0] + witch_dmg_array[0] += RoundToFloor(damage); + //witch_dmg_array[MAXPLAYERS+1] -= RoundToFloor(damage); + SetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT, true); + } +} + +public Action: Timer_CheckWitchCrown(Handle:timer, Handle:pack) +{ + ResetPack( pack ); + new attacker = ReadPackCell( pack ); + new witch = ReadPackCell( pack ); + new bool:bOneShot = bool:ReadPackCell( pack ); + CloseHandle( pack ); + + CheckWitchCrown( witch, attacker, bOneShot ); +} + +stock CheckWitchCrown ( witch, attacker, bool: bOneShot = false ) +{ + decl String:witch_key[10]; + FormatEx(witch_key, sizeof(witch_key), "%x", witch); + decl witch_dmg_array[MAXPLAYERS+DMGARRAYEXT]; + if ( !GetTrieArray(g_hWitchTrie, witch_key, witch_dmg_array, MAXPLAYERS+DMGARRAYEXT) ) { + PrintDebug(0, "Witch Crown Check: Error: Trie entry missing (entity: %i, oneshot: %i)", witch, bOneShot); + return; + } + + new chipDamage = 0; + new iWitchHealth = GetConVarInt(g_hCvarWitchHealth); + + /* + the attacker is the last one that did damage to witch + if their damage is full damage on an unharrassed witch, it's a full crown + if their damage is full or > drawcrown_threshhold, it's a drawcrown + */ + + // not a crown at all if anyone was hit, or if the killing damage wasn't a shotgun blast + + // safeguard: if it was a 'oneshot' witch kill, must've been a shotgun + // this is not enough: sometimes a shotgun crown happens that is not even reported as a oneshot... + // seems like the cause is that the witch post ontakedamage is not called in time? + if ( bOneShot ) + { + witch_dmg_array[MAXPLAYERS+WTCH_CROWNTYPE] = 1; + } + + if ( witch_dmg_array[MAXPLAYERS+WTCH_GOTSLASH] || !witch_dmg_array[MAXPLAYERS+WTCH_CROWNTYPE] ) + { + PrintDebug(0, "Witch Crown Check: Failed: bungled: %i / crowntype: %i (entity: %i)", + witch_dmg_array[MAXPLAYERS+WTCH_GOTSLASH], + witch_dmg_array[MAXPLAYERS+WTCH_CROWNTYPE], + witch + ); + PrintDebug(1, "Witch Crown Check: Further details: attacker: %N, attacker dmg: %i, teamless dmg: %i", + attacker, + witch_dmg_array[attacker], + witch_dmg_array[0] + ); + return; + } + + PrintDebug(0, "Witch Crown Check: crown shot: %i, harrassed: %i (full health: %i / drawthresh: %i / oneshot %i)", + witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT], + witch_dmg_array[MAXPLAYERS+WTCH_STARTLED], + iWitchHealth, + GetConVarInt(g_hCvarDrawCrownThresh), + bOneShot + ); + + // full crown? unharrassed + if ( !witch_dmg_array[MAXPLAYERS+WTCH_STARTLED] && ( bOneShot || witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] >= iWitchHealth ) ) + { + // make sure that we don't count any type of chip + if ( GetConVarBool(g_hCvarHideFakeDamage) ) + { + chipDamage = 0; + for ( new i = 0; i <= MAXPLAYERS; i++ ) + { + if ( i == attacker ) { continue; } + chipDamage += witch_dmg_array[i]; + } + witch_dmg_array[attacker] = iWitchHealth - chipDamage; + } + HandleCrown( attacker, witch_dmg_array[attacker] ); + } + else if ( witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] >= GetConVarInt(g_hCvarDrawCrownThresh) ) + { + // draw crown: harassed + over X damage done by one survivor -- in ONE shot + + for ( new i = 0; i <= MAXPLAYERS; i++ ) + { + if ( i == attacker ) { + // count any damage done before final shot as chip + chipDamage += witch_dmg_array[i] - witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT]; + } else { + chipDamage += witch_dmg_array[i]; + } + } + + // make sure that we don't count any type of chip + if ( GetConVarBool(g_hCvarHideFakeDamage) ) + { + // unlikely to happen, but if the chip was A LOT + if ( chipDamage >= iWitchHealth ) { + chipDamage = iWitchHealth - 1; + witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] = 1; + } + else { + witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] = iWitchHealth - chipDamage; + } + // re-check whether it qualifies as a drawcrown: + if ( witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT] < GetConVarInt(g_hCvarDrawCrownThresh) ) { return; } + } + + // plus, set final shot as 'damage', and the rest as chip + HandleDrawCrown( attacker, witch_dmg_array[MAXPLAYERS+WTCH_CROWNSHOT], chipDamage ); + } + + // remove trie + +} + +// tank rock +public Action: TraceAttack_Rock (victim, &attacker, &inflictor, &Float:damage, &damagetype, &ammotype, hitbox, hitgroup) +{ + if ( IS_VALID_SURVIVOR(attacker) ) + { + /* + can't really use this for precise detection, though it does + report the last shot -- the damage report is without distance falloff + */ + decl String:rock_key[10]; + decl rock_array[3]; + FormatEx(rock_key, sizeof(rock_key), "%x", victim); + GetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array)); + rock_array[rckDamage] += RoundToFloor(damage); + rock_array[rckSkeeter] = attacker; + SetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array), true); + } +} + +public OnTouch_Rock ( entity ) +{ + // remember that the rock wasn't shot + decl String:rock_key[10]; + FormatEx(rock_key, sizeof(rock_key), "%x", entity); + new rock_array[3]; + rock_array[rckDamage] = -1; + SetTrieArray(g_hRockTrie, rock_key, rock_array, sizeof(rock_array), true); + + SDKUnhook(entity, SDKHook_Touch, OnTouch_Rock); +} + +// smoker tongue cutting & self clears +public Action: Event_TonguePullStopped (Handle:event, const String:name[], bool:dontBroadcast) +{ + new attacker = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + new smoker = GetClientOfUserId( GetEventInt(event, "smoker") ); + new reason = GetEventInt(event, "release_type"); + + if ( !IS_VALID_SURVIVOR(attacker) || !IS_VALID_INFECTED(smoker) ) { return Plugin_Continue; } + + // clear check - if the smoker itself was not shoved, handle the clear + HandleClear( attacker, smoker, victim, + ZC_SMOKER, + (g_fPinTime[smoker][1] > 0.0) ? ( GetGameTime() - g_fPinTime[smoker][1]) : -1.0, + ( GetGameTime() - g_fPinTime[smoker][0]), + bool:( reason != CUT_SLASH && reason != CUT_KILL ) + ); + + if ( attacker != victim ) { return Plugin_Continue; } + + if ( reason == CUT_KILL ) + { + g_bSmokerClearCheck[smoker] = true; + } + else if ( g_bSmokerShoved[smoker] ) + { + HandleSmokerSelfClear( attacker, smoker, true ); + } + else if ( reason == CUT_SLASH ) // note: can't trust this to actually BE a slash.. + { + // check weapon + decl String:weapon[32]; + GetClientWeapon( attacker, weapon, 32 ); + + // this doesn't count the chainsaw, but that's no-skill anyway + if ( StrEqual(weapon, "weapon_melee", false) ) + { + HandleTongueCut( attacker, smoker ); + } + } + + return Plugin_Continue; +} + +public Action: Event_TongueGrab (Handle:event, const String:name[], bool:dontBroadcast) +{ + new attacker = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + + if ( IS_VALID_INFECTED(attacker) && IS_VALID_SURVIVOR(victim) ) + { + // new pull, clean damage + g_bSmokerClearCheck[attacker] = false; + g_bSmokerShoved[attacker] = false; + g_iSmokerVictim[attacker] = victim; + g_iSmokerVictimDamage[attacker] = 0; + g_fPinTime[attacker][0] = GetGameTime(); + g_fPinTime[attacker][1] = 0.0; + } + + return Plugin_Continue; +} + +public Action: Event_ChokeStart (Handle:event, const String:name[], bool:dontBroadcast) +{ + new attacker = GetClientOfUserId( GetEventInt(event, "userid") ); + + if ( g_fPinTime[attacker][0] == 0.0 ) { g_fPinTime[attacker][0] = GetGameTime(); } + g_fPinTime[attacker][1] = GetGameTime(); +} + +public Action: Event_ChokeStop (Handle:event, const String:name[], bool:dontBroadcast) +{ + new attacker = GetClientOfUserId( GetEventInt(event, "userid") ); + new victim = GetClientOfUserId( GetEventInt(event, "victim") ); + new smoker = GetClientOfUserId( GetEventInt(event, "smoker") ); + new reason = GetEventInt(event, "release_type"); + + if ( !IS_VALID_SURVIVOR(attacker) || !IS_VALID_INFECTED(smoker) ) { return; } + + // if the smoker itself was not shoved, handle the clear + HandleClear( attacker, smoker, victim, + ZC_SMOKER, + (g_fPinTime[smoker][1] > 0.0) ? ( GetGameTime() - g_fPinTime[smoker][1]) : -1.0, + ( GetGameTime() - g_fPinTime[smoker][0]), + bool:( reason != CUT_SLASH && reason != CUT_KILL ) + ); +} + +// car alarm handling +public Hook_CarAlarmStart ( const String:output[], caller, activator, Float:delay ) +{ + //decl String:car_key[10]; + //FormatEx(car_key, sizeof(car_key), "%x", entity); + + PrintDebug( 0, "calarm trigger: caller %i / activator %i / delay: %.2f", caller, activator, delay ); +} +public Action: Event_CarAlarmGoesOff( Handle:event, const String:name[], bool:dontBroadcast ) +{ + g_fLastCarAlarm = GetGameTime(); +} + +public Action: OnTakeDamage_Car ( victim, &attacker, &inflictor, &Float:damage, &damagetype ) +{ + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + /* + boomer popped on alarmed car = + DMG_BLAST_SURFACE| DMG_BLAST + and inflictor is the boomer + + melee slash/club = + DMG_SLOWBURN|DMG_PREVENT_PHYSICS_FORCE + DMG_CLUB or DMG_SLASH + shove is without DMG_SLOWBURN + */ + + CreateTimer( 0.01, Timer_CheckAlarm, victim, TIMER_FLAG_NO_MAPCHANGE ); + + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", victim); + SetTrieValue(g_hCarTrie, car_key, attacker); + + if ( damagetype & DMG_BLAST ) + { + if ( IS_VALID_INFECTED(inflictor) && GetEntProp(inflictor, Prop_Send, "m_zombieClass") == ZC_BOOMER ) { + g_iLastCarAlarmReason[attacker] = CALARM_BOOMER; + g_iLastCarAlarmBoomer = inflictor; + } else { + g_iLastCarAlarmReason[attacker] = CALARM_EXPLOSION; + } + } + else if ( damage == 0.0 && ( damagetype & DMG_CLUB || damagetype & DMG_SLASH ) && !( damagetype & DMG_SLOWBURN) ) + { + g_iLastCarAlarmReason[attacker] = CALARM_TOUCHED; + } + else + { + g_iLastCarAlarmReason[attacker] = CALARM_HIT; + } + + return Plugin_Continue; +} + +public OnTouch_Car ( entity, client ) +{ + if ( !IS_VALID_SURVIVOR(client) ) { return; } + + CreateTimer( 0.01, Timer_CheckAlarm, entity, TIMER_FLAG_NO_MAPCHANGE ); + + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", entity); + SetTrieValue(g_hCarTrie, car_key, client); + + g_iLastCarAlarmReason[client] = CALARM_TOUCHED; + + return; +} + +public Action: OnTakeDamage_CarGlass ( victim, &attacker, &inflictor, &Float:damage, &damagetype ) +{ + // check for either: boomer pop or survivor + if ( !IS_VALID_SURVIVOR(attacker) ) { return Plugin_Continue; } + + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", victim); + new parentEntity; + + if ( GetTrieValue(g_hCarTrie, car_key, parentEntity) ) + { + CreateTimer( 0.01, Timer_CheckAlarm, parentEntity, TIMER_FLAG_NO_MAPCHANGE ); + + FormatEx(car_key, sizeof(car_key), "%x", parentEntity); + SetTrieValue(g_hCarTrie, car_key, attacker); + + if ( damagetype & DMG_BLAST ) + { + if ( IS_VALID_INFECTED(inflictor) && GetEntProp(inflictor, Prop_Send, "m_zombieClass") == ZC_BOOMER ) { + g_iLastCarAlarmReason[attacker] = CALARM_BOOMER; + g_iLastCarAlarmBoomer = inflictor; + } else { + g_iLastCarAlarmReason[attacker] = CALARM_EXPLOSION; + } + } + else if ( damage == 0.0 && ( damagetype & DMG_CLUB || damagetype & DMG_SLASH ) && !( damagetype & DMG_SLOWBURN) ) + { + g_iLastCarAlarmReason[attacker] = CALARM_TOUCHED; + } + else + { + g_iLastCarAlarmReason[attacker] = CALARM_HIT; + } + } + + return Plugin_Continue; +} + +public OnTouch_CarGlass ( entity, client ) +{ + if ( !IS_VALID_SURVIVOR(client) ) { return; } + + decl String:car_key[10]; + FormatEx(car_key, sizeof(car_key), "%x", entity); + new parentEntity; + + if ( GetTrieValue(g_hCarTrie, car_key, parentEntity) ) + { + CreateTimer( 0.01, Timer_CheckAlarm, parentEntity, TIMER_FLAG_NO_MAPCHANGE ); + + FormatEx(car_key, sizeof(car_key), "%x", parentEntity); + SetTrieValue(g_hCarTrie, car_key, client); + + g_iLastCarAlarmReason[client] = CALARM_TOUCHED; + } + + return; +} + +public Action: Timer_CheckAlarm (Handle:timer, any:entity) +{ + //PrintToChatAll( "checking alarm: time: %.3f", GetGameTime() - g_fLastCarAlarm ); + + if ( (GetGameTime() - g_fLastCarAlarm) < CARALARM_MIN_TIME ) + { + // got a match, drop stuff from trie and handle triggering + decl String:car_key[10]; + new testEntity; + new survivor = -1; + + // remove car glass + FormatEx(car_key, sizeof(car_key), "%x_A", entity); + if ( GetTrieValue(g_hCarTrie, car_key, testEntity) ) + { + RemoveFromTrie(g_hCarTrie, car_key); + SDKUnhook(testEntity, SDKHook_OnTakeDamage, OnTakeDamage_CarGlass); + SDKUnhook(testEntity, SDKHook_Touch, OnTouch_CarGlass); + } + FormatEx(car_key, sizeof(car_key), "%x_B", entity); + if ( GetTrieValue(g_hCarTrie, car_key, testEntity) ) + { + RemoveFromTrie(g_hCarTrie, car_key); + SDKUnhook(testEntity, SDKHook_OnTakeDamage, OnTakeDamage_CarGlass); + SDKUnhook(testEntity, SDKHook_Touch, OnTouch_CarGlass); + } + + // remove car + FormatEx(car_key, sizeof(car_key), "%x", entity); + if ( GetTrieValue(g_hCarTrie, car_key, survivor) ) + { + RemoveFromTrie(g_hCarTrie, car_key); + SDKUnhook(entity, SDKHook_OnTakeDamage, OnTakeDamage_Car); + SDKUnhook(entity, SDKHook_Touch, OnTouch_Car); + } + + // check for infected assistance + new infected = 0; + if ( IS_VALID_SURVIVOR(survivor) ) + { + if ( g_iLastCarAlarmReason[survivor] == CALARM_BOOMER ) + { + infected = g_iLastCarAlarmBoomer; + } + else if ( IS_VALID_INFECTED(GetEntPropEnt(survivor, Prop_Send, "m_carryAttacker")) ) + { + infected = GetEntPropEnt(survivor, Prop_Send, "m_carryAttacker"); + } + else if ( IS_VALID_INFECTED(GetEntPropEnt(survivor, Prop_Send, "m_jockeyAttacker")) ) + { + infected = GetEntPropEnt(survivor, Prop_Send, "m_jockeyAttacker"); + } + else if ( IS_VALID_INFECTED(GetEntPropEnt(survivor, Prop_Send, "m_tongueOwner")) ) + { + infected = GetEntPropEnt(survivor, Prop_Send, "m_tongueOwner"); + } + } + + HandleCarAlarmTriggered( + survivor, + infected, + (IS_VALID_INGAME(survivor)) ? g_iLastCarAlarmReason[survivor] : CALARM_UNKNOWN + ); + } +} + + +/* throwactivate .. for more reliable rock-tracking? +public Action: L4D_OnCThrowActivate ( ability ) +{ + // tank throws rock + if ( !IsValidEntity(ability) ) { return Plugin_Continue; } + + // find tank player + new tank = GetEntPropEnt(ability, Prop_Send, "m_owner"); + if ( !IS_VALID_INGAME(tank) ) { return Plugin_Continue; } + + ... +} +*/ + +/* + Reporting and forwards + ---------------------- +*/ +// boomer pop +stock HandlePop( attacker, victim, shoveCount, Float:timeAlive ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_POP ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 popped \x05%N\x01.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 popped a boomer.", attacker ); + } + } + + Call_StartForward(g_hForwardBoomerPop); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(shoveCount); + Call_PushFloat(timeAlive); + Call_Finish(); +} + +// charger level +stock HandleLevel( attacker, victim ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_LEVEL ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 leveled \x05%N\x01.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 leveled a charger.", attacker ); + } + else { + PrintToChatAll( "A charger was leveled." ); + } + } + + // call forward + Call_StartForward(g_hForwardLevel); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); +} +// charger level hurt +stock HandleLevelHurt( attacker, victim, damage ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_HURTLEVEL ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 chip-leveled \x05%N\x01 (\x03%i\x01 damage).", attacker, victim, damage ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 chip-leveled a charger. (\x03%i\x01 damage)", attacker, damage ); + } + else { + PrintToChatAll( "A charger was chip-leveled (\x03%i\x01 damage).", damage ); + } + } + + // call forward + Call_StartForward(g_hForwardLevelHurt); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(damage); + Call_Finish(); +} + +// deadstops +stock HandleDeadstop( attacker, victim ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_DEADSTOP ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 deadstopped \x05%N\x01.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 deadstopped a hunter.", attacker ); + } + } + + Call_StartForward(g_hForwardHunterDeadstop); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); +} + +stock HandleShove( attacker, victim, zombieClass ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_SHOVE ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 shoved \x05%N\x01.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 shoved an SI.", attacker ); + } + } + + Call_StartForward(g_hForwardSIShove); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(zombieClass); + Call_Finish(); +} + +// real skeet +stock HandleSkeet( attacker, victim, bool:bMelee = false, bool:bSniper = false, bool:bGL = false ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_SKEET ) + { + if ( attacker == -2 ) + { + // team skeet sets to -2 + if ( IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) { + PrintToChatAll( "\x05%N\x01 was team-skeeted.", victim ); + } else { + PrintToChatAll( "\x01A hunter was team-skeeted." ); + } + } + else if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 %sskeeted \x05%N\x01.", + attacker, + (bMelee) ? "melee-": ((bSniper) ? "headshot-" : ((bGL) ? "grenade-" : "") ), + victim + ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 %sskeeted a hunter.", + attacker, + (bMelee) ? "melee-": ((bSniper) ? "headshot-" : ((bGL) ? "grenade-" : "") ) + ); + } + } + + // call forward + if ( bSniper ) + { + Call_StartForward(g_hForwardSkeetSniper); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); + } + else if ( bGL ) + { + Call_StartForward(g_hForwardSkeetGL); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); + } + else if ( bMelee ) + { + Call_StartForward(g_hForwardSkeetMelee); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); + } + else + { + Call_StartForward(g_hForwardSkeet); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); + } +} + +// hurt skeet / non-skeet +// NOTE: bSniper not set yet, do this +stock HandleNonSkeet( attacker, victim, damage, bool:bOverKill = false, bool:bMelee = false, bool:bSniper = false ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_HURTSKEET ) + { + if ( IS_VALID_INGAME(victim) ) + { + PrintToChatAll( "\x05%N\x01 was \x04not\x01 skeeted (\x03%i\x01 damage).%s", victim, damage, (bOverKill) ? "(Would've skeeted if hunter were unchipped!)" : "" ); + } + else + { + PrintToChatAll( "\x01Hunter was \x04not\x01 skeeted (\x03%i\x01 damage).%s", damage, (bOverKill) ? "(Would've skeeted if hunter were unchipped!)" : "" ); + } + } + + // call forward + if ( bSniper ) + { + Call_StartForward(g_hForwardSkeetSniperHurt); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(damage); + Call_PushCell(bOverKill); + Call_Finish(); + } + else if ( bMelee ) + { + Call_StartForward(g_hForwardSkeetMeleeHurt); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(damage); + Call_PushCell(bOverKill); + Call_Finish(); + } + else + { + Call_StartForward(g_hForwardSkeetHurt); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(damage); + Call_PushCell(bOverKill); + Call_Finish(); + } +} + + +// crown +HandleCrown( attacker, damage ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_CROWN ) + { + if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 crowned a witch (\x03%i\x01 damage).", attacker, damage ); + } + else { + PrintToChatAll( "A witch was crowned." ); + } + } + + // call forward + Call_StartForward(g_hForwardCrown); + Call_PushCell(attacker); + Call_PushCell(damage); + Call_Finish(); +} +// drawcrown +HandleDrawCrown( attacker, damage, chipdamage ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_DRAWCROWN ) + { + if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 draw-crowned a witch (\x03%i\x01 damage, \x05%i\x01 chip).", attacker, damage, chipdamage ); + } + else { + PrintToChatAll( "A witch was draw-crowned (\x03%i\x01 damage, \x05%i\x01 chip).", damage, chipdamage ); + } + } + + // call forward + Call_StartForward(g_hForwardDrawCrown); + Call_PushCell(attacker); + Call_PushCell(damage); + Call_PushCell(chipdamage); + Call_Finish(); +} + +// smoker clears +HandleTongueCut( attacker, victim ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_TONGUECUT ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 cut \x05%N\x01's tongue.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 cut smoker tongue.", attacker ); + } + } + + // call forward + Call_StartForward(g_hForwardTongueCut); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); +} + +HandleSmokerSelfClear( attacker, victim, bool:withShove = false ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_SELFCLEAR && + (!withShove || GetConVarInt(g_hCvarReport) & REP_SELFCLEARSHOVE ) + ) { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 self-cleared from \x05%N\x01's tongue%s.", attacker, victim, (withShove) ? " by shoving" : "" ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + PrintToChatAll( "\x04%N\x01 self-cleared from a smoker tongue%s.", attacker, (withShove) ? " by shoving" : "" ); + } + } + + // call forward + Call_StartForward(g_hForwardSmokerSelfClear); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(withShove); + Call_Finish(); +} + +// rocks +HandleRockEaten( attacker, victim ) +{ + Call_StartForward(g_hForwardRockEaten); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); +} +HandleRockSkeeted( attacker, victim ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_ROCKSKEET ) + { + /* + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + PrintToChatAll( "\x04%N\x01 skeeted \x05%N\x01's rock.", attacker, victim ); + } + else if ( IS_VALID_INGAME(attacker) ) + { + } + */ + PrintToChatAll( "\x04%N\x01 skeeted a tank rock.", attacker ); + } + + Call_StartForward(g_hForwardRockSkeeted); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_Finish(); +} + +// highpounces +stock HandleHunterDP( attacker, victim, actualDamage, Float:calculatedDamage, Float:height, bool:playerIncapped = false ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) + && GetConVarInt(g_hCvarReportFlags) & REP_HUNTERDP + && height >= GetConVarFloat(g_hCvarHunterDPThresh) + && !playerIncapped + ) { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(attacker) ) + { + PrintToChatAll( "\x04%N\x01 high-pounced \x05%N\x01 (\x03%i\x01 damage, height: \x05%i\x01).", attacker, victim, RoundFloat(calculatedDamage), RoundFloat(height) ); + } + else if ( IS_VALID_INGAME(victim) ) + { + PrintToChatAll( "A hunter high-pounced \x05%N\x01 (\x03%i\x01 damage, height: \x05%i\x01).", victim, RoundFloat(calculatedDamage), RoundFloat(height) ); + } + } + + Call_StartForward(g_hForwardHunterDP); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(actualDamage); + Call_PushFloat(calculatedDamage); + Call_PushFloat(height); + Call_PushCell( (height >= GetConVarFloat(g_hCvarHunterDPThresh)) ? 1 : 0 ); + Call_PushCell( (playerIncapped) ? 1 : 0 ); + Call_Finish(); +} +stock HandleJockeyDP( attacker, victim, Float:height ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) + && GetConVarInt(g_hCvarReportFlags) & REP_JOCKEYDP + && height >= GetConVarFloat(g_hCvarJockeyDPThresh) + ) { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(attacker) ) + { + PrintToChatAll( "\x04%N\x01 jockey high-pounced \x05%N\x01 (height: \x05%i\x01).", attacker, victim, RoundFloat(height) ); + } + else if ( IS_VALID_INGAME(victim) ) + { + PrintToChatAll( "A jockey high-pounced \x05%N\x01 (height: \x05%i\x01).", victim, RoundFloat(height) ); + } + } + + Call_StartForward(g_hForwardJockeyDP); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushFloat(height); + Call_PushCell( (height >= GetConVarFloat(g_hCvarJockeyDPThresh)) ? 1 : 0 ); + Call_Finish(); +} + +// deathcharges +stock HandleDeathCharge( attacker, victim, Float:height, Float:distance, bool:bCarried = true ) +{ + // report? + if ( GetConVarBool(g_hCvarReport) && + GetConVarInt(g_hCvarReportFlags) & REP_DEATHCHARGE && + height >= GetConVarFloat(g_hCvarDeathChargeHeight) + ) { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(attacker) ) + { + PrintToChatAll( "\x04%N\x01 death-charged \x05%N\x01 %s(height: \x05%i\x01).", + attacker, + victim, + (bCarried) ? "" : "by bowling ", + RoundFloat(height) + ); + } + else if ( IS_VALID_INGAME(victim) ) + { + PrintToChatAll( "A charger death-charged \x05%N\x01 %s(height: \x05%i\x01).", + victim, + (bCarried) ? "" : "by bowling ", + RoundFloat(height) + ); + } + } + + Call_StartForward(g_hForwardDeathCharge); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushFloat(height); + Call_PushFloat(distance); + Call_PushCell( (bCarried) ? 1 : 0 ); + Call_Finish(); +} + +// SI clears (cleartimeA = pummel/pounce/ride/choke, cleartimeB = tongue drag, charger carry) +stock HandleClear( attacker, victim, pinVictim, zombieClass, Float:clearTimeA, Float:clearTimeB, bool:bWithShove = false ) +{ + // sanity check: + if ( clearTimeA < 0 && clearTimeA != -1.0 ) { clearTimeA = 0.0; } + if ( clearTimeB < 0 && clearTimeB != -1.0 ) { clearTimeB = 0.0; } + + PrintDebug(0, "Clear: %i freed %i from %i: time: %.2f / %.2f -- class: %s (with shove? %i)", attacker, pinVictim, victim, clearTimeA, clearTimeB, g_csSIClassName[zombieClass], bWithShove ); + + if ( attacker != pinVictim && GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_INSTACLEAR ) + { + new Float: fMinTime = GetConVarFloat(g_hCvarInstaTime); + new Float: fClearTime = clearTimeA; + if ( zombieClass == ZC_CHARGER || zombieClass == ZC_SMOKER ) { fClearTime = clearTimeB; } + + + if ( fClearTime != -1.0 && fClearTime <= fMinTime ) + { + if ( IS_VALID_INGAME(attacker) && IS_VALID_INGAME(victim) && !IsFakeClient(victim) ) + { + if ( IS_VALID_INGAME(pinVictim) ) + { + PrintToChatAll( "\x04%N\x01 insta-cleared \x05%N\x01 from \x04%N\x01 (%s) (%.2f seconds).", + attacker, pinVictim, victim, + g_csSIClassName[zombieClass], + fClearTime + ); + } else { + PrintToChatAll( "\x04%N\x01 insta-cleared a teammate from \x04%N\x01 (%s) (%.2f seconds).", + attacker, victim, + g_csSIClassName[zombieClass], + fClearTime + ); + } + } + else if ( IS_VALID_INGAME(attacker) ) + { + if ( IS_VALID_INGAME(pinVictim) ) + { + PrintToChatAll( "\x04%N\x01 insta-cleared \x05%N\x01 from a %s (%.2f seconds).", + attacker, pinVictim, + g_csSIClassName[zombieClass], + fClearTime + ); + } else { + PrintToChatAll( "\x04%N\x01 insta-cleared a teammate from a %s (%.2f seconds).", + attacker, + g_csSIClassName[zombieClass], + fClearTime + ); + } + } + } + } + + Call_StartForward(g_hForwardClear); + Call_PushCell(attacker); + Call_PushCell(victim); + Call_PushCell(pinVictim); + Call_PushCell(zombieClass); + Call_PushFloat(clearTimeA); + Call_PushFloat(clearTimeB); + Call_PushCell( (bWithShove) ? 1 : 0 ); + Call_Finish(); +} + +// booms +stock HandleVomitLanded( attacker, boomCount ) +{ + Call_StartForward(g_hForwardVomitLanded); + Call_PushCell(attacker); + Call_PushCell(boomCount); + Call_Finish(); +} + +// bhaps +stock HandleBHopStreak( survivor, streak, Float: maxVelocity ) +{ + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_BHOPSTREAK && + IS_VALID_INGAME(survivor) && !IsFakeClient(survivor) && + streak >= GetConVarInt(g_hCvarBHopMinStreak) + ) { + PrintToChatAll( "\x04%N\x01 got \x05%i\x01 bunnyhop%s in a row (top speed: \x05%.1f\x01).", + survivor, + streak, + ( streak > 1 ) ? "s" : "", + maxVelocity + ); + } + + Call_StartForward(g_hForwardBHopStreak); + Call_PushCell(survivor); + Call_PushCell(streak); + Call_PushFloat(maxVelocity); + Call_Finish(); +} +// car alarms +stock HandleCarAlarmTriggered( survivor, infected, reason ) +{ + if ( GetConVarBool(g_hCvarReport) && GetConVarInt(g_hCvarReportFlags) & REP_CARALARM && + IS_VALID_INGAME(survivor) && !IsFakeClient(survivor) + ) { + if ( reason == CALARM_HIT ) { + PrintToChatAll( "\x05%N\x01 triggered an alarm with a hit.", survivor ); + } + else if ( reason == CALARM_TOUCHED ) + { + // if a survivor touches an alarmed car, it might be due to a special infected... + if ( IS_VALID_INFECTED(infected) ) + { + if ( !IsFakeClient(infected) ) + { + PrintToChatAll( "\x04%N\x01 made \x05%N\x01 trigger an alarm.", infected, survivor ); + } + else { + switch ( GetEntProp(infected, Prop_Send, "m_zombieClass") ) + { + case ZC_SMOKER: { PrintToChatAll( "\x01A hunter made \x05%N\x01 trigger an alarm.", survivor ); } + case ZC_JOCKEY: { PrintToChatAll( "\x01A jockey made \x05%N\x01 trigger an alarm.", survivor ); } + case ZC_CHARGER: { PrintToChatAll( "\x01A charger made \x05%N\x01 trigger an alarm.", survivor ); } + default: { PrintToChatAll( "\x01A bot infected made \x05%N\x01 trigger an alarm.", survivor ); } + } + } + } + else + { + PrintToChatAll( "\x05%N\x01 touched an alarmed car.", survivor ); + } + } + else if ( reason == CALARM_EXPLOSION ) { + PrintToChatAll( "\x05%N\x01 triggered an alarm with an explosion.", survivor ); + } + else if ( reason == CALARM_BOOMER ) + { + if ( IS_VALID_INFECTED(infected) && !IsFakeClient(infected) ) + { + PrintToChatAll( "\x05%N\x01 triggered an alarm by killing a boomer \x04%N\x01.", survivor, infected ); + } + else + { + PrintToChatAll( "\x05%N\x01 triggered an alarm by shooting a boomer.", survivor ); + } + } + else { + PrintToChatAll( "\x05%N\x01 triggered an alarm.", survivor ); + } + } + + Call_StartForward(g_hForwardAlarmTriggered); + Call_PushCell(survivor); + Call_PushCell(infected); + Call_PushCell(reason); + Call_Finish(); +} + + +// support +// ------- + +stock GetSurvivorPermanentHealth(client) +{ + return GetEntProp(client, Prop_Send, "m_iHealth"); +} + +stock GetSurvivorTempHealth(client) +{ + new temphp = RoundToCeil( + GetEntPropFloat(client, Prop_Send, "m_healthBuffer") + - ( (GetGameTime() - GetEntPropFloat(client, Prop_Send, "m_healthBufferTime") ) + * GetConVarFloat( FindConVar("pain_pills_decay_rate"))) + ) - 1; + return (temphp > 0 ? temphp : 0); +} + +stock Float: GetSurvivorDistance(client) +{ + return L4D2Direct_GetFlowDistance(client); +} +stock ShiftTankThrower() +{ + new tank = -1; + + if ( !g_iRocksBeingThrownCount ) { return -1; } + + tank = g_iRocksBeingThrown[0]; + + // shift the tank array downwards, if there are more than 1 throwers + if ( g_iRocksBeingThrownCount > 1 ) + { + for ( new x = 1; x <= g_iRocksBeingThrownCount; x++ ) + { + g_iRocksBeingThrown[x-1] = g_iRocksBeingThrown[x]; + } + } + + g_iRocksBeingThrownCount--; + + return tank; +} +/* Height check.. + not required now + maybe for some other 'skill'? +static Float: GetHeightAboveGround( Float:pos[3] ) +{ + // execute Trace straight down + new Handle:trace = TR_TraceRayFilterEx( pos, ANGLE_STRAIGHT_DOWN, MASK_SHOT, RayType_Infinite, ChargeTraceFilter ); + + if (!TR_DidHit(trace)) + { + LogError("Tracer Bug: Trace did not hit anything..."); + } + + decl Float:vEnd[3]; + TR_GetEndPosition(vEnd, trace); // retrieve our trace endpoint + CloseHandle(trace); + + return GetVectorDistance(pos, vEnd, false); +} + +public bool: ChargeTraceFilter (entity, contentsMask) +{ + if ( !entity || !IsValidEntity(entity) ) // dont let WORLD, or invalid entities be hit + { + return false; + } + return true; +} +*/ + +stock PrintDebug(debuglevel, const String:Message[], any:... ) +{ + decl String:DebugBuff[256]; + VFormat(DebugBuff, sizeof(DebugBuff), Message, 3); + LogMessage(DebugBuff); +} +stock bool: IsWitch(entity) +{ + if ( !IsValidEntity(entity) ) { return false; } + + decl String: classname[24]; + new strOEC: classnameOEC; + GetEdictClassname(entity, classname, sizeof(classname)); + if ( !GetTrieValue(g_hTrieEntityCreated, classname, classnameOEC) || classnameOEC != OEC_WITCH ) { return false; } + + return true; +} \ No newline at end of file diff --git a/scripting/l4d2_spawn_props.sp b/scripting/l4d2_spawn_props.sp new file mode 100644 index 0000000..a73ed38 --- /dev/null +++ b/scripting/l4d2_spawn_props.sp @@ -0,0 +1,4417 @@ +#include +#include +#include +#pragma semicolon 1 +#pragma newdecls required +#define DEBUG 0 + +#define GETVERSION "3.4" +#define ARRAY_SIZE 5000 +#define MAX_PATHS 30 + +#define DESIRED_ADM_FLAGS ADMFLAG_UNBAN //Edit here the flags to fit your needs! + +#define RouteType_Easy 0 +#define RouteType_Medium 1 +#define RouteType_Hard 2 + +char FolderNames[][] = { + "addons/stripper", + "addons/stripper/maps", + "addons/stripper/routing", + "addons/stripper/plugin_cache" +}; + +TopMenu g_TopMenuHandle; + +int g_iCategory[MAXPLAYERS+1] = 0; +int g_iSubCategory[MAXPLAYERS+1] = 0; +int g_iFileCategory[MAXPLAYERS+1] = 0; +int g_iMoveCategory[MAXPLAYERS+1] = 0; +int g_iLastObject[MAXPLAYERS+1] = -1; +int g_iLastGrabbedObject[MAXPLAYERS+1] = -1; + +bool g_bSpawned[ARRAY_SIZE] = false; +bool g_bGrabbed[ARRAY_SIZE] = false; +bool g_bGrab[MAXPLAYERS+1] = false; +bool g_bUnsolid[ARRAY_SIZE] = false; +bool g_bLoaded = false; + +float g_vecEntityAngles[ARRAY_SIZE][3]; +float g_vecLastEntityAngles[MAXPLAYERS+1][3]; + +char g_sPath[128]; + +// Global variables to hold menu position +int g_iRotateMenuPosition[MAXPLAYERS+1] = 0; +int g_iMoveMenuPosition[MAXPLAYERS+1] = 0; +int g_iVehiclesMenuPosition[MAXPLAYERS+1] = 0; +int g_iFoliageMenuPosition[MAXPLAYERS+1] = 0; +int g_iFurnitureMenuPosition[MAXPLAYERS+1] = 0; +int g_iFurnishingsMenuPosition[MAXPLAYERS+1] = 0; +int g_iAppliancesMenuPosition[MAXPLAYERS+1] = 0; +int g_iBuildingsMenuPosition[MAXPLAYERS+1] = 0; +int g_iScaffoldingMenuPosition[MAXPLAYERS+1] = 0; +int g_iDoorsMenuPosition[MAXPLAYERS+1] = 0; +int g_iWindowsMenuPosition[MAXPLAYERS+1] = 0; +int g_iLightsMenuPosition[MAXPLAYERS+1] = 0; +int g_iSignssMenuPosition[MAXPLAYERS+1] = 0; +int g_iFencingMenuPosition[MAXPLAYERS+1] = 0; +int g_iRailingMenuPosition[MAXPLAYERS+1] = 0; +int g_iStairsMenuPosition[MAXPLAYERS+1] = 0; +int g_iOfficeMenuPosition[MAXPLAYERS+1] = 0; +int g_iStreetsMenuPosition[MAXPLAYERS+1] = 0; +int g_iFairgroundsMenuPosition[MAXPLAYERS+1] = 0; +int g_iMallMenuPosition[MAXPLAYERS+1] = 0; +int g_iConstructionMenuPosition[MAXPLAYERS+1] = 0; +int g_iGeneralMiscMenuPosition[MAXPLAYERS+1] = 0; +int g_iExteriorMiscMenuPosition[MAXPLAYERS+1] = 0; +int g_iInteriorMiscMenuPosition[MAXPLAYERS+1] = 0; +int g_iDebrisMenuPosition[MAXPLAYERS+1] = 0; +int g_iJunkMenuPosition[MAXPLAYERS+1] = 0; +int g_iPipesMenuPosition[MAXPLAYERS+1] = 0; +int g_iBodiesGenericMenuPosition[MAXPLAYERS+1] = 0; +int g_iBodiesSwampMenuPosition[MAXPLAYERS+1] = 0; +int g_iBodiesSugarMillMenuPosition[MAXPLAYERS+1] = 0; +int g_iBodiesCemetaryMenuPosition[MAXPLAYERS+1] = 0; +int g_iInfectedMenuPosition[MAXPLAYERS+1] = 0; +int g_iSkyboxMenuPosition[MAXPLAYERS+1] = 0; + +ConVar g_cvarPhysics; +ConVar g_cvarDynamic; +ConVar g_cvarStatic; +ConVar g_cvarVehicles; +ConVar g_cvarFoliage; +ConVar g_cvarFurniture; +ConVar g_cvarFurnishings; +ConVar g_cvarAppliances; +ConVar g_cvarBuildings; +ConVar g_cvarScaffolding; +ConVar g_cvarDoors; +ConVar g_cvarWindows; +ConVar g_cvarLights; +ConVar g_cvarSigns; +ConVar g_cvarFencing; +ConVar g_cvarRailing; +ConVar g_cvarStairs; +ConVar g_cvarOffice; +ConVar g_cvarStreets; +ConVar g_cvarFairgrounds; +ConVar g_cvarMall; +ConVar g_cvarConstruction; +ConVar g_cvarGeneralMisc; +ConVar g_cvarExteriorMisc; +ConVar g_cvarInteriorMisc; +ConVar g_cvarDebris; +ConVar g_cvarJunk; +ConVar g_cvarPipes; +ConVar g_cvarBodiesGeneric; +ConVar g_cvarBodiesSwamp; +ConVar g_cvarBodiesSugarMill; +ConVar g_cvarBodiesCemetary; +ConVar g_cvarInfected; +ConVar g_cvarSkybox; +ConVar g_cvarLog; +ConVar g_cvarAutoload; +ConVar g_cvarAutoloadType; + +public Plugin myinfo = +{ + name = "[L4D1/2] Objects Spawner", + author = "honorcode23 & $atanic $pirit & HarryPotter", + description = "Let admins spawn any kind of objects", + version = GETVERSION, + url = "http://forums.alliedmods.net/showthread.php?p=1186503" +} + +bool L4D2Version; +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + EngineVersion test = GetEngineVersion(); + + if( test == Engine_Left4Dead ) + { + L4D2Version = false; + } + else if( test == Engine_Left4Dead2 ) + { + L4D2Version = true; + } + else + { + strcopy(error, err_max, "Plugin only supports Left 4 Dead 1 & 2."); + return APLRes_SilentFailure; + } + + return APLRes_Success; +} + +public void OnPluginStart() +{ + LoadTranslations("l4d2_spawn_props.phrases"); + + CreateConVar("l4d2_spawn_props_version", GETVERSION, "Version of the Plugin", FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY); //Version + g_cvarPhysics = CreateConVar("l4d2_spawn_props_physics", "1", "Enable the Physics Objects in the menu"); + g_cvarDynamic = CreateConVar("l4d2_spawn_props_dynamic", "1", "Enable the Dynamic (Non-solid) Objects in the menu"); + g_cvarStatic = CreateConVar("l4d2_spawn_props_static", "1", "Enable the Static (Solid) Objects in the menu"); + g_cvarVehicles = CreateConVar("l4d2_spawn_props_category_vehicles", "1", "Enable the Vehicles category"); + g_cvarFoliage = CreateConVar("l4d2_spawn_props_category_foliage", "1", "Enable the Foliage category"); + g_cvarFurniture = CreateConVar("l4d2_spawn_props_category_furniture", "1", "Enable the Furniture category"); + g_cvarFurnishings = CreateConVar("l4d2_spawn_props_category_furnishings", "1", "Enable the Furnishings category"); + g_cvarAppliances = CreateConVar("l4d2_spawn_props_category_appliances", "1", "Enable the appliances category"); + g_cvarBuildings = CreateConVar("l4d2_spawn_props_category_buildings", "1", "Enable the Buildings category"); + g_cvarScaffolding = CreateConVar("l4d2_spawn_props_category_scaffolding", "1", "Enable the Scaffolding category"); + g_cvarDoors = CreateConVar("l4d2_spawn_props_category_doors", "1", "Enable the Doors category"); + g_cvarWindows = CreateConVar("l4d2_spawn_props_category_windows", "1", "Enable the Windows category"); + g_cvarLights = CreateConVar("l4d2_spawn_props_category_lights", "1", "Enable the Lights category"); + g_cvarSigns = CreateConVar("l4d2_spawn_props_category_signs", "1", "Enable the Signs category"); + g_cvarFencing = CreateConVar("l4d2_spawn_props_category_fencing", "1", "Enable the Fencing category"); + g_cvarRailing = CreateConVar("l4d2_spawn_props_category_railing", "1", "Enable the Railing category"); + g_cvarStairs = CreateConVar("l4d2_spawn_props_category_stairs", "1", "Enable the Stairs category"); + g_cvarOffice = CreateConVar("l4d2_spawn_props_category_office", "1", "Enable the Office category"); + g_cvarStreets = CreateConVar("l4d2_spawn_props_category_streets", "1", "Enable the Streets category"); + g_cvarFairgrounds = CreateConVar("l4d2_spawn_props_category_fairgrounds", "1", "Enable the Fairgrounds category"); + g_cvarMall = CreateConVar("l4d2_spawn_props_category_mall", "1", "Enable the Mall category"); + g_cvarConstruction = CreateConVar("l4d2_spawn_props_category_construction", "1", "Enable the Construction category"); + g_cvarGeneralMisc = CreateConVar("l4d2_spawn_props_category_generalmisc", "1", "Enable the GeneralMisc category"); + g_cvarExteriorMisc = CreateConVar("l4d2_spawn_props_category_exteriormisc", "1", "Enable the ExteriorMisc category"); + g_cvarInteriorMisc = CreateConVar("l4d2_spawn_props_category_interiormisc", "1", "Enable the InteriorMisc category"); + g_cvarDebris = CreateConVar("l4d2_spawn_props_category_debris", "1", "Enable the Debris category"); + g_cvarJunk = CreateConVar("l4d2_spawn_props_category_junk", "1", "Enable the Junk category"); + g_cvarPipes = CreateConVar("l4d2_spawn_props_category_pipes", "1", "Enable the Pipes category"); + g_cvarBodiesGeneric = CreateConVar("l4d2_spawn_props_category_bodiesgeneric", "1", "Enable the BodiesGeneric category"); + g_cvarBodiesSwamp = CreateConVar("l4d2_spawn_props_category_bodiesswamp", "1", "Enable the BodiesSwamp category"); + g_cvarBodiesSugarMill = CreateConVar("l4d2_spawn_props_category_bodiessugarmill", "1", "Enable the BodiesSugarMill category"); + g_cvarBodiesCemetary = CreateConVar("l4d2_spawn_props_category_bodiescemetary", "1", "Enable the BodiesCemetary category"); + g_cvarInfected = CreateConVar("l4d2_spawn_props_category_infected", "1", "Enable the Infected category"); + g_cvarSkybox = CreateConVar("l4d2_spawn_props_category_skybox", "1", "Enable the Skybox category"); + g_cvarLog = CreateConVar("l4d2_spawn_props_log_actions", "0", "Log if an admin spawns an object?"); + g_cvarAutoload = CreateConVar("l4d2_spawn_props_autoload", "0", "Enable the plugin to auto load the cache?"); + g_cvarAutoloadType = CreateConVar("l4d2_spawn_props_autoload_different", "1", "Should the paths be different for the teams or not?"); + + RegAdminCmd("sm_spawnprop", CmdSpawnProp, DESIRED_ADM_FLAGS, "Spawns an object with the given information"); + RegAdminCmd("sm_savemap", CmdSaveMap, DESIRED_ADM_FLAGS, "Save all the spawned object in a stripper file"); + + RegAdminCmd("sm_prop_rotate", CmdRotate, DESIRED_ADM_FLAGS, "Rotates the last spawned object with the desired angles"); + RegAdminCmd("sm_prop_removelast", CmdRemoveLast, DESIRED_ADM_FLAGS, "Remove last spawned object"); + RegAdminCmd("sm_prop_removelook", CmdRemoveLook, DESIRED_ADM_FLAGS, "Remove the looking object"); + RegAdminCmd("sm_prop_removeall", CmdRemoveAll, DESIRED_ADM_FLAGS, "Remove all objects"); + RegAdminCmd("sm_prop_move", CmdMove, DESIRED_ADM_FLAGS, "Move an object with the desired movement type"); + RegAdminCmd("sm_prop_setang", CmdSetAngles, DESIRED_ADM_FLAGS, "Forces an object angles"); + RegAdminCmd("sm_prop_setpos", CmdSetPosition, DESIRED_ADM_FLAGS, "Sets the last object position"); + + RegAdminCmd("sm_debugprop", CmdDebugProp, ADMFLAG_ROOT, "DEBUG"); + + + AutoExecConfig(true, "l4d2_spawn_props"); + TopMenu topMenu; + if (LibraryExists("adminmenu") && ((topMenu = GetAdminTopMenu()) != null)) { + OnAdminMenuReady(topMenu); + } + + //DEV + RegAdminCmd("sm_spload", CmdLoad, DESIRED_ADM_FLAGS, "Load map"); + + //Events + if(L4D2Version) + { + HookEvent("survival_round_start", Event_SurvivalRoundStart); + HookEvent("scavenge_round_start", Event_ScavengeRoundStart); + } + HookEvent("round_start_post_nav", Event_RoundStart); + HookEvent("round_end", Event_RoundEnd); + + //Create required folders + BuildFileDirectories(); +} + + +public Action CmdDebugProp(int client, int args) +{ + char name[256]; + int Object = g_iLastObject[client]; + if(Object > 0 && IsValidEntity(Object)) + { + GetEntPropString(Object, Prop_Data, "m_iName", name, sizeof(name)); + PrintToChat(client, "prop: %s", name); + } + return Plugin_Handled; +} + +public void Event_SurvivalRoundStart(Event hEvent, const char[] sEventName, bool bDontBroadcast) +{ + if(g_cvarAutoload.BoolValue && !g_bLoaded) + { + g_bLoaded = true; + SpawnObjects(); + } +} + +public void Event_ScavengeRoundStart(Event hEvent, const char[] sEventName, bool bDontBroadcast) +{ + LogSpawn("Scavenge Round Has Started"); + if(g_cvarAutoload.BoolValue && !g_bLoaded) + { + g_bLoaded = true; + SpawnObjects(); + } +} +public void Event_RoundStart(Event hEvent, const char[] sEventName, bool bDontBroadcast) +{ + if(g_cvarAutoload.BoolValue && g_cvarAutoloadType.BoolValue) + { + GetRandomMapPath(g_sPath, sizeof(g_sPath)); + } + LogSpawn("Normal Round Has Started"); + if(g_cvarAutoload.BoolValue && !g_bLoaded) + { + g_bLoaded = true; + SpawnObjects(); + } +} + +public void Event_RoundEnd(Event hEvent, const char[] sEventName, bool bDontBroadcast) +{ + g_bLoaded = false; +} + +public void OnMapEnd() +{ + g_bLoaded = false; +} + +public void OnMapStart() +{ + for(int i=MaxClients; i < ARRAY_SIZE; i++) + { + g_bSpawned[i] = false; + g_bUnsolid[i] = false; + g_vecEntityAngles[i][0] = 0.0; + g_vecEntityAngles[i][1] = 0.0; + g_vecEntityAngles[i][2] = 0.0; + } + if(g_cvarAutoload.BoolValue && !g_cvarAutoloadType.BoolValue) + { + GetRandomMapPath(g_sPath, sizeof(g_sPath)); + } +} + +public Action CmdSpawnProp(int client, int args) +{ + if(args < 3) + { + PrintToChat(client, "[SM] Usage: sm_spawnprop [static | dynamic | physics] [cursor | origin]"); + return Plugin_Handled; + } + char arg1[256]; + char arg2[256]; + char arg3[256]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + char model[256]; + strcopy(model, sizeof(model), arg1); + if(!IsModelPrecached(model)) + { + if(PrecacheModel(model) <= 0) + { + PrintToChat(client, "[SM] There was a problem spawning the selected model [ERROR: Invalid Model]"); + return Plugin_Handled; + } + } + if(StrContains(arg2, "static") >= 0) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + SetEntProp(prop, Prop_Send, "m_nSolidType", 6); + if(strcmp(arg3, "cursor") == 0) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, client); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(client, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + } + else if(strcmp(arg3, "origin") == 0) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + } + else + { + PrintToChat(client, "[SM] Invalid spawn method specified. Use: [cursor | origin]"); + return Plugin_Handled; + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[client][0] = VecAngles[0]; + g_vecLastEntityAngles[client][1] = VecAngles[1]; + g_vecLastEntityAngles[client][2] = VecAngles[2]; + g_iLastObject[client] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(client, name, sizeof(name)); + LogSpawn("%s spawned a static object with model <%s>", name, model); + } + else if(StrContains(arg2, "dynamic") >= 0) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + if(strcmp(arg3, "cursor") == 0 ) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, client); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(client, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + } + else if(strcmp(arg3, "origin")== 0) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + } + else + { + PrintToChat(client, "[SM] Invalid spawn method specified. Use: [cursor | origin]"); + return Plugin_Handled; + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[client][0] = VecAngles[0]; + g_vecLastEntityAngles[client][1] = VecAngles[1]; + g_vecLastEntityAngles[client][2] = VecAngles[2]; + g_iLastObject[client] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + g_bUnsolid[prop] = true; + char name[256]; + GetClientName(client, name, sizeof(name)); + LogSpawn("%s spawned a dynamic object with model <%s>", name, model); + } + else if(StrContains(arg2, "physics") >= 0) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_physics_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + if(strcmp(arg3, "cursor")== 0) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, client); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(client, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + } + else if(strcmp(arg3, "origin")== 0) + { + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + } + else + { + PrintToChat(client, "[SM] Invalid spawn method specified. Use: [cursor | origin]"); + return Plugin_Handled; + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[client][0] = VecAngles[0]; + g_vecLastEntityAngles[client][1] = VecAngles[1]; + g_vecLastEntityAngles[client][2] = VecAngles[2]; + g_iLastObject[client] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(client, name, sizeof(name)); + LogSpawn("%s spawned a physics object with model <%s>", name, model); + } + else + { + PrintToChat(client, "[SM] Invalid render mode. Use: [static | dynamic | physics]"); + return Plugin_Handled; + } + return Plugin_Handled; +} + +//Admin Menu ready +public void OnAdminMenuReady(Handle topmenu) +{ + if (topmenu == g_TopMenuHandle) + { + return; + } + g_TopMenuHandle = view_as(topmenu); + TopMenuObject menu_category_prop = g_TopMenuHandle.AddCategory("Object Spawner", Category_Handler); + + if (menu_category_prop != INVALID_TOPMENUOBJECT) + { + g_TopMenuHandle.AddItem("sm_spdelete", AdminMenu_Delete, menu_category_prop, "sm_spdelete", DESIRED_ADM_FLAGS); //Delete + g_TopMenuHandle.AddItem("sm_spedit", AdminMenu_Edit, menu_category_prop, "sm_spedit", DESIRED_ADM_FLAGS); //Edit + g_TopMenuHandle.AddItem("sm_spspawn", AdminMenu_Spawn, menu_category_prop, "sm_spspawn", DESIRED_ADM_FLAGS); //Spawn + g_TopMenuHandle.AddItem("sm_spsave", AdminMenu_Save, menu_category_prop, "sm_spsave", DESIRED_ADM_FLAGS); //Save + g_TopMenuHandle.AddItem("sm_spload", AdminMenu_Load, menu_category_prop, "sm_spload", DESIRED_ADM_FLAGS); //Load + } +} + +//Admin Category Name +public int Category_Handler(TopMenu topmenu, TopMenuAction action, TopMenuObject topobj_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayTitle) + { + Format(buffer, maxlength, Translate(param, "%t", "Select a task:")); + } + else if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, "Spawn Objects (Old)"); + } +} +/* +////////////////////////////////////////////////////////////////////////////| + D E L E T E M E N U | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void AdminMenu_Delete(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, Translate(param, "%t", "Delete Object")); + } + else if(action == TopMenuAction_SelectOption) + { + BuildDeleteMenu(param); + } +} + +Menu BuildDeleteMenu(int client) +{ + Menu menu = new Menu(MenuHandler_Delete); + menu.SetTitle("%T", "Select the delete task", client); + menu.AddItem("sm_spdeleteall", Translate(client, "%t", "Delete All Objects")); + menu.AddItem("sm_spdeletelook", Translate(client, "%t", "Delete Looking Object")); + menu.AddItem("sm_spdeletelast", Translate(client, "%t", "Delete Last Object")); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +Menu BuildDeleteAllAskMenu(int client) +{ + Menu menu = new Menu(MenuHandler_DA_Ask); + menu.SetTitle("%T", "Are you sure(Delete All)?", client); + menu.AddItem("sm_spyes", Translate(client, "%t", "Yes")); + menu.AddItem("sm_spno", Translate(client, "%t", "No")); + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_DA_Ask(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spyes")== 0) + { + DeleteAllProps(); + PrintToChat(param1, "[SM] %T", "Successfully deleted all spawned objects", param1); + } + else + { + PrintToChat(param1, "[SM] %T", "Canceled", param1); + } + BuildDeleteMenu(param1); + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_Delete(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spdeleteall")== 0) + { + BuildDeleteAllAskMenu(param1); + PrintToChat(param1, "[SM] %T", "delete all the spawned objects?", param1); + } + else if(strcmp(menucmd, "sm_spdeletelook")== 0) + { + DeleteLookingEntity(param1); + BuildDeleteMenu(param1); + } + else if(strcmp(menucmd, "sm_spdeletelast")== 0) + { + DeleteLastProp(param1); + BuildDeleteMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +/* +////////////////////////////////////////////////////////////////////////////| + E D I T M E N U | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void AdminMenu_Edit(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, Translate(param, "%t", "Edit Object")); + } + else if(action == TopMenuAction_SelectOption) + { + BuildEditPropMenu(param); + } +} + +/* +////////////////////////////////////////////////////////////////////////////| + S P A W N M E N U | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void AdminMenu_Spawn(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, Translate(param, "%t", "Spawn Objects")); + } + else if(action == TopMenuAction_SelectOption) + { + ConVar cheats = FindConVar("sm_cheats"); + if(cheats != null && !cheats.BoolValue) { + ReplyToCommand(param, "Set sm_cheats to 1 to use the prop spawner"); + return; + } + BuildSpawnMenu(param); + } +} + +Menu BuildSpawnMenu(int client) +{ + Menu menu = new Menu(MenuHandler_Spawn); + menu.SetTitle("%T", "Select the spawn method", client); + + if(g_cvarPhysics.BoolValue) + { + menu.AddItem("sm_spawnpc", Translate(client, "%t", "Spawn Physics On Cursor")); + menu.AddItem("sm_spawnpo", Translate(client, "%t", "Spawn Physics On Origin")); + } + if(g_cvarDynamic.BoolValue) + { + menu.AddItem("sm_spawndc", Translate(client, "%t", "Spawn Non-solid On Cursor")); + menu.AddItem("sm_spawndo", Translate(client, "%t", "Spawn Non-solid On Origin")); + } + if(g_cvarStatic.BoolValue) + { + menu.AddItem("sm_spawnsc", Translate(client, "%t", "Spawn Solid On Cursor")); + menu.AddItem("sm_spawnso", Translate(client, "%t", "Spawn Solid On Origin")); + } + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_Spawn(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spawnpc")== 0) + { + BuildPhysicsCursorMenu(param1); + } + else if(strcmp(menucmd, "sm_spawnpo")== 0) + { + BuildPhysicsPositionMenu(param1); + } + else if(strcmp(menucmd, "sm_spawndc")== 0) + { + BuildDynamicCursorMenu(param1); + } + else if(strcmp(menucmd, "sm_spawndo")== 0) + { + BuildDynamicPositionMenu(param1); + } + else if(strcmp(menucmd, "sm_spawnsc")== 0) + { + BuildStaticCursorMenu(param1); + } + else if(strcmp(menucmd, "sm_spawnso")== 0) + { + BuildStaticPositionMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +/* +////////////////////////////////////////////////////////////////////////////| + S A V E M E N U | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void AdminMenu_Save(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, Translate(param, "%t", "Save Objects")); + } + else if(action == TopMenuAction_SelectOption) + { + BuildSaveMenu(param); + } +} + +Menu BuildSaveMenu(int client) +{ + Menu menu = new Menu(MenuHandler_Save); + menu.SetTitle("%T", "Select The Save Method", client); + menu.AddItem("sm_spsavestripper", Translate(client, "%t", "Save Stripper File")); + menu.AddItem("sm_spsaverouting", Translate(client, "%t", "Save Routing File")); + menu.AddItem("sm_spsaveplugin", Translate(client, "%t", "Save Spawn Objects File")); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +Menu BuildRoutingMenu(int client) +{ + Menu menu = new Menu(MenuHandler_PathDiff); + menu.SetTitle("%T", "Select Path Difficulty", client); + menu.AddItem("sm_speasy", Translate(client, "%t", "Easy Path")); + menu.AddItem("sm_spmedium", Translate(client, "%t", "Medium Path")); + menu.AddItem("sm_sphard", Translate(client, "%t", "Hard Path")); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_PathDiff(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_speasy")== 0) + { + SaveRoutingPath(param1, RouteType_Easy); + } + else if(strcmp(menucmd, "sm_spmedium")== 0) + { + SaveRoutingPath(param1, RouteType_Medium); + } + else if(strcmp(menucmd, "sm_sphard")== 0) + { + SaveRoutingPath(param1, RouteType_Hard); + } + BuildSaveMenu(param1); + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_Save(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spsavestripper")== 0) + { + SaveMapStripper(param1); + BuildSaveMenu(param1); + } + else if(strcmp(menucmd, "sm_spsaverouting")== 0) + { + BuildRoutingMenu(param1); + } + else if(strcmp(menucmd, "sm_spsaveplugin")== 0) + { + SavePluginProps(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +/* +////////////////////////////////////////////////////////////////////////////| + L O A D M E N U | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void AdminMenu_Load(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) +{ + if(action == TopMenuAction_DisplayOption) + { + Format(buffer, maxlength, Translate(param, "%t", "Load Objects")); + } + else if(action == TopMenuAction_SelectOption) + { + BuildLoadAskMenu(param); + PrintToChat(param, "[SM] %T", "load the map data cache?", param); + } +} + +Menu BuildLoadAskMenu(int client) +{ + Menu menu = new Menu(MenuHandler_Load_Ask); + menu.SetTitle("%T", "Are you sure?", client); + menu.AddItem("sm_spyes", Translate(client, "%t", "Yes")); + menu.AddItem("sm_spno", Translate(client, "%t", "No")); + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +Menu BuildLoadPropsMenu(int client) +{ + Menu menu = new Menu(MenuHandler_Load_Props); + menu.SetTitle("%T", "Choose a map number please", client); + char buffer[16]; + char buffer2[16]; + for(int i=1; i <= MAX_PATHS; i++) + { + Format(buffer, sizeof(buffer), "map%i", i); + Format(buffer2, sizeof(buffer2), "Map %i", i); + menu.AddItem(buffer, buffer2); + } + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_Load_Props(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + ReplaceString(menucmd, sizeof(menucmd), "map", "", false); + int number = StringToInt(menucmd); + LoadPluginProps(param1, number); + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_Load_Ask(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spyes")== 0) + { + BuildLoadPropsMenu(param1); + } + else + { + PrintToChat(param1, "[SM] %T", "Canceled", param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +/* +////////////////////////////////////////////////////////////////////////////| + Build Secondary Menus | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ +Menu BuildPhysicsCursorMenu(int client) +{ + Menu menu = new Menu(MenuHandler_PhysicsCursor); + CheckSecondaryMenuCategories(menu, client); +} + +Menu BuildPhysicsPositionMenu(int client) +{ + Menu menu = new Menu(MenuHandler_PhysicsPosition); + CheckSecondaryMenuCategories(menu, client); +} + +Menu BuildDynamicCursorMenu(int client) +{ + Menu menu = new Menu(MenuHandler_DynamicCursor); + CheckSecondaryMenuCategories(menu, client); +} + +Menu BuildDynamicPositionMenu(int client) +{ + Menu menu = new Menu(MenuHandler_DynamicPosition); + CheckSecondaryMenuCategories(menu, client); +} +Menu BuildStaticCursorMenu(int client) +{ + Menu menu = new Menu(MenuHandler_StaticCursor); + CheckSecondaryMenuCategories(menu, client); +} +Menu BuildStaticPositionMenu(int client) +{ + Menu menu = new Menu(MenuHandler_StaticPosition); + CheckSecondaryMenuCategories(menu, client); +} + +Menu CheckSecondaryMenuCategories(Menu menu, int client) +{ + if(g_cvarVehicles.BoolValue) + { + menu.AddItem("vehicles", Translate(client, "%t", "Vehicles")); + } + if(g_cvarFoliage.BoolValue) + { + menu.AddItem("foliage", Translate(client, "%t", "Foliage")); + } + if(g_cvarFurniture.BoolValue) + { + menu.AddItem("furniture", Translate(client, "%t", "Furniture")); + } + if(g_cvarFurnishings.BoolValue) + { + menu.AddItem("furnishings", Translate(client, "%t", "Furnishings")); + } + if(g_cvarAppliances.BoolValue) + { + menu.AddItem("appliances", Translate(client, "%t", "Appliances")); + } + if(g_cvarBuildings.BoolValue) + { + menu.AddItem("buildings", Translate(client, "%t", "Buildings")); + } + if(g_cvarScaffolding.BoolValue) + { + menu.AddItem("scaffolding", Translate(client, "%t", "Scaffolding")); + } + if(g_cvarDoors.BoolValue) + { + menu.AddItem("doors", Translate(client, "%t", "Doors")); + } + if(g_cvarWindows.BoolValue) + { + menu.AddItem("windows", Translate(client, "%t", "Windows")); + } + if(g_cvarLights.BoolValue) + { + menu.AddItem("lights", Translate(client, "%t", "Lights")); + } + if(g_cvarSigns.BoolValue) + { + menu.AddItem("signs", Translate(client, "%t", "Signs")); + } + if(g_cvarFencing.BoolValue) + { + menu.AddItem("fencing", Translate(client, "%t", "Fencing")); + } + if(g_cvarRailing.BoolValue) + { + menu.AddItem("railing", Translate(client, "%t", "Railing")); + } + if(g_cvarStairs.BoolValue) + { + menu.AddItem("stairs", Translate(client, "%t", "Stairs")); + } + if(g_cvarOffice.BoolValue) + { + menu.AddItem("office", Translate(client, "%t", "Office")); + } + if(g_cvarStreets.BoolValue) + { + menu.AddItem("streets", Translate(client, "%t", "Streets")); + } + if(g_cvarFairgrounds.BoolValue) + { + menu.AddItem("fairgrounds", Translate(client, "%t", "Fairgrounds")); + } + if(g_cvarMall.BoolValue) + { + menu.AddItem("mall", Translate(client, "%t", "Mall")); + } + if(g_cvarConstruction.BoolValue) + { + menu.AddItem("construction", Translate(client, "%t", "Construction")); + } + if(g_cvarGeneralMisc.BoolValue) + { + menu.AddItem("generalmisc", Translate(client, "%t", "GeneralMisc")); + } + if(g_cvarExteriorMisc.BoolValue) + { + menu.AddItem("exteriormisc", Translate(client, "%t", "ExteriorMisc")); + } + if(g_cvarInteriorMisc.BoolValue) + { + menu.AddItem("interiormisc", Translate(client, "%t", "InteriorMisc")); + } + if(g_cvarDebris.BoolValue) + { + menu.AddItem("debris", Translate(client, "%t", "Debris")); + } + if(g_cvarJunk.BoolValue) + { + menu.AddItem("junk", Translate(client, "%t", "Junk")); + } + if(g_cvarPipes.BoolValue) + { + menu.AddItem("pipes", Translate(client, "%t", "Pipes")); + } + if(g_cvarBodiesGeneric.BoolValue) + { + menu.AddItem("bodiesgeneric", Translate(client, "%t", "BodiesGeneric")); + } + if(g_cvarBodiesSwamp.BoolValue) + { + menu.AddItem("bodiesswamp", Translate(client, "%t", "BodiesSwamp")); + } + if(g_cvarBodiesSugarMill.BoolValue) + { + menu.AddItem("BodiesSugarMill", Translate(client, "%t", "BodiesSugarMill")); + } + if(g_cvarBodiesCemetary.BoolValue) + { + menu.AddItem("bodiescemetary", Translate(client, "%t", "BodiesCemetary")); + } + if(g_cvarInfected.BoolValue) + { + menu.AddItem("infected", Translate(client, "%t", "Infected")); + } + if(g_cvarSkybox.BoolValue) + { + menu.AddItem("skybox", Translate(client, "%t", "Skybox")); + } + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +Menu BuildEditPropMenu(int client) +{ + Menu menu = new Menu(MenuHandler_EditProp); + menu.SetTitle("%T", "Select an action:", client); + menu.AddItem("rotate", Translate(client, "%t", "Rotate")); + menu.AddItem("move", Translate(client, "%t", "Move")); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_PhysicsCursor(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 1; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_PhysicsPosition(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 2; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_DynamicCursor(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 3; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_DynamicPosition(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 4; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_StaticCursor(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 5; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_StaticPosition(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + g_iCategory[param1] = 6; + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "vehicles")== 0) + { + DisplayVehiclesMenu(param1); + } + else if(strcmp(menucmd, "foliage")== 0) + { + DisplayFoliageMenu(param1); + } + else if(strcmp(menucmd, "furniture")== 0) + { + DisplayFurnitureMenu(param1); + } + else if(strcmp(menucmd, "furnishings")== 0) + { + DisplayFurnishingsMenu(param1); + } + else if(strcmp(menucmd, "appliances")== 0) + { + DisplayAppliancesMenu(param1); + } + else if(strcmp(menucmd, "buildings")== 0) + { + DisplayBuildingsMenu(param1); + } + else if(strcmp(menucmd, "scaffolding")== 0) + { + DisplayScaffoldingMenu(param1); + } + else if(strcmp(menucmd, "doors")== 0) + { + DisplayDoorsMenu(param1); + } + else if(strcmp(menucmd, "windows")== 0) + { + DisplayWindowsMenu(param1); + } + else if(strcmp(menucmd, "lights")== 0) + { + DisplayLightsMenu(param1); + } + else if(strcmp(menucmd, "signs")== 0) + { + DisplaySignsMenu(param1); + } + else if(strcmp(menucmd, "fencing")== 0) + { + DisplayFencingMenu(param1); + } + else if(strcmp(menucmd, "railing")== 0) + { + DisplayRailingMenu(param1); + } + else if(strcmp(menucmd, "stairs")== 0) + { + DisplayStairsMenu(param1); + } + else if(strcmp(menucmd, "office")== 0) + { + DisplayOfficeMenu(param1); + } + else if(strcmp(menucmd, "streets")== 0) + { + DisplayStreetsMenu(param1); + } + else if(strcmp(menucmd, "fairgrounds")== 0) + { + DisplayFairgroundsMenu(param1); + } + else if(strcmp(menucmd, "mall")== 0) + { + DisplayMallMenu(param1); + } + else if(strcmp(menucmd, "construction")== 0) + { + DisplayConstructionMenu(param1); + } + else if(strcmp(menucmd, "generalmisc")== 0) + { + DisplayGeneralMiscMenu(param1); + } + else if(strcmp(menucmd, "exteriormisc")== 0) + { + DisplayExteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "interiormisc")== 0) + { + DisplayInteriorMiscMenu(param1); + } + else if(strcmp(menucmd, "debris")== 0) + { + DisplayDebrisMenu(param1); + } + else if(strcmp(menucmd, "junk")== 0) + { + DisplayJunkMenu(param1); + } + else if(strcmp(menucmd, "pipes")== 0) + { + DisplayPipesMenu(param1); + } + else if(strcmp(menucmd, "bodiesgeneric")== 0) + { + DisplayBodiesGenericMenu(param1); + } + else if(strcmp(menucmd, "bodiesswamp")== 0) + { + DisplayBodiesSwampMenu(param1); + } + else if(strcmp(menucmd, "BodiesSugarMill")== 0) + { + DisplayBodiesSugarMill(param1); + } + else if(strcmp(menucmd, "bodiescemetary")== 0) + { + DisplayBodiesCemetaryMenu(param1); + } + else if(strcmp(menucmd, "infected")== 0) + { + DisplayInfectedMenu(param1); + } + else if(strcmp(menucmd, "skybox")== 0) + { + DisplaySkyboxMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_EditProp(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "rotate")== 0) + { + DisplayRotateMenu(param1); + } + else if(strcmp(menucmd, "move")== 0) + { + DisplayMoveMenu(param1); + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack && g_TopMenuHandle != null) + { + g_TopMenuHandle.Display(param1, TopMenuPosition_LastCategory); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +Menu DisplayVehiclesMenu(int client) +{ + g_iSubCategory[client] = 1; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Vehicles", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iVehiclesMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayFoliageMenu(int client) +{ + g_iSubCategory[client] = 2; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Foliage", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iFoliageMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayFurnitureMenu(int client) +{ + g_iSubCategory[client] = 3; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Furniture", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iFurnitureMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayFurnishingsMenu(int client) +{ + g_iSubCategory[client] = 4; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Furnishings", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iFurnishingsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayAppliancesMenu(int client) +{ + g_iSubCategory[client] = 5; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Appliances", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iAppliancesMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayBuildingsMenu(int client) +{ + g_iSubCategory[client] = 6; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Buildings", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iBuildingsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayScaffoldingMenu(int client) +{ + g_iSubCategory[client] = 7; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Scaffolding", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iScaffoldingMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayDoorsMenu(int client) +{ + g_iSubCategory[client] = 8; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Doors", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iDoorsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayWindowsMenu(int client) +{ + g_iSubCategory[client] = 9; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Windows", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iWindowsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayLightsMenu(int client) +{ + g_iSubCategory[client] = 10; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Lights", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iLightsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplaySignsMenu(int client) +{ + g_iSubCategory[client] = 11; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Signs", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iSignssMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayFencingMenu(int client) +{ + g_iSubCategory[client] = 12; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Fencing", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iFencingMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayRailingMenu(int client) +{ + g_iSubCategory[client] = 13; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Railing", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iRailingMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayStairsMenu(int client) +{ + g_iSubCategory[client] = 14; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Stairs", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iStairsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayOfficeMenu(int client) +{ + g_iSubCategory[client] = 15; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Office", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iOfficeMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayStreetsMenu(int client) +{ + g_iSubCategory[client] = 16; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Streets", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iStreetsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayFairgroundsMenu(int client) +{ + g_iSubCategory[client] = 17; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Fairgrounds", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iFairgroundsMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayMallMenu(int client) +{ + g_iSubCategory[client] = 18; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Mall", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iMallMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayConstructionMenu(int client) +{ + g_iSubCategory[client] = 19; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Construction", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iConstructionMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayGeneralMiscMenu(int client) +{ + g_iSubCategory[client] = 20; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "GeneralMisc", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iGeneralMiscMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayExteriorMiscMenu(int client) +{ + g_iSubCategory[client] = 21; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "ExteriorMisc", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iExteriorMiscMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayInteriorMiscMenu(int client) +{ + g_iSubCategory[client] = 22; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "InteriorMisc", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iInteriorMiscMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayDebrisMenu(int client) +{ + g_iSubCategory[client] = 23; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Debris", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iDebrisMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayJunkMenu(int client) +{ + g_iSubCategory[client] = 24; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Junk", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iJunkMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayPipesMenu(int client) +{ + g_iSubCategory[client] = 1; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Pipes", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iPipesMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayBodiesGenericMenu(int client) +{ + g_iSubCategory[client] = 25; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "BodiesGeneric", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iBodiesGenericMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayBodiesSwampMenu(int client) +{ + g_iSubCategory[client] = 26; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "BodiesSwamp", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iBodiesSwampMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayBodiesSugarMill(int client) +{ + g_iSubCategory[client] = 27; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "BodiesSugarMill", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iBodiesSugarMillMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayBodiesCemetaryMenu(int client) +{ + g_iSubCategory[client] = 28; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "BodiesCemetary", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iBodiesCemetaryMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayInfectedMenu(int client) +{ + g_iSubCategory[client] = 29; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Infected", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iInfectedMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplaySkyboxMenu(int client) +{ + g_iSubCategory[client] = 1; + Menu menu = new Menu(MenuHandler_DoAction); + SetFileCategory(menu, client); + menu.SetTitle("%T", "Skybox", client); + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iSkyboxMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu SetFileCategory(Menu menu, int client) +{ + File file; + char FileName[256]; + char ItemModel[256]; + char ItemTag[256]; + char buffer[256]; + BuildPath(Path_SM, FileName, sizeof(FileName), "data/l4d2_spawn_props_models.txt"); + int len; + if(!FileExists(FileName)) + { + SetFailState("Unable to find the l4d2_spawn_props_models.txt file"); + } + file = OpenFile(FileName, "r"); + if(file == null) + { + SetFailState("Error opening the models file"); + } + g_iFileCategory[client] = 0; + while(file.ReadLine(buffer, sizeof(buffer))) + { + len = strlen(buffer); + if (buffer[len-1] == 'n') + { + buffer[--len] = '0'; + } + if(StrContains(buffer, "//Category Vehicles") >= 0) + { + g_iFileCategory[client] = 1; + continue; + } + else if(StrContains(buffer, "//Category Foliage") >= 0) + { + g_iFileCategory[client] = 2; + continue; + } + else if(StrContains(buffer, "//Category Furniture") >= 0) + { + g_iFileCategory[client] = 3; + continue; + } + if(StrContains(buffer, "//Category Furnishings") >= 0) + { + g_iFileCategory[client] = 4; + continue; + } + else if(StrContains(buffer, "//Category Appliances") >= 0) + { + g_iFileCategory[client] = 5; + continue; + } + if(StrContains(buffer, "//Category Buildings") >= 0) + { + g_iFileCategory[client] = 6; + continue; + } + if(StrContains(buffer, "//Category Scaffolding") >= 0) + { + g_iFileCategory[client] = 7; + continue; + } + if(StrContains(buffer, "//Category Doors") >= 0) + { + g_iFileCategory[client] = 8; + continue; + } + if(StrContains(buffer, "//Category Windows") >= 0) + { + g_iFileCategory[client] = 9; + continue; + } + if(StrContains(buffer, "//Category Lights") >= 0) + { + g_iFileCategory[client] = 10; + continue; + } + else if(StrContains(buffer, "//Category Signs") >= 0) + { + g_iFileCategory[client] = 11; + continue; + } + if(StrContains(buffer, "//Category Fencing") >= 0) + { + g_iFileCategory[client] = 12; + continue; + } + if(StrContains(buffer, "//Category Railing") >= 0) + { + g_iFileCategory[client] = 13; + continue; + } + if(StrContains(buffer, "//Category Stairs") >= 0) + { + g_iFileCategory[client] = 14; + continue; + } + else if(StrContains(buffer, "//Category Office") >= 0) + { + g_iFileCategory[client] = 15; + continue; + } + else if(StrContains(buffer, "//Category Streets") >= 0) + { + g_iFileCategory[client] = 16; + continue; + } + else if(StrContains(buffer, "//Category Fairgrounds") >= 0) + { + g_iFileCategory[client] = 17; + continue; + } + else if(StrContains(buffer, "//Category Mall") >= 0) + { + g_iFileCategory[client] = 18; + continue; + } + else if(StrContains(buffer, "//Category Construction") >= 0) + { + g_iFileCategory[client] = 19; + continue; + } + else if(StrContains(buffer, "//Category GeneralMisc") >= 0) + { + g_iFileCategory[client] = 20; + continue; + } + else if(StrContains(buffer, "//Category ExteriorMisc") >= 0) + { + g_iFileCategory[client] = 21; + continue; + } + else if(StrContains(buffer, "//Category InteriorMisc") >= 0) + { + g_iFileCategory[client] = 22; + continue; + } + else if(StrContains(buffer, "//Category Debris") >= 0) + { + g_iFileCategory[client] = 23; + continue; + } + else if(StrContains(buffer, "//Category Junk") >= 0) + { + g_iFileCategory[client] = 24; + continue; + } + else if(StrContains(buffer, "//Category Pipes") >= 0) + { + g_iFileCategory[client] = 25; + continue; + } + else if(StrContains(buffer, "//Category BodiesGeneric") >= 0) + { + g_iFileCategory[client] = 26; + continue; + } + else if(StrContains(buffer, "//Category BodiesSwamp") >= 0) + { + g_iFileCategory[client] = 27; + continue; + } + else if(StrContains(buffer, "//Category BodiesSugarMill") >= 0) + { + g_iFileCategory[client] = 28; + continue; + } + else if(StrContains(buffer, "//Category BodiesCemetary") >= 0) + { + g_iFileCategory[client] = 29; + continue; + } + else if(StrContains(buffer, "//Category Infected") >= 0) + { + g_iFileCategory[client] = 30; + continue; + } + else if(StrContains(buffer, "//Category Skybox") >= 0) + { + g_iFileCategory[client] = 31; + continue; + } + if(strcmp(buffer, "")== 0) + { + continue; + } + if(g_iFileCategory[client] != g_iSubCategory[client]) + { + continue; + } + SplitString(buffer, " TAG-", ItemModel, sizeof(ItemModel)); + + strcopy(ItemTag, sizeof(ItemTag), buffer); + + ReplaceString(ItemTag, sizeof(ItemTag), ItemModel, "", false); + ReplaceString(ItemTag, sizeof(ItemTag), " TAG- ", "", false); + menu.AddItem(ItemModel, ItemTag); + + if(IsEndOfFile(file)) + { + break; + } + } + CloseHandle(file); +} + +Menu DisplayRotateMenu(int client) +{ + g_iMoveCategory[client] = 1; + Menu menu = new Menu(MenuHandler_PropPosition); + menu.SetTitle("%T", "Rotate", client); + menu.AddItem("rotate1x", Translate(client, "%t", "Rotate 1 degree (X axys)")); + menu.AddItem("rotate-1x", Translate(client, "%t", "Back 1 degree (X axys)")); + menu.AddItem("rotate10x", Translate(client, "%t", "Rotate 10 degree (X axys)")); + menu.AddItem("rotate-10x", Translate(client, "%t", "Back 10 degree (X axys)")); + menu.AddItem("rotate15x", Translate(client, "%t", "Rotate 15 degree (X axys)")); + menu.AddItem("rotate-15x", Translate(client, "%t", "Back 15 degree (X axys)")); + menu.AddItem("rotate45x", Translate(client, "%t", "Rotate 45 degree (X axys)")); + menu.AddItem("rotate90x", Translate(client, "%t", "Rotate 90 degree (X axys)")); + menu.AddItem("rotate180x", Translate(client, "%t", "Rotate 180 degree (X axys)")); + menu.AddItem("rotate1y", Translate(client, "%t", "Rotate 1 degree (Y axys)")); + menu.AddItem("rotate-1y", Translate(client, "%t", "Back 1 degree (Y axys)")); + menu.AddItem("rotate10y", Translate(client, "%t", "Rotate 10 degree (Y axys)")); + menu.AddItem("rotate-10y", Translate(client, "%t", "Back 10 degree (Y axys)")); + menu.AddItem("rotate15y", Translate(client, "%t", "Rotate 15 degree (Y axys)")); + menu.AddItem("rotate-15y", Translate(client, "%t", "Back 15 degree (Y axys)")); + menu.AddItem("rotate45y", Translate(client, "%t", "Rotate 45 degree (Y axys)")); + menu.AddItem("rotate90y", Translate(client, "%t", "Rotate 90 degree (Y axys)")); + menu.AddItem("rotate180y", Translate(client, "%t", "Rotate 180 degree (Y axys)")); + menu.AddItem("rotate1z", Translate(client, "%t", "Rotate 1 degree (Z axys)")); + menu.AddItem("rotate-1z", Translate(client, "%t", "Back 1 degree (Z axys)")); + menu.AddItem("rotate10z", Translate(client, "%t", "Rotate 10 degree (Z axys)")); + menu.AddItem("rotate-10z", Translate(client, "%t", "Back 10 degree (Z axys)")); + menu.AddItem("rotate15z", Translate(client, "%t", "Rotate 15 degree (Z axys)")); + menu.AddItem("rotate-15z", Translate(client, "%t", "Back 15 degree (Z axys)")); + menu.AddItem("rotate45z", Translate(client, "%t", "Rotate 45 degree (Z axys)")); + menu.AddItem("rotate90z", Translate(client, "%t", "Rotate 90 degree (Z axys)")); + menu.AddItem("rotate180z", Translate(client, "%t", "Rotate 180 degree (Z axys)")); + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iRotateMenuPosition[client], MENU_TIME_FOREVER); +} + +Menu DisplayMoveMenu(int client) +{ + g_iMoveCategory[client] = 2; + Menu menu = new Menu(MenuHandler_PropPosition); + menu.SetTitle("%T", "Move", client); + menu.AddItem("moveup1", Translate(client, "%t", "Move Up 1 Unit")); + menu.AddItem("moveup10", Translate(client, "%t", "Move Up 10 Unit")); + menu.AddItem("moveup30", Translate(client, "%t", "Move Up 30 Unit")); + menu.AddItem("movedown1", Translate(client, "%t", "Move Down 1 Unit")); + menu.AddItem("movedown10", Translate(client, "%t", "Move Down 10 Unit")); + menu.AddItem("movedown30", Translate(client, "%t", "Move Down 30 Unit")); + menu.AddItem("moveright1", Translate(client, "%t", "Move Right 1 Unit")); + menu.AddItem("moveright10", Translate(client, "%t", "Move Right 10 Unit")); + menu.AddItem("moveright30", Translate(client, "%t", "Move Right 30 Unit")); + menu.AddItem("moveleft1", Translate(client, "%t", "Move Left 1 Unit")); + menu.AddItem("moveleft10", Translate(client, "%t", "Move Left 10 Unit")); + menu.AddItem("moveleft30", Translate(client, "%t", "Move Left 30 Unit")); + menu.AddItem("moveforward1", Translate(client, "%t", "Move Forward 1 Unit")); + menu.AddItem("moveforward10", Translate(client, "%t", "Move Forward 10 Unit")); + menu.AddItem("moveforward30", Translate(client, "%t", "Move Forward 30 Unit")); + menu.AddItem("movebackward1", Translate(client, "%t", "Move Backward 1 Unit")); + menu.AddItem("movebackward10", Translate(client, "%t", "Move Backward 10 Unit")); + menu.AddItem("movebackward30", Translate(client, "%t", "Move Backward 30 Unit")); + + menu.ExitBackButton = true; + menu.ExitButton = true; + menu.DisplayAt(client, g_iMoveMenuPosition[client], MENU_TIME_FOREVER); +} + +public int MenuHandler_DoAction(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char model[256]; + GetMenuItem(menu, param2, model, sizeof(model)); + if(!IsModelPrecached(model)) + { + PrecacheModel(model); + } + if(g_iCategory[param1] == 1) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_physics_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + DispatchSpawn(prop); + GetClientEyePosition(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, param1); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(param1, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a physics object with model <%s>", name, model); + } + else if(g_iCategory[param1] == 2) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_physics_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + DispatchSpawn(prop); + GetClientAbsOrigin(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a physics object with model <%s>", name, model); + } + else if(g_iCategory[param1] == 3) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + DispatchSpawn(prop); + GetClientEyePosition(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, param1); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(param1, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + + g_bSpawned[prop] = true; + g_bUnsolid[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a dynamic object with model <%s>", name, model); + } + else if(g_iCategory[param1] == 4) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + DispatchSpawn(prop); + GetClientAbsOrigin(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_bUnsolid[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a dynamic object with model <%s>", name, model); + } + else if(g_iCategory[param1] == 5) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + GetClientEyePosition(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + SetEntProp(prop, Prop_Send, "m_nSolidType", 6); + + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_OPAQUE, RayType_Infinite, TraceRayDontHitSelf, param1); + if(TR_DidHit(null)) + { + TR_GetEndPosition(VecOrigin); + } + else + { + PrintToChat(param1, "[SM] Vector out of world geometry. Spawning on current position instead"); + } + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a static object with model <%s>", name, model); + } + else if(g_iCategory[param1] == 6) + { + float VecOrigin[3]; + float VecAngles[3]; + int prop = CreateEntityByName("prop_dynamic_override"); + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + SetEntProp(prop, Prop_Send, "m_nSolidType", 6); + DispatchSpawn(prop); + GetClientAbsOrigin(param1, VecOrigin); + GetClientEyeAngles(param1, VecAngles); + VecAngles[0] = 0.0; + VecAngles[2] = 0.0; + g_vecLastEntityAngles[param1] = VecAngles; + g_iLastObject[param1] = prop; + DispatchKeyValueVector(prop, "angles", VecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, VecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = VecAngles; + char name[256]; + GetClientName(param1, name, sizeof(name)); + LogSpawn("%s spawned a static object with model <%s>", name, model); + } + switch(g_iSubCategory[param1]) + { + case 1: + { + g_iVehiclesMenuPosition[param1] = menu.Selection; + DisplayVehiclesMenu(param1); + } + case 2: + { + g_iFoliageMenuPosition[param1] = menu.Selection; + DisplayFoliageMenu(param1); + } + case 3: + { + g_iFurnitureMenuPosition[param1] = menu.Selection; + DisplayFurnitureMenu(param1); + } + case 4: + { + g_iFurnishingsMenuPosition[param1] = menu.Selection; + DisplayFurnishingsMenu(param1); + } + case 5: + { + g_iAppliancesMenuPosition[param1] = menu.Selection; + DisplayAppliancesMenu(param1); + + } + case 6: + { + g_iBuildingsMenuPosition[param1] = menu.Selection; + DisplayBuildingsMenu(param1); + } + case 7: + { + g_iScaffoldingMenuPosition[param1] = menu.Selection; + DisplayScaffoldingMenu(param1); + } + case 8: + { + g_iDoorsMenuPosition[param1] = menu.Selection; + DisplayDoorsMenu(param1); + } + case 9: + { + g_iWindowsMenuPosition[param1] = menu.Selection; + DisplayWindowsMenu(param1); + } + case 10: + { + g_iLightsMenuPosition[param1] = menu.Selection; + DisplayLightsMenu(param1); + } + case 11: + { + g_iSignssMenuPosition[param1] = menu.Selection; + DisplaySignsMenu(param1); + + } + case 12: + { + g_iFencingMenuPosition[param1] = menu.Selection; + DisplayFencingMenu(param1); + } + case 13: + { + g_iRailingMenuPosition[param1] = menu.Selection; + DisplayRailingMenu(param1); + } + case 14: + { + g_iStairsMenuPosition[param1] = menu.Selection; + DisplayStairsMenu(param1); + } + case 15: + { + g_iOfficeMenuPosition[param1] = menu.Selection; + DisplayOfficeMenu(param1); + } + case 16: + { + g_iStreetsMenuPosition[param1] = menu.Selection; + DisplayStreetsMenu(param1); + } + case 17: + { + g_iFairgroundsMenuPosition[param1] = menu.Selection; + DisplayFairgroundsMenu(param1); + } + case 18: + { + g_iMallMenuPosition[param1] = menu.Selection; + DisplayMallMenu(param1); + } + case 19: + { + g_iConstructionMenuPosition[param1] = menu.Selection; + DisplayConstructionMenu(param1); + } + case 20: + { + g_iGeneralMiscMenuPosition[param1] = menu.Selection; + DisplayGeneralMiscMenu(param1); + } + case 21: + { + g_iExteriorMiscMenuPosition[param1] = menu.Selection; + DisplayExteriorMiscMenu(param1); + } + case 22: + { + g_iInteriorMiscMenuPosition[param1] = menu.Selection; + DisplayInteriorMiscMenu(param1); + } + case 23: + { + g_iDebrisMenuPosition[param1] = menu.Selection; + DisplayDebrisMenu(param1); + } + case 24: + { + g_iJunkMenuPosition[param1] = menu.Selection; + DisplayJunkMenu(param1); + } + case 25: + { + g_iPipesMenuPosition[param1] = menu.Selection; + DisplayPipesMenu(param1); + } + case 26: + { + g_iBodiesGenericMenuPosition[param1] = menu.Selection; + DisplayBodiesGenericMenu(param1); + } + case 27: + { + g_iBodiesSwampMenuPosition[param1] = menu.Selection; + DisplayBodiesSwampMenu(param1); + } + case 28: + { + g_iBodiesSugarMillMenuPosition[param1] = menu.Selection; + DisplayBodiesSugarMill(param1); + } + case 29: + { + g_iBodiesCemetaryMenuPosition[param1] = menu.Selection; + DisplayBodiesCemetaryMenu(param1); + } + case 30: + { + g_iInfectedMenuPosition[param1] = menu.Selection; + DisplayInfectedMenu(param1); + } + case 31: + { + g_iSkyboxMenuPosition[param1] = menu.Selection; + DisplaySkyboxMenu(param1); + } + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack) + { + switch(g_iCategory[param1]) + { + case 1: + { + BuildPhysicsCursorMenu(param1); + } + case 2: + { + BuildPhysicsPositionMenu(param1); + } + case 3: + { + BuildDynamicCursorMenu(param1); + } + case 4: + { + BuildDynamicPositionMenu(param1); + } + case 5: + { + BuildStaticCursorMenu(param1); + } + case 6: + { + BuildStaticPositionMenu(param1); + } + case 7: + { + BuildStaticPositionMenu(param1); + } + case 8: + { + BuildStaticPositionMenu(param1); + } + case 9: + { + BuildStaticPositionMenu(param1); + } + } + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public int MenuHandler_PropPosition(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + switch(g_iMoveCategory[param1]) + { + case 1: + { + if(g_iLastObject[param1] <= 0 || !IsValidEntity(g_iLastObject[param1])) + { + PrintToChat(param1, "[SM] The last object is not valid anymore or you haven't spawned anything yet"); + DisplayRotateMenu(param1); + return; + } + int Object = g_iLastObject[param1]; + + float vecAngles[3]; + vecAngles[0] = g_vecLastEntityAngles[param1][0]; + vecAngles[1] = g_vecLastEntityAngles[param1][1]; + vecAngles[2] = g_vecLastEntityAngles[param1][2]; + + if(strcmp(menucmd, "rotate1x")== 0) + { + vecAngles[0] += 1; + } + if(strcmp(menucmd, "rotate-1x")== 0) + { + vecAngles[0] -= 1; + } + else if(strcmp(menucmd, "rotate10x")== 0) + { + vecAngles[0] += 10; + } + else if(strcmp(menucmd, "rotate-10x")== 0) + { + vecAngles[0] -= 10; + } + else if(strcmp(menucmd, "rotate15x")== 0) + { + vecAngles[0] += 15; + } + else if(strcmp(menucmd, "rotate-15x")== 0) + { + vecAngles[0] -= 15; + } + else if(strcmp(menucmd, "rotate45x")== 0) + { + vecAngles[0] += 45; + } + else if(strcmp(menucmd, "rotate90x")== 0) + { + vecAngles[0] += 90; + } + else if(strcmp(menucmd, "rotate180x")== 0) + { + vecAngles[0] += 180; + } + else if(strcmp(menucmd, "rotate1y")== 0) + { + vecAngles[1] += 1; + } + else if(strcmp(menucmd, "rotate-1y")== 0) + { + vecAngles[1] -= 1; + } + else if(strcmp(menucmd, "rotate10y")== 0) + { + vecAngles[1] += 10; + } + else if(strcmp(menucmd, "rotate-10y")== 0) + { + vecAngles[1] -= 10; + } + else if(strcmp(menucmd, "rotate15y")== 0) + { + vecAngles[1] += 15; + } + else if(strcmp(menucmd, "rotate-15y")== 0) + { + vecAngles[1] -= 15; + } + else if(strcmp(menucmd, "rotate45y")== 0) + { + vecAngles[1] += 45; + } + else if(strcmp(menucmd, "rotate90y")== 0) + { + vecAngles[1] += 90; + } + else if(strcmp(menucmd, "rotate180y")== 0) + { + vecAngles[1] += 180; + } + else if(strcmp(menucmd, "rotate1z")== 0) + { + vecAngles[2] += 1; + } + else if(strcmp(menucmd, "rotate-1z")== 0) + { + vecAngles[2] -= 1; + } + else if(strcmp(menucmd, "rotate10z")== 0) + { + vecAngles[2] += 10; + } + else if(strcmp(menucmd, "rotate-10z")== 0) + { + vecAngles[2] -= 10; + } + else if(strcmp(menucmd, "rotate15z")== 0) + { + vecAngles[2] += 15; + } + else if(strcmp(menucmd, "rotate-15z")== 0) + { + vecAngles[2] -= 15; + } + else if(strcmp(menucmd, "rotate45z")== 0) + { + vecAngles[2] += 45; + } + else if(strcmp(menucmd, "rotate90z")== 0) + { + vecAngles[2] += 90; + } + else if(strcmp(menucmd, "rotate180z")== 0) + { + vecAngles[2] += 180; + } + + g_vecLastEntityAngles[param1] = vecAngles; + TeleportEntity(Object, NULL_VECTOR, vecAngles, NULL_VECTOR); + g_vecEntityAngles[g_iLastObject[param1]] = vecAngles; + + g_iRotateMenuPosition[param1] = menu.Selection; + DisplayRotateMenu(param1); + } + case 2: + { + if(g_iLastObject[param1] <= 0 || !IsValidEntity(g_iLastObject[param1])) + { + PrintToChat(param1, "[SM] The last object is not valid anymore or you haven't spawned anything yet"); + DisplayMoveMenu(param1); + return; + } + + int Object = g_iLastObject[param1]; + float vecOrigin[3]; + GetEntPropVector(Object, Prop_Data, "m_vecOrigin", vecOrigin); + + if(strcmp(menucmd, "moveup1")== 0) + { + vecOrigin[2]+= 1; + } + if(strcmp(menucmd, "moveup10")== 0) + { + vecOrigin[2]+= 10; + } + if(strcmp(menucmd, "moveup30")== 0) + { + vecOrigin[2]+= 30; + } + else if(strcmp(menucmd, "movedown1")== 0) + { + vecOrigin[2]-= 1; + } + else if(strcmp(menucmd, "movedown10")== 0) + { + vecOrigin[2]-= 10; + } + else if(strcmp(menucmd, "movedown30")== 0) + { + vecOrigin[2]-= 30; + } + else if(strcmp(menucmd, "moveright1")== 0) + { + vecOrigin[1]+= 1; + } + else if(strcmp(menucmd, "moveright10")== 0) + { + vecOrigin[1]+= 10; + } + else if(strcmp(menucmd, "moveright30")== 0) + { + vecOrigin[1]+= 30; + } + else if(strcmp(menucmd, "moveleft1")== 0) + { + vecOrigin[1]-= 1; + } + else if(strcmp(menucmd, "moveleft10")== 0) + { + vecOrigin[1]-= 10; + } + else if(strcmp(menucmd, "moveleft30")== 0) + { + vecOrigin[1]-= 30; + } + else if(strcmp(menucmd, "moveforward1")== 0) + { + vecOrigin[0]+= 1; + } + else if(strcmp(menucmd, "moveforward10")== 0) + { + vecOrigin[0]+= 10; + } + else if(strcmp(menucmd, "moveforward30")== 0) + { + vecOrigin[0]+= 30; + } + else if(strcmp(menucmd, "movebackward1")== 0) + { + vecOrigin[0]-= 1; + } + else if(strcmp(menucmd, "movebackward10")== 0) + { + vecOrigin[0]-= 10; + } + else if(strcmp(menucmd, "movebackward30")== 0) + { + vecOrigin[0]-= 30; + } + TeleportEntity(Object, vecOrigin, NULL_VECTOR, NULL_VECTOR); + + g_iMoveMenuPosition[param1] = menu.Selection; + DisplayMoveMenu(param1); + } + } + } + case MenuAction_Cancel: + { + if(param2 == MenuCancel_ExitBack) + { + BuildEditPropMenu(param1); + } + } + case MenuAction_End: + { + delete menu; + } + } +} + +public bool TraceRayDontHitSelf(int entity, int mask, any data) +{ + if(entity == data) // Check if the TraceRay hit the itself. + { + return false; // Don't let the entity be hit + } + return true; // It didn't hit itself +} + +void DeleteLookingEntity(int client) +{ + float VecOrigin[3]; + float VecAngles[3]; + GetClientEyePosition(client, VecOrigin); + GetClientEyeAngles(client, VecAngles); + TR_TraceRayFilter(VecOrigin, VecAngles, MASK_PLAYERSOLID, RayType_Infinite, TraceRayDontHitSelf, client); + if(TR_DidHit(null)) + { + int Object = TR_GetEntityIndex(null); + if(Object > 0 && IsValidEntity(Object) && IsValidEdict(Object)) + { + char class[256]; + GetEdictClassname(Object, class, sizeof(class)); + if(strcmp(class, "prop_physics") == 0 + || strcmp(class, "prop_dynamic") == 0 + || strcmp(class, "prop_physics_override") == 0 + || strcmp(class, "prop_dynamic_override") == 0) + { + g_bSpawned[Object] = false; + g_bUnsolid[Object] = false; + g_vecEntityAngles[Object][0] = 0.0; + g_vecEntityAngles[Object][1] = 0.0; + g_vecEntityAngles[Object][2] = 0.0; + + char m_ModelName[PLATFORM_MAX_PATH]; + GetEntPropString(Object, Prop_Data, "m_ModelName", m_ModelName, sizeof(m_ModelName)); + PrintToChat(client, "[SM] %T", "Object Model", client, Object, m_ModelName); + + float position[3]; + GetEntPropVector(Object, Prop_Send, "m_vecOrigin", position); + PrintToChat(client, "[SM] %T", "Object Position", client, Object, position[0], position[1], position[2]); + + float angle[3]; + GetEntPropVector(Object, Prop_Data, "m_angRotation", angle); + PrintToChat(client, "[SM] %T", "Object Angle", client, Object, angle[0], angle[1], angle[2]); + + AcceptEntityInput(Object, "KillHierarchy"); + PrintToChat(client, "[SM] %T", "Successfully removed an object", client, Object); + if(Object == g_iLastObject[client]) + { + g_iLastObject[client] = -1; + g_vecLastEntityAngles[client][0] = 0.0; + g_vecLastEntityAngles[client][1] = 0.0; + g_vecLastEntityAngles[client][2] = 0.0; + g_bGrab[client] = false; + g_bGrabbed[Object] = false; + } + if(Object == g_iLastGrabbedObject[client]) + { + g_iLastGrabbedObject[client] = -1; + } + return; + } + } + } + else + { + int Object = GetClientAimTarget(client, false); + if(Object == -2) + { + PrintToChat(client, "[SM] %T","This plugin won't work in this game",client); + SetFailState("Unhandled Behaviour"); + } + if(Object > 0 && IsValidEntity(Object)) + { + char class[256]; + GetEdictClassname(Object, class, sizeof(class)); + if(strcmp(class, "prop_physics") == 0 + || strcmp(class, "prop_dynamic") == 0 + || strcmp(class, "prop_physics_override") == 0 + || strcmp(class, "prop_dynamic_override") == 0) + { + g_bSpawned[Object] = false; + g_bUnsolid[Object] = false; + g_vecEntityAngles[Object][0] = 0.0; + g_vecEntityAngles[Object][1] = 0.0; + g_vecEntityAngles[Object][2] = 0.0; + AcceptEntityInput(Object, "KillHierarchy"); + PrintToChat(client, "[SM] %T", "Successfully removed an object", client, Object); + if(Object == g_iLastObject[client]) + { + g_iLastObject[client] = -1; + g_vecLastEntityAngles[client][0] = 0.0; + g_vecLastEntityAngles[client][1] = 0.0; + g_vecLastEntityAngles[client][2] = 0.0; + if(Object == g_iLastGrabbedObject[client]) + { + g_iLastGrabbedObject[client] = -1; + } + } + return; + } + } + } + PrintToChat(client, "[SM] %T","You are not looking to a valid object",client); +} + +void DeleteAllProps() +{ + CheatCommand(_, "ent_fire", "l4d2_spawn_props_prop KillHierarchy"); + for(int i=1; i<=MaxClients; i++) + { + g_iLastObject[i] = -1; + g_vecLastEntityAngles[i][0] = 0.0; + g_vecLastEntityAngles[i][1] = 0.0; + g_vecLastEntityAngles[i][2] = 0.0; + g_bGrab[i] = false; + g_iLastGrabbedObject[i] = -1; + } + for(int i=MaxClients; i < ARRAY_SIZE; i++) + { + if(g_bSpawned[i]) + { + g_bGrabbed[i] = false; + g_bSpawned[i] = false; + g_bUnsolid[i] = false; + g_vecEntityAngles[i][0] = 0.0; + g_vecEntityAngles[i][1] = 0.0; + g_vecEntityAngles[i][2] = 0.0; + if(IsValidEntity(i)) + { + AcceptEntityInput(i, "Kill"); + } + } + } +} + +void CheatCommand(int client = 0, char[] command, char[] arguments="") +{ + if (!client || !IsClientInGame(client)) + { + for (int target = 1; target <= MaxClients; target++) + { + if (IsClientInGame(target)) + { + client = target; + break; + } + } + + if (!client || !IsClientInGame(client)) return; + } + + int userflags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s", command, arguments); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userflags); +} + +//Disabled right now +void DeleteLastProp(int client) +{ + int Object = g_iLastObject[client]; + if(Object > 0 && IsValidEntity(Object)) + { + char class[256]; + GetEdictClassname(Object, class, sizeof(class)); + if(strcmp(class, "prop_physics") == 0 + || strcmp(class, "prop_dynamic") == 0 + || strcmp(class, "prop_physics_override") == 0 + || strcmp(class, "prop_dynamic_override") == 0) + { + AcceptEntityInput(g_iLastObject[client], "KillHierarchy"); + PrintToChat(client, "[SM] %T","Succesfully deleted the last spawned object",client); + g_iLastObject[client] = -1; + g_vecLastEntityAngles[client][0] = 0.0; + g_vecLastEntityAngles[client][1] = 0.0; + g_vecLastEntityAngles[client][2] = 0.0; + g_bSpawned[Object] = false; + g_bUnsolid[Object] = false; + g_vecEntityAngles[Object][0] = 0.0; + g_vecEntityAngles[Object][1] = 0.0; + g_vecEntityAngles[Object][2] = 0.0; + g_bGrab[client] = false; + g_bGrabbed[Object] = false; + if(Object == g_iLastGrabbedObject[client]) + { + g_iLastGrabbedObject[client] = -1; + } + return; + } + else + { + PrintToChat(client, "[SM] %T", "The last spawned object index is not an object anymore!", client, Object); + g_iLastObject[client] = -1; + g_vecLastEntityAngles[client][0] = 0.0; + g_vecLastEntityAngles[client][1] = 0.0; + g_vecLastEntityAngles[client][2] = 0.0; + g_bSpawned[Object] = false; + g_bUnsolid[Object] = false; + g_vecEntityAngles[Object][0] = 0.0; + g_vecEntityAngles[Object][1] = 0.0; + g_vecEntityAngles[Object][2] = 0.0; + } + } + else if(Object > 0 && !IsValidEntity(Object)) + { + PrintToChat(client, "[SM] %T","The last object is not valid anymore",client); + } + else if(Object <= 0) + { + PrintToChat(client, "[SM] %T","You haven't spawned anything yet",client); + } +} + +void LogSpawn(const char[] format, any ...) +{ + if(!g_cvarLog.BoolValue) + { + return; + } + char buffer[512]; + VFormat(buffer, sizeof(buffer), format, 2); + File file; + char FileName[256]; + char sTime[256]; + FormatTime(sTime, sizeof(sTime), "%Y%m%d"); + BuildPath(Path_SM, FileName, sizeof(FileName), "logs/objects_%s.log", sTime); + file = OpenFile(FileName, "a+"); + FormatTime(sTime, sizeof(sTime), "%b %d |%H:%M:%S| %Y"); + file.WriteLine("%s: %s", sTime, buffer); + FlushFile(file); + CloseHandle(file); +} + +public Action CmdSaveMap(int client, int args) +{ + SaveMapStripper(client); + return Plugin_Handled; +} + +void SaveMapStripper(int client) +{ + #if DEBUG + LogSpawn("[DEBUG] was called by %N", client); + #endif + LogSpawn("%N saved the objects for this map on a 'Stripper' file format", client); + PrintToChat(client, "\x04[SM] Saving the content. Please Wait"); + char FileName[256]; + char map[256]; + char classname[256]; + File file; + GetCurrentMap(map, sizeof(map)); + BuildPath(Path_SM, FileName, sizeof(FileName), "../stripper/maps/%s.cfg", map); + + if(FileExists(FileName)) + { + PrintHintText(client, "%T", "The file already exists.", client); + } + #if DEBUG + LogSpawn("[DEBUG] File stated, proceed"); + #endif + file = OpenFile(FileName, "a+"); + #if DEBUG + LogSpawn("[DEBUG] File Opened, proceed"); + #endif + if(file == null) + { + #if DEBUG + LogSpawn("[DEBUG] File Invalid, proceed"); + #endif + PrintToChat(client, "[SM] Failed to create or overwrite the map file"); + PrintToChat(client, "\x04[SM] Something was probably missing during installation"); + PrintHintText(client, "[SM] Probably missing addons/stripper folder"); + PrintToConsole(client, "[SM] Unable to open, write, or find the file!"); + PrintCenterText(client, "[SM] FAILURE"); + return; + } + + float vecOrigin[3]; + float vecAngles[3]; + char sModel[256]; + char sTime[256]; + int iOrigin[3], iAngles[3]; + FormatTime(sTime, sizeof(sTime), "%Y/%m/%d"); + file.WriteLine(";----------FILE MODIFICATION (YY/MM/DD): [%s] ---------------||", sTime); + file.WriteLine(";----------BY: %N----------------------||", client); + file.WriteLine(""); + file.WriteLine("add:"); + #if DEBUG + LogSpawn("[DEBUG] Wrote first information line"); + #endif + for(int i=MaxClients; i < ARRAY_SIZE; i++) + { + #if DEBUG + LogSpawn("[DEBUG] CHECK: %i", i); + #endif + if(g_bSpawned[i] && IsValidEntity(i)) + { + GetEdictClassname(i, classname, sizeof(classname)); + #if DEBUG + LogSpawn("[DEBUG] Possible Entity Found: %i <%s>", i, classname); + #endif + if(StrContains(classname, "prop_dynamic") >= 0 || StrContains(classname, "prop_physics") >= 0) + { + GetEntPropVector(i, Prop_Send, "m_vecOrigin", vecOrigin); + vecAngles = g_vecEntityAngles[i]; + GetEntPropString(i, Prop_Data, "m_ModelName", sModel, sizeof(sModel)); + iOrigin[0] = RoundToFloor(vecOrigin[0]); + iOrigin[1] = RoundToFloor(vecOrigin[1]); + iOrigin[2] = RoundToFloor(vecOrigin[2]); + + iAngles[0] = RoundToFloor(vecAngles[0]); + iAngles[1] = RoundToFloor(vecAngles[1]); + iAngles[2] = RoundToFloor(vecAngles[2]); + file.WriteLine("{"); + if(StrContains(classname, "physics") < 0) + { + if(g_bUnsolid[i]) + { + file.WriteLine(" \"solid\" \"0\""); + } + else + { + file.WriteLine(" \"solid\" \"6\""); + } + } + file.WriteLine(" \"origin\" \"%i %i %i\"", iOrigin[0], iOrigin[1], iOrigin[2]); + file.WriteLine(" \"angles\" \"%i %i %i\"", iAngles[0], iAngles[1], iAngles[2]); + file.WriteLine(" \"model\" \"%s\"", sModel); + file.WriteLine(" \"classname\" \"%s\"", classname); + file.WriteLine("}"); + file.WriteLine(""); + #if DEBUG + LogSpawn("[DEBUG] END: %i", i); + #endif + } + } + } + #if DEBUG + LogSpawn("[DEBUG] Wrote all entities"); + #endif + FlushFile(file); + CloseHandle(file); + PrintToChat(client, "\x03[SM] %T (%s)", "Succesfully saved the map data", client, FileName); + #if DEBUG + LogSpawn("[DEBUG] END"); + #endif +} + +void SaveRoutingPath(int client, int type) +{ + #if DEBUG + LogSpawn("[DEBUG] was called by %N", client); + #endif + LogSpawn("%N saved the objects for this map on a \"Routing\" file format", client); + PrintToChat(client, "\x04[SM] Saving the content. Please Wait"); + char FileName[256]; + char map[256]; + char classname[256]; + char targetname[256]; + File file; + bool Exists = false; + GetCurrentMap(map, sizeof(map)); + BuildPath(Path_SM, FileName, sizeof(FileName), "../stripper/routing/%s.cfg", map); + if(FileExists(FileName)) + { + PrintHintText(client, "%T", "The file already exists.", client); + Exists = true; + } + file = OpenFile(FileName, "a+"); + if(file == null) + { + PrintToChat(client, "[SM] Failed to create or overwrite the map file"); + PrintToChat(client, "\x04[SM] Something was probably missing during installation"); + PrintHintText(client, "[SM] Probably missing addons/stripper/maps/routing folder"); + PrintToConsole(client, "[SM] Unable to open, write, or find the file!"); + PrintCenterText(client, "[SM] FAILURE"); + return; + } + float vecOrigin[3]; + float vecAngles[3]; + char sModel[256]; + char sTime[256]; + int iOrigin[3], iAngles[3]; + FormatTime(sTime, sizeof(sTime), "%Y/%m/%d"); + file.WriteLine(";----------FILE MODIFICATION (YY/MM/DD): [%s] ---------------||", sTime); + file.WriteLine(";----------BY: %N----------------------||", client); + file.WriteLine(""); + switch(type) + { + case RouteType_Easy: + { + file.WriteLine(";This part was generated for an \"Easy\" routing path."); + Format(targetname, sizeof(targetname), "easy_route_blocker"); + } + case RouteType_Medium: + { + file.WriteLine(";This part was generated for a \"Medium\" routing path."); + Format(targetname, sizeof(targetname), "medium_route_blocker"); + } + case RouteType_Hard: + { + file.WriteLine(";This part was generated for a \"Hard\" routing path."); + Format(targetname, sizeof(targetname), "hard_route_blocker"); + } + } + file.WriteLine(""); + file.WriteLine("add:"); + + if(!Exists) + { + //First, wee add the necessary relays + + file.WriteLine("; plugin trigger relay"); + file.WriteLine("; will get fired by Plugin ONLY IN VERSUS, so it doesnt break coop"); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"spawnflags\" \"1\""); + file.WriteLine(" \"targetname\" \"relay_routing_init\""); + file.WriteLine(" \"classname\" \"logic_relay\""); + file.WriteLine(" "); + file.WriteLine(" ; destroy Valve routing entities so they dont interfere"); + file.WriteLine(" "); + file.WriteLine(" \"OnTrigger\" \"director_queryKill0-1\""); + file.WriteLine("}"); + file.WriteLine(""); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"spawnflags\" \"1\""); + file.WriteLine(" \"targetname\" \"relay_routing_disabledbydefault\""); + file.WriteLine(" \"classname\" \"logic_auto\""); + file.WriteLine(" "); + file.WriteLine(" \"OnMapSpawn\" \"easy_route_blockerDisable0-1\""); + file.WriteLine(" \"OnMapSpawn\" \"easy_route_blockerDisableCollision0-1\""); + file.WriteLine(" \"OnMapSpawn\" \"medium_route_blockerDisable0-1\""); + file.WriteLine(" \"OnMapSpawn\" \"medium_route_blockerDisableCollision0-1\""); + file.WriteLine(" \"OnMapSpawn\" \"hard_route_blockerDisable0-1\""); + file.WriteLine(" \"OnMapSpawn\" \"hard_route_blockerDisableCollision0-1\""); + file.WriteLine("}"); + file.WriteLine("; config existence checking entity"); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"targetname\" \"map_has_routing\""); + file.WriteLine(" \"noise\" \"0\""); + file.WriteLine(" \"minAngerRange\" \"1\""); + file.WriteLine(" \"maxAngerRange\" \"10\""); + file.WriteLine(" \"classname\" \"logic_director_query\""); + file.WriteLine(" \"OutAnger\" \"DoHeadBangInValue0-1\""); + file.WriteLine("}"); + file.WriteLine(""); + file.WriteLine("; easy path"); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"targetname\" \"relay_easy_route_spawn\""); + file.WriteLine(" \"spawnflags\" \"0\""); + file.WriteLine(" \"classname\" \"logic_relay\""); + file.WriteLine(" \"OnTrigger\" \"easy_route_blockerEnable0-1\""); + file.WriteLine(" \"OnTrigger\" \"easy_route_blockerEnableCollision0-1\""); + file.WriteLine("}"); + file.WriteLine(""); + file.WriteLine("; medium path"); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"targetname\" \"relay_medium_route_spawn\""); + file.WriteLine(" \"spawnflags\" \"0\""); + file.WriteLine(" \"classname\" \"logic_relay\""); + file.WriteLine(" \"OnTrigger\" \"medium_route_blockerEnable0-1\""); + file.WriteLine(" \"OnTrigger\" \"medium_route_blockerEnableCollision0-1\""); + file.WriteLine("}"); + file.WriteLine(""); + file.WriteLine("; hard path"); + file.WriteLine("{"); + file.WriteLine(" \"origin\" \"0 0 0\""); + file.WriteLine(" \"targetname\" \"relay_hard_route_spawn\""); + file.WriteLine(" \"spawnflags\" \"0\""); + file.WriteLine(" \"classname\" \"logic_relay\""); + file.WriteLine(" \"OnTrigger\" \"hard_route_blockerEnable0-1\""); + file.WriteLine(" \"OnTrigger\" \"hard_route_blockerEnableCollision0-1\""); + file.WriteLine("}"); + file.WriteLine(""); + } + for(int i=MaxClients; i < ARRAY_SIZE; i++) + { + if(g_bSpawned[i] && IsValidEntity(i)) + { + GetEdictClassname(i, classname, sizeof(classname)); + if(StrContains(classname, "prop_dynamic") >= 0 || StrContains(classname, "prop_physics") >= 0) + { + GetEntPropVector(i, Prop_Send, "m_vecOrigin", vecOrigin); + vecAngles = g_vecEntityAngles[i]; + GetEntPropString(i, Prop_Data, "m_ModelName", sModel, sizeof(sModel)); + iOrigin[0] = RoundToFloor(vecOrigin[0]); + iOrigin[1] = RoundToFloor(vecOrigin[1]); + iOrigin[2] = RoundToFloor(vecOrigin[2]); + + iAngles[0] = RoundToFloor(vecAngles[0]); + iAngles[1] = RoundToFloor(vecAngles[1]); + iAngles[2] = RoundToFloor(vecAngles[2]); + file.WriteLine("{"); + if(StrContains(classname, "physics") < 0) + { + if(g_bUnsolid[i]) + { + file.WriteLine(" \"solid\" \"0\""); + } + else + { + file.WriteLine(" \"solid\" \"6\""); + } + } + file.WriteLine(" \"origin\" \"%i %i %i\"", iOrigin[0], iOrigin[1], iOrigin[2]); + file.WriteLine(" \"angles\" \"%i %i %i\"", iAngles[0], iAngles[1], iAngles[2]); + file.WriteLine(" \"model\" \"%s\"", sModel); + file.WriteLine(" \"targetname\" \"%s\"", targetname); + file.WriteLine(" \"classname\" \"%s\"", classname); + file.WriteLine("}"); + file.WriteLine(""); + } + } + } + FlushFile(file); + CloseHandle(file); + PrintToChat(client, "\x03[SM] %T (%s)", "Succesfully saved the map data", client, FileName); +} + +void SavePluginProps(int client) +{ + LogSpawn("%N saved the objects for this map on a \"Plugin Cache\" file format", client); + PrintToChat(client, "\x04[SM] Saving the content. Please Wait"); + char FileName[256]; + char map[256]; + char classname[256]; + char FileNameS[256]; + char FileNameT[256]; + File file; + GetCurrentMap(map, sizeof(map)); + BuildPath(Path_SM, FileNameS, sizeof(FileNameS), "../stripper/plugin_cache/%s", map); + Format(FileName, sizeof(FileName), "%s_1.txt", FileNameS); + int map_number = 0; + if(FileExists(FileName)) + { + map_number = GetNextMapNumber(FileNameS); + if(map_number <= 0) + { + PrintToChat(client, "\x04[SM] Fatal Error: Too Many path files for this map! (Max: %i)", MAX_PATHS); + return; + } + Format(FileNameT, sizeof(FileNameT), "%s_%i.txt", FileNameS, map_number); + } + else + { + Format(FileNameT, sizeof(FileNameT), "%s_1.txt", FileNameS); + } + file = OpenFile(FileNameT, "a+"); + if(file == null) + { + PrintToChat(client, "[SM] Failed to create or overwrite the map file"); + PrintToChat(client, "\x04[SM] Something was probably missing during installation"); + PrintHintText(client, "[SM] Probably missing addons/stripper/maps/plugin_cache folder"); + PrintToConsole(client, "[SM] Unable to open, write, or find the file!"); + PrintCenterText(client, "[SM] FAILURE"); + return; + } + CreateInitFile(); + float vecOrigin[3]; + float vecAngles[3]; + char sModel[256]; + char sTime[256]; + int iOrigin[3], iAngles[3]; + int count = 0; + FormatTime(sTime, sizeof(sTime), "%Y/%m/%d"); + file.WriteLine("//----------FILE MODIFICATION (YY/MM/DD): [%s] ---------------||", sTime); + file.WriteLine("//----------BY: %N----------------------||", client); + file.WriteLine(""); + file.WriteLine("\"Objects_Cache\""); + file.WriteLine("{"); + for(int i=MaxClients; i < ARRAY_SIZE; i++) + { + if(g_bSpawned[i] && IsValidEntity(i)) + { + GetEdictClassname(i, classname, sizeof(classname)); + if(StrContains(classname, "prop_dynamic") >= 0 || StrContains(classname, "prop_physics") >= 0) + { + GetEntPropVector(i, Prop_Send, "m_vecOrigin", vecOrigin); + vecAngles = g_vecEntityAngles[i]; + GetEntPropString(i, Prop_Data, "m_ModelName", sModel, sizeof(sModel)); + iOrigin[0] = RoundToFloor(vecOrigin[0]); + iOrigin[1] = RoundToFloor(vecOrigin[1]); + iOrigin[2] = RoundToFloor(vecOrigin[2]); + + iAngles[0] = RoundToFloor(vecAngles[0]); + iAngles[1] = RoundToFloor(vecAngles[1]); + iAngles[2] = RoundToFloor(vecAngles[2]); + count++; + + file.WriteLine(" \"object_%i\"", count); + file.WriteLine(" {"); + if(StrContains(classname, "physics") < 0) + { + if(g_bUnsolid[i]) + { + file.WriteLine(" \"solid\" \"0\""); + } + else + { + file.WriteLine(" \"solid\" \"6\""); + } + } + file.WriteLine(" \"origin\" \"%i %i %i\"", iOrigin[0], iOrigin[1], iOrigin[2]); + file.WriteLine(" \"angles\" \"%i %i %i\"", iAngles[0], iAngles[1], iAngles[2]); + file.WriteLine(" \"model\" \"%s\"", sModel); + file.WriteLine(" \"classname\" \"%s\"", classname); + file.WriteLine(" }"); + file.WriteLine(" "); + } + } + } + file.WriteLine(" \"total_cache\""); + file.WriteLine(" {"); + file.WriteLine(" \"total\" \"%i\"", count); + file.WriteLine(" }"); + file.WriteLine("}"); + + FlushFile(file); + CloseHandle(file); + PrintToChat(client, "\x03[SM] %T (%s)", "Succesfully saved the map data", client, FileNameT); +} + +public Action CmdLoad(int client, int args) +{ + if(args < 1) + { + PrintToChat(client, "[SM] Specify a map number"); + } + char arg[5]; + GetCmdArgString(arg, sizeof(arg)); + int number = StringToInt(arg); + LoadPluginProps(client, number); + return Plugin_Handled; +} + +void LoadPluginProps(int client, int number) +{ + LogSpawn("%N loaded the objects for this map", client); + PrintToChat(client, "\x04[SM] Loading content. Please Wait"); + char KvFileName[256]; + char map[256]; + char name[256]; + GetCurrentMap(map, sizeof(map)); + BuildPath(Path_SM, KvFileName, sizeof(KvFileName), "../stripper/plugin_cache/%s_%i.txt", map, number); + if(!FileExists(KvFileName)) + { + PrintToChat(client, "\x04[SM] The file does not exist"); + PrintHintText(client, "\x04[SM] The file does not exist"); + return; + } + KeyValues keyvalues = new KeyValues("Objects_Cache"); + keyvalues.ImportFromFile(KvFileName); + keyvalues.Rewind(); + if(keyvalues.JumpToKey("total_cache")) + { + int max = keyvalues.GetNum("total", 0); + if(max <= 0) + { + PrintToChat(client, "\x04[SM] No objects found in the cache"); + return; + } + char model[256]; + char class[64]; + float vecOrigin[3]; + float vecAngles[3]; + int solid; + keyvalues.Rewind(); + for(int count=1; count <= max; count++) + { + Format(name, sizeof(name), "object_%i", count); + if(keyvalues.JumpToKey(name)) + { + solid = keyvalues.GetNum("solid"); + keyvalues.GetVector("origin", vecOrigin); + keyvalues.GetVector("angles", vecAngles); + keyvalues.GetString("model", model, sizeof(model)); + keyvalues.GetString("classname", class, sizeof(class)); + int prop = -1; + keyvalues.Rewind(); + if(StrContains(class, "prop_physics") >= 0) + { + prop = CreateEntityByName("prop_physics_override"); + } + else + { + prop = CreateEntityByName("prop_dynamic_override"); + SetEntProp(prop, Prop_Send, "m_nSolidType", solid); + } + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + + g_vecLastEntityAngles[client][0] = vecAngles[0]; + g_vecLastEntityAngles[client][1] = vecAngles[1]; + g_vecLastEntityAngles[client][2] = vecAngles[2]; + DispatchKeyValueVector(prop, "angles", vecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, vecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = vecAngles; + } + else + { + break; + } + } + } + CloseHandle(keyvalues); + PrintToChat(client, "\x03[SM] Succesfully loaded the map data"); + PrintHintText(client, "[SM] If nothing is visible, you probably forgot something during installation"); +} + +public Action CmdRotate(int client, int args) +{ + if(args < 2) + { + PrintToChat(client, "[SM] Usage: sm_prop_rotate [EX: !prop_rotate x 30]"); + return Plugin_Handled; + } + int Object = g_iLastObject[client]; + char arg1[16]; + char arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + float vecAngles[3]; + vecAngles[0] = g_vecLastEntityAngles[client][0]; + vecAngles[1] = g_vecLastEntityAngles[client][1]; + vecAngles[2] = g_vecLastEntityAngles[client][2]; + int iAngles = StringToInt(arg2); + if(strcmp(arg1, "x")== 0) + { + vecAngles[0] += iAngles; + } + else if(strcmp(arg1, "y")== 0) + { + vecAngles[1] += iAngles; + } + else if(strcmp(arg1, "z")== 0) + { + vecAngles[2] += iAngles; + } + else + { + PrintToChat(client, "[SM] Invalid Axys (x,y,z are allowed)"); + } + g_vecLastEntityAngles[client] = vecAngles; + TeleportEntity(Object, NULL_VECTOR, vecAngles, NULL_VECTOR); + g_vecEntityAngles[g_iLastObject[client]] = vecAngles; + return Plugin_Handled; +} + +public Action CmdRemoveLast(int client, int args) +{ + DeleteLastProp(client); + return Plugin_Handled; +} + +public Action CmdRemoveLook(int client, int args) +{ + DeleteLookingEntity(client); + return Plugin_Handled; +} + +public Action CmdRemoveAll(int client, int args) +{ + PrintToChat(client, "\x04[SM] %T","Are you sure(Delete All)?",client); + BuildDeleteAllCmd(client); + return Plugin_Handled; +} + +Menu BuildDeleteAllCmd(int client) +{ + Menu menu = new Menu(MenuHandler_cmd_Ask); + menu.SetTitle("%T", "Are you sure?", client); + menu.AddItem("sm_spyes", Translate(client, "%t", "Yes")); + menu.AddItem("sm_spno", Translate(client, "%t", "No")); + menu.ExitButton = true; + menu.Display(client, MENU_TIME_FOREVER); +} + +public int MenuHandler_cmd_Ask(Menu menu, MenuAction action, int param1, int param2) +{ + switch(action) + { + case MenuAction_Select: + { + char menucmd[256]; + GetMenuItem(menu, param2, menucmd, sizeof(menucmd)); + if(strcmp(menucmd, "sm_spyes")== 0) + { + DeleteAllProps(); + PrintToChat(param1, "[SM] %T", "Successfully deleted all spawned objects", param1); + } + else + { + PrintToChat(param1, "[SM] %T", "Canceled", param1); + } + } + case MenuAction_Cancel: + { + } + case MenuAction_End: + { + delete menu; + } + } +} + +int GetNextMapNumber(char[] FileName) +{ + char FileNameS[256]; + for(int i=1; i <= MAX_PATHS; i++) + { + Format(FileNameS, sizeof(FileNameS), "%s_%i.txt", FileName, i); + if(FileExists(FileNameS)) + { + continue; + } + else + { + return i; + } + } + return -1; +} + +void SpawnObjects() +{ + //if disabled + if(!g_cvarAutoload.BoolValue) + { + return; + } + char KvFileName[256]; + char name[256]; + BuildPath(Path_SM, KvFileName, sizeof(KvFileName), "../stripper/plugin_cache/%s.txt", g_sPath); + LogSpawn("Spawning props from file %s", KvFileName); + if(!FileExists(KvFileName)) + { + LogError("Attempted to load an object file which does not exist (%s)", KvFileName); + LogSpawn("[ERROR] Attempted to load an object file which does not exist (%s)", KvFileName); + return; + } + KeyValues keyvalues = new KeyValues("Objects_Cache"); + keyvalues.ImportFromFile(KvFileName); + keyvalues.Rewind(); + if(keyvalues.JumpToKey("total_cache")) + { + int max = keyvalues.GetNum("total", 0); + if(max <= 0) + { + LogError("No Objects found for the map number cache"); + LogSpawn("[ERROR] No Objects found for the map number cache"); + return; + } + char model[256]; + char class[64]; + float vecOrigin[3]; + float vecAngles[3]; + int solid; + keyvalues.Rewind(); + for(int count=1; count <= max; count++) + { + Format(name, sizeof(name), "object_%i", count); + if(keyvalues.JumpToKey(name)) + { + solid = keyvalues.GetNum("solid"); + keyvalues.GetVector("origin", vecOrigin); + keyvalues.GetVector("angles", vecAngles); + keyvalues.GetString("model", model, sizeof(model)); + keyvalues.GetString("classname", class, sizeof(class)); + int prop = -1; + keyvalues.Rewind(); + if(StrContains(class, "prop_physics") >= 0) + { + prop = CreateEntityByName("prop_physics_override"); + } + else + { + prop = CreateEntityByName("prop_dynamic_override"); + SetEntProp(prop, Prop_Send, "m_nSolidType", solid); + } + DispatchKeyValue(prop, "model", model); + DispatchKeyValue(prop, "targetname", "l4d2_spawn_props_prop"); + + DispatchKeyValueVector(prop, "angles", vecAngles); + DispatchSpawn(prop); + TeleportEntity(prop, vecOrigin, NULL_VECTOR, NULL_VECTOR); + g_bSpawned[prop] = true; + g_vecEntityAngles[prop] = vecAngles; + } + else + { + break; + } + } + } + CloseHandle(keyvalues); +} +void CreateInitFile() +{ + char FileName[256]; + char map[256]; + File file; + GetCurrentMap(map, sizeof(map)); + BuildPath(Path_SM, FileName, sizeof(FileName), "../stripper/plugin_cache/%s_init.txt", map); + + if(!FileExists(FileName)) + { + file = OpenFile(FileName, "a+"); + if(file == null) + { + return; + } + file.WriteLine("//Init file for map %s", map); + file.WriteLine("//DO NOT FORGET TO REPLACE \" FOR QUOTES!"); + file.WriteLine("//"); + file.WriteLine("//The format of the file is:"); + file.WriteLine("//"); + file.WriteLine("// \"coop\" --------> This is the gamemode where the following object list will be loaded"); + file.WriteLine("// {"); + file.WriteLine("// \"total\" \"2\" ---------> This is the total object list availables. Randomly, one will be selected"); + file.WriteLine("// \"path1\" \"c5m2_park_1\" -------------> If the plugin chooses the option 1, the file c5m2_park_1.txt will be loaded"); + file.WriteLine("// \"path2\" \"c5m2_park_3\" -------------> Same if the option is 2"); + file.WriteLine("// }"); + file.WriteLine("//"); + file.WriteLine("// If you have any doubts, please check the example_init.txt file or ask on the plugin topic."); + file.WriteLine("//"); + file.WriteLine(""); + file.WriteLine("\"PathInit\""); + file.WriteLine("{"); + file.WriteLine(" \"coop\""); + file.WriteLine(" {"); + file.WriteLine(" "); + file.WriteLine(" }"); + file.WriteLine(" "); + file.WriteLine(" \"versus\""); + file.WriteLine(" {"); + file.WriteLine(" "); + file.WriteLine(" }"); + file.WriteLine(" "); + file.WriteLine(" \"survival\""); + file.WriteLine(" {"); + file.WriteLine(" "); + file.WriteLine(" }"); + file.WriteLine(" "); + file.WriteLine(" \"scavenge\""); + file.WriteLine(" {"); + file.WriteLine(" "); + file.WriteLine(" }"); + file.WriteLine("}"); + FlushFile(file); + CloseHandle(file); + } +} + +void GetRandomMapPath(char[] MapName, int maxlen) +{ + char KvFileName[256]; + char sMap[128]; + char GameMode[128]; + GetCurrentMap(sMap, sizeof(sMap)); + BuildPath(Path_SM, KvFileName, sizeof(KvFileName), "../stripper/plugin_cache/%s_init.txt", sMap); + if(!FileExists(KvFileName)) + { + LogError("Unable to find the init file!"); + } + else + { + KeyValues keyvalues = new KeyValues("PathInit"); + keyvalues.ImportFromFile(KvFileName); + keyvalues.Rewind(); + ConVar cvarGameMode = FindConVar("mp_gamemode"); + cvarGameMode.GetString(GameMode, sizeof(GameMode)); + if(keyvalues.JumpToKey(GameMode)) + { + char sNumber[11]; + int total_paths = keyvalues.GetNum("total"); + int random = GetRandomInt(1, total_paths); + Format(sNumber, sizeof(sNumber), "path%i", random); + keyvalues.GetString(sNumber, MapName, maxlen); + CloseHandle(keyvalues); + return; + } + else + { + LogError("Unable to find the gamemode"); + Format(MapName, maxlen, "invalid"); + CloseHandle(keyvalues); + return; + } + + } + Format(MapName, maxlen, "invalid"); + return; +} + +public Action CmdMove(int client, int args) +{ + if(args < 2) + { + PrintToChat(client, "[SM] Usage: sm_prop_move [EX: !prop_move x 30]"); + return Plugin_Handled; + } + int Object = g_iLastObject[client]; + char arg1[16]; + char arg2[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + float vecPosition[3]; + GetEntPropVector(Object, Prop_Data, "m_vecOrigin", vecPosition); + float flPosition = StringToFloat(arg2); + if(strcmp(arg1, "x")== 0) + { + vecPosition[0] += flPosition; + } + else if(strcmp(arg1, "y")== 0) + { + vecPosition[1] += flPosition; + } + else if(strcmp(arg1, "z")== 0) + { + vecPosition[2] += flPosition; + } + else + { + PrintToChat(client, "[SM] Invalid Axys (x,y,z are allowed)"); + } + g_bGrab[client] = false; + g_bGrabbed[Object] = false; + TeleportEntity(Object, vecPosition, NULL_VECTOR, NULL_VECTOR); + return Plugin_Handled; +} + +public Action CmdSetAngles(int client, int args) +{ + if(args < 3) + { + PrintToChat(client, "[SM] Usage: sm_prop_setang [EX: !prop_setang 30 0 34"); + return Plugin_Handled; + } + int Object = g_iLastObject[client]; + char arg1[16]; + char arg2[16]; + char arg3[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + float vecAngles[3]; + + vecAngles[0] = StringToFloat(arg1); + vecAngles[1] = StringToFloat(arg2); + vecAngles[2] = StringToFloat(arg3); + g_vecLastEntityAngles[client] = vecAngles; + g_vecEntityAngles[Object] = vecAngles; + + g_bGrab[client] = false; + g_bGrabbed[Object] = false; + TeleportEntity(Object, NULL_VECTOR, vecAngles, NULL_VECTOR); + return Plugin_Handled; +} + +public Action CmdSetPosition(int client, int args) +{ + if(args < 3) + { + PrintToChat(client, "[SM] Usage: sm_prop_setpos [EX: !prop_setpos 505 -34 17"); + return Plugin_Handled; + } + int Object = g_iLastObject[client]; + char arg1[16]; + char arg2[16]; + char arg3[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + GetCmdArg(3, arg3, sizeof(arg3)); + float vecPosition[3]; + + vecPosition[0] = StringToFloat(arg1); + vecPosition[1] = StringToFloat(arg2); + vecPosition[2] = StringToFloat(arg3); + TeleportEntity(Object, vecPosition, NULL_VECTOR, NULL_VECTOR); + return Plugin_Handled; +} + +/* +////////////////////////////////////////////////////////////////////////////| + Build File Directories | +\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| +*/ + +public void BuildFileDirectories() +{ + for(int Num; Num < sizeof(FolderNames); Num++) + { + if(!DirExists(FolderNames[Num])) + { + CreateDirectory(FolderNames[Num], 509); + } + } +} + +stock char[] Translate(int client, const char[] format, any ...) +{ + char buffer[192]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + return buffer; +} \ No newline at end of file diff --git a/scripting/l4d2_special_control.sp b/scripting/l4d2_special_control.sp new file mode 100644 index 0000000..b23b18d --- /dev/null +++ b/scripting/l4d2_special_control.sp @@ -0,0 +1,164 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define DEBUG 1 + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +//#include + +#define SPECIAL_COUNT 8 + +char SPECIAL_NAMES[SPECIAL_COUNT][] = { + "Smoker", "Boomer", "Hunter", "Spitter", "Jockey", "Charger", "Witch", "Tank" +}; + + +enum SpecialSpawnType { + SpawnType_Vanilla, + SpawnType_GroupsOf4, + SpawnType_Constant +} + +enum SpecialType { + Special_Invalid = -1, + Special_Smoker = 1, + Special_Boomer, + Special_Hunter, + Special_Spitter, + Special_Jockey, + Special_Charger, + Special_Witch, + Special_Tank +} + + +// Changeable settings +#define MIN_SPAWN_DURATION 200 + +public Plugin myinfo = +{ + name = "L4D2 Special Control", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +ConVar cvar_MinPlayersNeeded, cvar_SpawnMode; + +int extraSpecialCount = 1; // 4 + X + +float specialTimers[SPECIAL_COUNT]; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + cvar_MinPlayersNeeded = CreateConVar("l4d_spc_minplayers", "5", "Minimum number of players needed to enable special control.", FCVAR_NONE, true, 1.0); + cvar_SpawnMode = CreateConVar("l4d_spc_spawn_mode", "0", "Controls how the specials will be spawned.\n0 = Vanilla Timing, 1 = ", FCVAR_NONE, true, 1.0); + + CreateTimer(30.0, SpawnTimer, _, TIMER_REPEAT); + CreateTimer(1.0, DebugTimer, _, TIMER_REPEAT); +} + +public Action DebugTimer(Handle h) { + static char buffer[512]; + static bool a; + int start = a ? 5 : 1; + int end = a ? 7 : 4; + buffer[0] = '\0'; + for(int i = 1; i < 6; i++) { + Format(buffer, sizeof(buffer), "%s\n%s: %f (raw %.0f)", buffer, SPECIAL_NAMES[i], specialTimers[i], GetGameTime() - specialTimers[i]); + } + a = !a; + PrintCenterTextAll(buffer); + return Plugin_Continue; +} + +public Action SpawnTimer(Handle h) { + SpecialType special = GetNextPendingSpecial(); + if(special != Special_Invalid) { + int victim = FindSuitableVictim(); + specialTimers[view_as(special) - 1] = GetGameTime(); + SpawnAutoSpecialOnPlayer(special, victim); + } + return Plugin_Continue; +} + +int FindSuitableVictim() { + float distance; + int victim = -1; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) { + if(GetRandomFloat() < 0.1) continue; //10% to skip + float flow = L4D2Direct_GetFlowDistance(i); + if(flow > distance || victim == -1) { + flow = distance; + victim = i; + } + } + } + Debug("Found victim: %N (flow %f)", victim, distance); + return victim; +} + +SpecialType GetNextPendingSpecial() { + float time = GetGameTime(); + int specialId = -1; + float spTime; + for(int i = 1; i < SPECIAL_COUNT; i++) { + if(time - specialTimers[i] > MIN_SPAWN_DURATION && (specialTimers[i] < spTime || specialId == -1)) { + specialId = i; + spTime = specialTimers[i]; + } + } + Debug("Found next special: %s (rel %f)", SPECIAL_NAMES[specialId-1], GetGameTime() - spTime); + return view_as(specialId); +} + + +public void SpawnAutoSpecialOnPlayer(SpecialType type, int target) { + int bot = CreateFakeClient("SpecialControlBot"); + if (bot != 0) { + ChangeClientTeam(bot, 3); + CreateTimer(0.1, Timer_KickBot, bot); + } + int index = view_as(type) - 1; + Debug("Spawning special %s on %N", SPECIAL_NAMES[index], target); + CheatCommand(target, "z_spawn_old", SPECIAL_NAMES[index], "auto"); +} + +stock Action Timer_KickBot(Handle timer, int client) { + if (IsClientInGame(client) && (!IsClientInKickQueue(client))) { + if (IsFakeClient(client)) KickClient(client); + } +} + +stock void CheatCommand(int client, const char[] command, const char[] argument1, const char[] argument2) { + int userFlags = GetUserFlagBits(client); + SetUserFlagBits(client, ADMFLAG_ROOT); + int flags = GetCommandFlags(command); + SetCommandFlags(command, flags & ~FCVAR_CHEAT); + FakeClientCommand(client, "%s %s %s", command, argument1, argument2); + SetCommandFlags(command, flags); + SetUserFlagBits(client, userFlags); +} + + +stock void Debug(const char[] format, any ...) { + #if defined DEBUG + char buffer[192]; + + VFormat(buffer, sizeof(buffer), format, 2); + + PrintToServer("[SpecialControl] %s", buffer); + PrintToConsoleAll("[SpecialControl] %s", buffer); + + #endif +} \ No newline at end of file diff --git a/scripting/l4d2_swarm.sp b/scripting/l4d2_swarm.sp new file mode 100644 index 0000000..078c0cd --- /dev/null +++ b/scripting/l4d2_swarm.sp @@ -0,0 +1,269 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_NAME "L4D2 Swarm" +#define PLUGIN_DESCRIPTION "Swarm a player with zombies to counter the trolls" +#define PLUGIN_AUTHOR "jackzmc" +#define PLUGIN_VERSION "1.0" +#define PLUGIN_URL "" + +#include +#include +#include "jutils.inc" + +ConVar hSwarmDefaultRange; +//Swarm target is a userid +int SwarmTarget, SwarmRadius; + +Handle timer = INVALID_HANDLE; + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +}; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + hSwarmDefaultRange = CreateConVar("sm_swarm_default_range", "7500", "The default range swarms will affect (As a default argument or in use in menus)", FCVAR_NONE, true, 20.0); + SwarmRadius = hSwarmDefaultRange.IntValue; + + LoadTranslations("common.phrases"); + RegAdminCmd("sm_swarm", Cmd_Swarm, ADMFLAG_BAN, "sm_swarm [player] [range] - Zombies swarm player (or random if not set)"); + RegAdminCmd("sm_rush", Cmd_Swarm, ADMFLAG_BAN, "sm_swarm [player] [range] - Zombies swarm player (or random if not set)"); + RegAdminCmd("sm_rushmenu", Cmd_SwarmMenu, ADMFLAG_BAN, "sm_swarmmenu - Open swarm menu"); + RegAdminCmd("sm_rmenu", Cmd_SwarmMenu, ADMFLAG_BAN, "sm_swarmmenu - Open swarm menu"); + + RegAdminCmd("sm_swarmtoggle", Cmd_SwarmToggle, ADMFLAG_BAN | ADMFLAG_CHEATS, "sm_swarmtoggle [range]"); + RegAdminCmd("sm_rushtoggle", Cmd_SwarmToggle, ADMFLAG_BAN | ADMFLAG_CHEATS, "sm_swarmtoggle [range]"); + RegAdminCmd("sm_rt", Cmd_SwarmToggle, ADMFLAG_BAN | ADMFLAG_CHEATS, "sm_swarmtoggle [range]"); + RegAdminCmd("sm_rushtogglemenu", Cmd_SwarmToggleMenu, ADMFLAG_BAN | ADMFLAG_CHEATS, "sm_swarmtogglemenu - Open swarm toggle menu"); + RegAdminCmd("sm_rtmenu", Cmd_SwarmToggleMenu, ADMFLAG_BAN | ADMFLAG_CHEATS, "sm_swarmtogglemenu - Open swarm toggle menu"); + + HookEvent("triggered_car_alarm", Event_CarAlarm); +} + +public void OnMapStart() { + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + CloseHandle(timer); + timer = INVALID_HANDLE; +} + +public void OnClientDisconnect(int client) { + if(SwarmTarget != -1 || timer != INVALID_HANDLE) { + int userid = GetClientUserId(client); + if(userid == SwarmTarget) { + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + CloseHandle(timer); + timer = INVALID_HANDLE; + } + } +} + +public Action Cmd_Swarm(int client, int args) { + if(args == 0) { + SwarmUser(-1, hSwarmDefaultRange.IntValue); + ShowActivity(client, "toggled swarming random player with radius %d", hSwarmDefaultRange.IntValue); + }else{ + char arg1[32], arg2[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + int range = StringToInt(arg2); + if(range <= 0) range = hSwarmDefaultRange.IntValue; + + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE, /* Only allow alive players */ + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + SwarmUser(GetClientUserId(target_list[0]), range); + ShowActivity(client, "swarming player \"%N\" with radius %d", target_list[0], range); + } + return Plugin_Handled; +} + +public Action Cmd_SwarmToggle(int client, int args) { + //SwarmTarget, SwarmRadius + if(args == 0) { + ReplyToCommand(client, "Usage: sm_rushtoggle [radius]"); + }else{ + char arg1[32], arg2[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + GetCmdArg(2, arg2, sizeof(arg2)); + + if(StrEqual(arg1, "disable", true) || StrEqual(arg1, "x", true)) { + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + ReplyToCommand(client, "Deactivated swarm toggle."); + CloseHandle(timer); + timer = INVALID_HANDLE; + return Plugin_Handled; + } + + int range = StringToInt(arg2); + if(range <= 0) range = hSwarmDefaultRange.IntValue; + SwarmRadius = range; + + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + if(target_list[0] == SwarmTarget) { + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + ReplyToCommand(client, "Deactivated swarm toggle."); + CloseHandle(timer); + timer = INVALID_HANDLE; + }else{ + SwarmTarget = GetClientUserId(target_list[0]); + SwarmUser(GetClientUserId(target_list[0]), range); + ShowActivity(client, "toggled swarming player \"%N\" with radius %d", target_list[0], range); + if(timer == INVALID_HANDLE) + timer = CreateTimer(1.0, Timer_Swarm, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + } + } + return Plugin_Handled; +} +public Action Cmd_SwarmMenu(int client, int args) { + Menu menu = new Menu(Handle_SwarmMenu); + menu.SetTitle("Swarm a Player"); + char name[32], idStr[4]; + for(int id = 1; id < MaxClients; id++) { + if(IsClientConnected(id) && IsClientInGame(id) && IsPlayerAlive(id) && GetClientTeam(id) == 2) { + GetClientName(id, name, sizeof(name)); + Format(idStr, sizeof(idStr), "%d", GetClientUserId(id)); + menu.AddItem(idStr, name); + } + } + menu.ExitButton = true; + menu.Display(client, 0); +} +public Action Cmd_SwarmToggleMenu(int client, int args) { + Menu menu = new Menu(Handle_SwarmMenuToggle); + menu.SetTitle("Toggle Swarm On Player"); + menu.AddItem("x", "Disable"); + char name[32], idStr[3]; + for(int id = 1; id < MaxClients; id++) { + if(IsClientConnected(id) && IsClientInGame(id) && IsPlayerAlive(id) && GetClientTeam(id) == 2) { + GetClientName(id, name, sizeof(name)); + Format(idStr, sizeof(idStr), "%d", GetClientUserId(id)); + menu.AddItem(idStr, name); + } + } + menu.ExitButton = true; + menu.Display(client, 0); +} + +public int Handle_SwarmMenu(Menu menu, MenuAction action, int client, int index) +{ + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) + { + char info[4]; + menu.GetItem(index, info, sizeof(info)); + int userid = StringToInt(info); + int clientID = GetClientOfUserId(userid); + SwarmUser(userid, hSwarmDefaultRange.IntValue); + ShowActivity(client, "swarming player \"%N\" with radius %d", clientID, hSwarmDefaultRange.IntValue); + Cmd_SwarmMenu(client, 0); + } else if (action == MenuAction_End) { + delete menu; + } +} + +public int Handle_SwarmMenuToggle(Menu menu, MenuAction action, int client, int index) +{ + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) + { + char info[4]; + menu.GetItem(index, info, sizeof(info)); + if(StrEqual(info, "x", true)) { + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + ShowActivity(client, "disabled swarm toggle"); + CloseHandle(timer); + timer = INVALID_HANDLE; + }else{ + int clickedUser = StringToInt(info); + if(clickedUser != SwarmTarget) { + SwarmTarget = clickedUser; + int clientID = GetClientOfUserId(SwarmTarget); + ShowActivity(client, "toggled swarming player \"%N\" with radius %d", clientID, SwarmRadius); + if(timer == INVALID_HANDLE) + timer = CreateTimer(1.0, Timer_Swarm, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE); + }else{ + SwarmTarget = -1; + SwarmRadius = hSwarmDefaultRange.IntValue; + PrintToChat(client, "Disabled swarm toggle.", SwarmTarget, SwarmRadius); + CloseHandle(timer); + timer = INVALID_HANDLE; + } + } + } else if (action == MenuAction_End) { + delete menu; + } +} + +public Action Timer_Swarm(Handle timerH, any data) { + if(SwarmTarget >= 0) { + SwarmUser(SwarmTarget, SwarmRadius); + return Plugin_Continue; + }else { + return Plugin_Stop; + } +} + + +void SwarmUser(int clientUserId, int range) { + L4D2_RunScript("RushVictim(GetPlayerFromUserID(%d), %d)", clientUserId, range); +} + +public void Event_CarAlarm(Event event, const char[] name, bool dontBroadcast) { + int user = event.GetInt("userid"); + CreateTimer(0.5, Timer_SwarmSingle, user); +} + +public Action Timer_SwarmSingle(Handle hdl, int user) { + SwarmUser(user, hSwarmDefaultRange.IntValue); +} \ No newline at end of file diff --git a/scripting/l4d2_tank_priority.sp b/scripting/l4d2_tank_priority.sp new file mode 100644 index 0000000..f629f1f --- /dev/null +++ b/scripting/l4d2_tank_priority.sp @@ -0,0 +1,187 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +#include +//#include + +public Plugin myinfo = +{ + name = "L4D2 Tank Priority", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://gi thub.com/Jackzmc/sourcemod-plugins" +}; + +#define TANK_CLASS_ID 8 + +static int tankChooseVictimTicks[MAXPLAYERS+1]; //Per tank +static int tankChosenVictim[MAXPLAYERS+1]; +static int targettingTank[MAXPLAYERS+1]; +// tankDamage[tank][client] +static int totalTankDamage[MAXPLAYERS+1][MAXPLAYERS+1]; +static float highestFlow[MAXPLAYERS+1]; +static ArrayList clients; + +static bool finaleStarted; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + clients = new ArrayList(4); + + HookEvent("player_hurt", Event_PlayerHurt); + HookEvent("tank_spawn", Event_TankSpawn); + HookEvent("tank_killed", Event_TankKilled); +} + +public Action L4D2_OnChooseVictim(int attacker, int &curTarget) { + if(finaleStarted) return Plugin_Continue; + int class = GetEntProp(attacker, Prop_Send, "m_zombieClass"); + if(class != TANK_CLASS_ID) return Plugin_Continue; + + //Find a new victim + if(++tankChooseVictimTicks[attacker] >= 200) { + tankChooseVictimTicks[attacker] = 0; + clients.Clear(); + static float tankPos[3], clientPos[3]; + GetClientAbsOrigin(attacker, tankPos); + + float tankFlow = L4D2Direct_GetFlowDistance(attacker); + + // TODO: check if player has been set with tankChosenVictim (or make clone var) + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && !IsPlayerIncapacitated(i) && !IsFakeClient(i) && targettingTank[curTarget] == 0) { + //If a player does less than 50 damage, and has green health add them to list + if(totalTankDamage[attacker][i] < 100 && GetClientHealth(i) > 40) { + GetClientAbsOrigin(i, clientPos); + float flow = L4D2Direct_GetFlowDistance(i); + if(flow > highestFlow[i]) { + highestFlow[i] = flow; + } + // Ignore far behind players who never reached the tank + if(highestFlow[i] < tankFlow) continue; + // float dist = GetVectorDistance(clientPos, tankPos); + // Only add targets who are far enough away from tank + // Add targets where their flow difference is greater than 100 + /* + [TankPriority/debug] Adding player CoCo Nibbz to possible victim list. TankFlow=11057.665039 Flow=10753.859375 Dmg=0 + [TankPriority] Player Selected to target: CoCo Nibbz + [TankPriority/debug] Adding player CoCo Nibbz to possible victim list. TankFlow=10650.624023 Flow=9850.155273 Dmg=0 + */ + if(tankFlow - flow > 500.0) { + PrintToConsoleAll("[TankPriority/debug] Add %N to possible targets. TankFlow=%f Flow=%f HighestFlow=%f Dmg=%d", i, tankFlow, flow, highestFlow[i], totalTankDamage[i]); + int index = clients.Push(i); + clients.Set(index, GetVectorDistance(clientPos, tankPos, true), 1); + clients.Set(index, attacker, 2); + clients.Set(index, tankFlow - flow, 3); + } + } + } + } + + if(clients.Length == 0) return Plugin_Continue; + + clients.SortCustom(Sort_TankTargetter); + curTarget = clients.Get(0); + // tankChosenVictim[attacker] = curTarget; + // targettingTank[curTarget] = attacker; + PrintToConsoleAll("[TankPriority] Player Selected to target: %N", curTarget); + //TODO: Possibly clear totalTankDamage + return Plugin_Changed; + } + + if(tankChosenVictim[attacker] > 0) { + if(IsClientConnected(tankChosenVictim[attacker]) && IsClientInGame(tankChosenVictim[attacker]) && IsPlayerAlive(tankChosenVictim[attacker]) && !IsPlayerIncapacitated(tankChosenVictim[attacker])) { + curTarget = tankChosenVictim[attacker]; + return Plugin_Changed; + } else { + tankChosenVictim[attacker] = 0; + } + } + return Plugin_Continue; +} + +int Sort_TankTargetter(int index1, int index2, Handle array, Handle hndl) { + int client1 = GetArrayCell(array, index1); + int client2 = GetArrayCell(array, index2); + float distance1 = GetArrayCell(array, index1, 1); + float distance2 = GetArrayCell(array, index2, 1); + int tankIndex = GetArrayCell(array, index2, 2); + float flowDiff1 = GetArrayCell(array, index1, 3); + float flowDiff2 = GetArrayCell(array, index2, 3); + /*500 units away, 0 damage vs 600 units away, 0 damage + -> target closest 500 + 500 units away, 10 damage, vs 600 units away 0 damage + 500 - 10 = 450 vs 600 + */ + return (totalTankDamage[tankIndex][client1] + RoundFloat(flowDiff1)) - (totalTankDamage[tankIndex][client2] + RoundFloat(flowDiff2)); +} + +public void Event_PlayerHurt(Event event, const char[] name, bool dontBroadcast) { + int victim = GetClientOfUserId(event.GetInt("userid")); + int attacker = GetClientOfUserId(event.GetInt("attacker")); + int dmg = event.GetInt("dmg_health"); + if(dmg > 0 && attacker > 0 && victim > 0 && IsFakeClient(victim) && GetEntProp(victim, Prop_Send, "m_zombieClass") == TANK_CLASS_ID) { + if(GetClientTeam(victim) == 3 && GetClientTeam(attacker) == 2) { + totalTankDamage[victim][attacker] += dmg; + } + } +} + +public void Event_TankSpawn(Event event, const char[] name, bool dontBroadcast) { + int tank = GetClientOfUserId(GetEventInt(event, "userid")); + if(tank > 0 && IsFakeClient(tank)) { + tankChooseVictimTicks[tank] = -20; + } +} + +public void L4D2_OnChangeFinaleStage_Post(int finaleType, const char[] arg) { + if(finaleType == 1) { + finaleStarted = true; + } +} + +public void Event_TankKilled(Event event, const char[] name, bool dontBroadcast) { + int tank = GetClientOfUserId(GetEventInt(event, "userid")); + if(tank > 0 && IsFakeClient(tank)) { + targettingTank[tankChosenVictim[tank]] = 0; + tankChosenVictim[tank] = 0; + for(int i = 1; i <= MaxClients; i++) { + totalTankDamage[tank][i] = 0; + } + } +} + +bool IsPlayerIncapacitated(int client) { + return (GetEntProp(client, Prop_Send, "m_isIncapacitated") == 1); +} + +public void OnClientDisconnect(int client) { + tankChosenVictim[client] = 0; + targettingTank[client] = 0; + for(int i = 1; i <= MaxClients; i++) { + if(tankChosenVictim[i] == client) { + tankChosenVictim[i] = 0; + targettingTank[i] = 0; + } + // If tank: + totalTankDamage[client][i] = 0; + // If player: + totalTankDamage[i][client] = 0; + } + highestFlow[client] = 0.0; +} + +public void OnMapEnd() { + finaleStarted = false; +} \ No newline at end of file diff --git a/scripting/l4d2_target_test.sp b/scripting/l4d2_target_test.sp new file mode 100644 index 0000000..f76755f --- /dev/null +++ b/scripting/l4d2_target_test.sp @@ -0,0 +1,136 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define GAMEDATA "l4d_target_override" + +#include +#include +#include + +enum L4D2Infected +{ + L4D2Infected_None = 0, + L4D2Infected_Smoker = 1, + L4D2Infected_Boomer = 2, + L4D2Infected_Hunter = 3, + L4D2Infected_Spitter = 4, + L4D2Infected_Jockey = 5, + L4D2Infected_Charger = 6, + L4D2Infected_Witch = 7, + L4D2Infected_Tank = 8 +} + +public Plugin myinfo = +{ + name = "L4D2 target poo", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +bool g_bIsVictim[MAXPLAYERS+1]; +Handle g_hDetour; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D2 only."); + } + + + RegAdminCmd("sm_set_victim", Cmd_SetVictim, ADMFLAG_CHEATS); + + HookEvent("player_death", Event_PlayerDeath); +} + +public void OnPluginEnd() +{ +} + +public Action Cmd_SetVictim(int client, int args) { + if(args == 0) { + ReplyToCommand(client, "Please enter a player to target"); + }else{ + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_ALIVE, /* Only allow alive players */ + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for(int i = 0; i < target_count; i++) { + int victim = target_list[i]; + //g_iSITargets + g_bIsVictim[victim] = !g_bIsVictim[victim]; + ReplyToCommand(client, "Successfully toggled %N victim status to: %b", victim, g_bIsVictim[victim]); + ShowActivity(client, "toggled special infected victim status for %N to %b", victim, g_bIsVictim[victim]); + } + } + return Plugin_Handled; +} + +static int b_attackerTarget[MAXPLAYERS+1]; +public Action L4D2_OnChooseVictim(int attacker, int &curTarget) { + // ========================= + // OVERRIDE VICTIM + // ========================= + L4D2Infected class = view_as(GetEntProp(attacker, Prop_Send, "m_zombieClass")); + if(class != L4D2Infected_Tank) { + int existingTarget = GetClientOfUserId(b_attackerTarget[attacker]); + if(existingTarget > 0) { + curTarget = existingTarget; + return Plugin_Changed; + } + + float closestDistance, survPos[3], spPos[3]; + GetClientAbsOrigin(attacker, spPos); + int closestClient = -1; + for(int i = 1; i <= MaxClients; i++) { + if(g_bIsVictim[i] && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + GetClientAbsOrigin(i, survPos); + float dist = GetVectorDistance(survPos, spPos, true); + if(closestClient == -1 || dist < closestDistance) { + closestDistance = dist; + closestClient = i; + } + } + } + + if(closestClient > 0) { + PrintToConsoleAll("Attacker %N new target: %N", attacker, closestClient); + b_attackerTarget[attacker] = GetClientUserId(closestClient); + curTarget = closestClient; + return Plugin_Changed; + } + } + return Plugin_Continue; +} + +public Action Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + b_attackerTarget[client] = 0; +} + +public void OnClientDisconnect(int client) { + b_attackerTarget[client] = 0; +} \ No newline at end of file diff --git a/scripting/l4d2_turret.sp b/scripting/l4d2_turret.sp new file mode 100644 index 0000000..7361636 --- /dev/null +++ b/scripting/l4d2_turret.sp @@ -0,0 +1,1195 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define TURRET_MAX_RANGE_HUMANS 140.0 // Max range to find humans near. Does not activate if found +#define TURRET_MAX_RANGE_SPECIALS 1700.0 // Max range of specials (including tanks, not witches) +#define TURRET_MAX_RANGE_INFECTED 1500.0 // Max range of infected commons +#define TURRET_ACTIVATION_TIME 5.0 // The time for a new turret to activate + +#define TURRET_MAX_RANGE_HUMANS_OPTIMIZED TURRET_MAX_RANGE_HUMANS * TURRET_MAX_RANGE_HUMANS +#define TURRET_MAX_RANGE_SPECIALS_OPTIMIZED TURRET_MAX_RANGE_SPECIALS * TURRET_MAX_RANGE_SPECIALS +#define TURRET_MAX_RANGE_INFECTED_OPTIMIZED TURRET_MAX_RANGE_INFECTED * TURRET_MAX_RANGE_INFECTED + +#define TURRET_NORMAL_PHASE_TICKS 15 // The number of ticks to be in normal operation +#define TURRET_COMMON_PHASE_TICKS 5 // The number of ticks to clear out commons exclusively + +#define _TURRET_PHASE_TICKS TURRET_NORMAL_PHASE_TICKS + TURRET_COMMON_PHASE_TICKS + +// Taken from l4d_machine, thanks +#define SOUND_IMPACT_HIT "physics/flesh/flesh_impact_bullet1.wav" +#define SOUND_IMPACT_MISS "physics/concrete/concrete_impact_bullet1.wav" +#define SOUND_FIRE "weapons/50cal/50cal_shoot.wav" +#define PARTICLE_WEAPON_TRACER "weapon_tracers_50cal" + +#define PLUGIN_VERSION "2.0" + +#include +#include +#include +#include +#include +// #include + + +#define PARTICLE_ELMOS "st_elmos_fire_cp0" +#define PARTICLE_TES1 "electrical_arc_01_system" +#define ENT_PORTAL_NAME "turret" +#define SOUND_LASER_FIRE "custom/xen_teleport.mp3" +#define TEAM_SPECIALS 3 +#define TEAM_SURVIVORS 2 +// #define SOUND_LASER_FIRE "level/puck_impact.wav" +#include + +enum MountedGun { + MountedGun_Minigun, + MountedGun_50Cal +} +char MountedGunClassname[2][32] = { "prop_minigun_l4d1", "prop_minigun" }; +char MountedGunModel[2][64] = { "models/w_models/weapons/w_minigun.mdl", "models/w_models/weapons/50cal.mdl" }; +float MOUNTED_HEAT_MIN[2] = { 0.01, 0.0 }; +float MOUNTED_HEAT_INCREASE_RATE[2] = { 0.0003333333, 0.0075}; +float MOUNTED_DAMAGE[2] = { 10.0, 100.0 }; +float MOUNTED_FIRE_RATE[2] = { 0.0, 0.25 }; // Only can fire every value game ticks +enum struct MountedTurret { + MountedGun type; + int entity; + float heat; + int target; + bool cooling; + float nextFire; + int poseParamYaw; + int poseParamPitch; + int poseController; //TODO: kill +} +#define MAX_MOUNTED_TURRETS 6 +MountedTurret MTurret[MAX_MOUNTED_TURRETS]; +int MTurretCount; +#define HEAT_DECREASE_RATE 0.01 + +int g_iLaserIndex; +int g_iBeamSprite; +int g_iHaloSprite; +int g_iTracerIndex; + +int manualTargetter; +int g_debugTracer; +Handle thinkTimer; + +ConVar cv_autoBaseDamage; +ConVar cv_manualBaseDamage; + +static int COLOR_RED[4] = { 255, 0, 0, 200 }; +static int COLOR_RED_LIGHT[4] = { 150, 0, 0, 150 }; +int manualTarget = -1; +#define MANUAL_TARGETNAME "turret_target_manual" + +ArrayList turretIds; +Handle SDKCall_LookupPoseParameter; +Handle SDKCall_LoadModel, SDKCall_DeleteModel; +int Animating_StudioHdr; + +/* TODO: +Entity_ChangeOverTime` + + acquire all turrets on plugin start, then go through list + + laser charge up + - yellow to red + - thick to thin + - sound + --- or possibly weak damage to higher? + + on death: kill info_target? keep ref of info_target, or just find via targetname? + + clear all perm props (info_target, env_laser?) on round end + + dont constantly wipe info_target, just teleport + + keep data if ent is being targetted? + + dont target last ent? incase stuck + + optimize by keeping turret pos? + +*/ +public Plugin myinfo = +{ + name = "l4d2 turret", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + GameData gameData = LoadGameConfigFile("l4d2_turret"); + if(!gameData) { + LogError("Missing gamedata l4d2_turret.txt, mounted turret disabled"); + } else { + // = + StartPrepSDKCall(SDKCall_Entity); + // CBaseAnimating::LookupPoseParameter(CStudioHdr*, char const*) + PrepSDKCall_SetFromConf(gameData, SDKConf_Signature, "CBaseAnimating::LookupPoseParameter"); + PrepSDKCall_AddParameter(SDKType_PlainOldData, SDKPass_Plain); + PrepSDKCall_AddParameter(SDKType_String, SDKPass_Pointer); + PrepSDKCall_SetReturnInfo(SDKType_PlainOldData, SDKPass_Plain); + SDKCall_LookupPoseParameter = EndPrepSDKCall(); + if(SDKCall_LookupPoseParameter == null) { + SetFailState("Failed to load SDK call \"CBaseAnimating::LookupPoseParameter\". Update signature in \"plugin.turret\""); + } + + // Taken from https://github.com/Natanel-Shitrit/StudioHdr/blob/d95e93134729361e06a0381a163de8b0b5625bc4/include/studio_hdr.inc#L4722 + // CStudioHdr *ModelSoundsCache_LoadModel( const char *filename ) + StartPrepSDKCall(SDKCall_Static); + PrepSDKCall_SetFromConf(gameData, SDKConf_Signature, "ModelSoundsCache_LoadModel"); + PrepSDKCall_AddParameter(SDKType_String, SDKPass_Pointer); + PrepSDKCall_SetReturnInfo(SDKType_PlainOldData, SDKPass_Plain); + if (!(SDKCall_LoadModel = EndPrepSDKCall())) { + SetFailState("Missing signature 'ModelSoundsCache_LoadModel'"); + } + + // void ModelSoundsCache_FinishModel( CStudioHdr *hdr ) + StartPrepSDKCall(SDKCall_Static); + PrepSDKCall_SetFromConf(gameData, SDKConf_Signature, "ModelSoundsCache_FinishModel"); + PrepSDKCall_AddParameter(SDKType_PlainOldData, SDKPass_Plain); + if (!(SDKCall_DeleteModel = EndPrepSDKCall())) { + SetFailState("Missing signature 'ModelSoundsCache_FinishModel'"); + } + + // TODO: REMOVE + Animating_StudioHdr = gameData.GetOffset("CBaseAnimating::StudioHdr"); + if(Animating_StudioHdr == -1) + SetFailState("Failed to get offset: \"CBaseAnimating::StudioHdr\""); + int iOffset_hLightingOrigin = FindSendPropInfo("CBaseAnimating", "m_hLightingOrigin"); + if (iOffset_hLightingOrigin < 1) + SetFailState("Failed to find send prop: \"m_hLightingOrigin\""); + Animating_StudioHdr += iOffset_hLightingOrigin; + + delete gameData; + } + + turretIds = new ArrayList(); + + FindTurrets(); + + HookEvent("player_death", Event_PlayerDeath); + HookEvent("tank_killed", Event_PlayerDeath); + + cv_autoBaseDamage = CreateConVar("turret_auto_damage", "50.0", "The base damage the automatic turret deals", FCVAR_NONE, true, 0.0); + cv_manualBaseDamage = CreateConVar("turret_manual_damage", "70.0", "The base damage the manual turret deals", FCVAR_NONE, true, 0.0); + + RegAdminCmd("sm_turret", Command_SpawnTurret, ADMFLAG_CHEATS); + RegAdminCmd("sm_rmturrets", Command_RemoveTurrets, ADMFLAG_CHEATS); + RegAdminCmd("sm_rmlaser", Command_RemoveLaserTurret, ADMFLAG_CHEATS); + RegAdminCmd("sm_rmturret", Command_RemoveTurret, ADMFLAG_CHEATS); + RegAdminCmd("sm_manturret", Command_ManualTarget, ADMFLAG_CHEATS); + RegAdminCmd("sm_turret_debug", Command_Debug, ADMFLAG_CHEATS); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + SDKHook(i, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); + } + } +} + +public void OnPluginEnd() { + ClearTurrets(false); +} + +enum TurretState { + Turret_Disabled = -1, + Turret_Invalid = 0, + Turret_Idle, + Turret_Active +} + +TurretState turretState[2048]; +int turretActivatorParticle[2048]; +int entityActiveTurret[2048]; // mapping the turret thats active on victim. [victim] = turret +int entityActiveMounted[2048]; +int turretActiveEntity[2048]; +int turretPhaseOffset[2048]; // slight of offset so they dont all enter the same phase at same time +bool turretIsActiveLaser[2048]; +bool pendingDeletion[2048]; +float turretDamage[2048]; + +int turretCount; + +void FindTurrets() { + int entity = -1; + char targetname[32]; + while ((entity = FindEntityByClassname(entity, "info_particle_system")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrEqual(targetname, "turret")) { + SetupLaserTurret(entity); + PrintToServer("Found existing laser turret: %d", entity); + } + } + entity = -1; + while ((entity = FindEntityByClassname(entity, "prop_minigun")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrContains(targetname, "turret_") > -1) + AddMountedGun(entity, MountedGun_50Cal); + } + entity = -1; + while ((entity = FindEntityByClassname(entity, "prop_minigun_l4d1")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrContains(targetname, "turret_") > -1) + AddMountedGun(entity, MountedGun_Minigun); + } +} + +int AddMountedGun(int entity, MountedGun type) { + MTurret[MTurretCount].entity = EntIndexToEntRef(entity); + MTurret[MTurretCount].type = type; + MTurret[MTurretCount].target = INVALID_ENT_REFERENCE; + MTurret[MTurretCount].heat = 0.0; + MTurret[MTurretCount].cooling = false; + MTurret[MTurretCount].nextFire = GetGameTime(); + + char buffer[64]; + Format(buffer, sizeof(buffer), "turret_%d", entity); + SetEntPropString(entity, Prop_Data, "m_iName", buffer); + + int poseCtrl = CreateEntityByName("point_posecontroller"); + DispatchKeyValue(poseCtrl, "PropName", buffer); + Format(buffer, sizeof(buffer), "turret_%d_posectrl", entity); + DispatchKeyValue(poseCtrl, "targetname", buffer); + DispatchKeyValue(poseCtrl, "PoseParameterName", "MiniGun_Horizontal"); + DispatchKeyValue(poseCtrl, "CycleFrequency", "0"); + DispatchKeyValue(poseCtrl, "FModRate", "0"); + DispatchSpawn(poseCtrl); + SetParent(poseCtrl, entity); + MTurret[MTurretCount].poseController = EntIndexToEntRef(poseCtrl); + + // TODO: do on start + // char buffer[PLATFORM_MAX_PATH]; + // GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, sizeof(buffer)); + + + // Address pStudioHdrClass = view_as
(GetEntData(entity, 0x13E0)); + // // Address pStudioHdrClass = //GetStudioHdr(buffer); + // PrintToServer("MG%d '%s' pStudioHdrClass=%d", MTurretCount, buffer, pStudioHdrClass); + // MTurret[MTurretCount].poseParamYaw = SDKCall(SDKCall_LookupPoseParameter, entity, pStudioHdrClass, "MiniGun_Horizontal"); + // // MTurret[MTurretCount].poseParamPitch = SDKCall(SDKCall_LookupPoseParameter, entity, pStudioHdrClass, "MiniGun_Vertical"); + PrintToServer("MG%d poseParamYaw=%d poseParamPitch=%d", MTurretCount, MTurret[MTurretCount].poseParamYaw, MTurret[MTurretCount].poseParamPitch); + + MTurretCount++; + PrintToServer("Added mounted gun #%d (type=%d)", MTurretCount, type); + if(thinkTimer == null) { + PrintToServer("Created turret think timer"); + thinkTimer = CreateTimer(0.1, Timer_Think, _, TIMER_REPEAT); + } + return MTurretCount; +} + +void RemoveMounted(int index) { + // Shift everything from [index, MTurretCount] down + for(int i = index; i < MTurretCount; i++) { + if(!IsValidEntity(MTurret[i+1].entity)) { + break; + } + MTurret[i].entity = MTurret[i+1].entity; + MTurret[i].type = MTurret[i+1].type; + MTurret[i].target = MTurret[i+1].target; + MTurret[i].heat = MTurret[i+1].heat; + MTurret[i].cooling = MTurret[i+1].cooling; + MTurret[i].nextFire = MTurret[i+1].nextFire; + } + MTurretCount--; +} + +void SetupLaserTurret(int turret, float time = 0.0) { + float pos[3]; + GetEntPropVector(turret, Prop_Send, "m_vecOrigin", pos); + turretState[turret] = Turret_Disabled; + turretActivatorParticle[turret] = INVALID_ENT_REFERENCE; + char targetName[32]; + Format(targetName, sizeof(targetName), "laser_target_%d", turret); + CreateTimer(time, Timer_ActivateTurret, turret); + turretCount++; + if(thinkTimer == null) { + PrintToServer("Created turret think timer"); + thinkTimer = CreateTimer(0.1, Timer_Think, _, TIMER_REPEAT); + } + // Clamp to 0 -> _TURRET_PHASE_TICKS - 1 + turretPhaseOffset[turret] = (turretIds.Length + 1) % (_TURRET_PHASE_TICKS - 1); + turretIds.Push(turret); +} +Action Timer_ActivateTurret(Handle h, int turret) { + turretState[turret] = Turret_Idle; + return Plugin_Handled; +} + +void DeactivateTurret(int turret) { + int particle = EntRefToEntIndex(turretActivatorParticle[turret]); + if(IsValidEntity(particle)) + AcceptEntityInput(particle, "Kill"); + turretActivatorParticle[turret] = INVALID_ENT_REFERENCE; + turretState[turret] = Turret_Idle; + turretActiveEntity[turret] = 0; +} + +int ClearTurrets(bool fullClear = true) { + turretIds.Clear(); + int entity = -1; + int count; + char targetname[32]; + if(fullClear) { + while ((entity = FindEntityByClassname(entity, "info_particle_system")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(turretState[entity] != Turret_Invalid) { + count++; + AcceptEntityInput(entity, "Kill"); + int particle = EntRefToEntIndex(turretActivatorParticle[entity]); + if(IsValidEntity(particle)) + AcceptEntityInput(particle, "Kill"); + + turretState[entity] = Turret_Invalid; + turretActivatorParticle[entity] = 0; + } else if(StrEqual(targetname, "turret_activate")) { + AcceptEntityInput(entity, "Kill"); + } + } + entity = -1; + while ((entity = FindEntityByClassname(entity, "prop_minigun*")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrContains(targetname, "turret_") > -1) { + RemoveEntity(entity); + count++; + } + } + MTurretCount = 0; + } + entity = -1; + while ((entity = FindEntityByClassname(entity, "env_laser")) != INVALID_ENT_REFERENCE) { + if(turretIsActiveLaser[entity]) { + AcceptEntityInput(entity, "TurnOff"); + AcceptEntityInput(entity, "Kill"); + } + } + entity = -1; + while ((entity = FindEntityByClassname(entity, "point_posecontroller")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrContains(targetname, "turret_") > -1) { + RemoveEntity(entity); + } + } + + entity = -1; + while ((entity = FindEntityByClassname(entity, "info_target")) != INVALID_ENT_REFERENCE) { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if(StrContains(targetname, "turret_target_") > -1 || StrEqual(targetname, MANUAL_TARGETNAME)) { + RemoveEntity(entity); + } + } + + + for(int i = 1; i < 2048; i++) { + entityActiveTurret[i] = 0; + entityActiveMounted[i] = 0; + pendingDeletion[i] = false; + } + turretCount = 0; + if(thinkTimer != null) { + delete thinkTimer; + } + return count; +} + +public void OnClientPutInServer(int client) { + pendingDeletion[client] = false; + SDKHook(client, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive); +} + +public void OnClientDisconnect(int client) { + if(manualTargetter == client) + manualTargetter = 0; +} + +public Action OnTakeDamageAlive(int victim, int& attacker, int& inflictor, float& damage, int& damagetype) { + // TODO: see if DMG_ENERGYBEAM + if(attacker > MaxClients && attacker < 2048 && turretIsActiveLaser[attacker] && GetClientTeam(victim) != 3) { + int health = L4D_GetPlayerTempHealth(victim); + L4D_SetPlayerTempHealth(victim, health + 1.0); + damage = 0.0; + return Plugin_Stop; + } + return Plugin_Continue; +} + +public void OnMapEnd() { + manualTarget = -1; + ClearTurrets(); +} + +public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + int index = event.GetInt("entindex", 0); + int turret = entityActiveTurret[client]; + if(turret > 0) { + pendingDeletion[client] = true; + turretActiveEntity[turret] = 0; + DeactivateTurret(turret); + } + entityActiveTurret[index] = 0; + entityActiveTurret[client] = 0; + entityActiveMounted[index] = 0; + entityActiveMounted[client] = 0; +} + +public void OnEntityDestroyed(int entity) { + if(entity > 0 && entity <= 2048) { + pendingDeletion[entity] = false; + int turret = entityActiveTurret[entity]; + if(turret > 0) { + DeactivateTurret(turret); + } + entityActiveTurret[entity] = 0; + entityActiveMounted[entity] = 0; + } +} + + +public Action Command_SpawnTurret(int client, int args) { + if(args == 0) { + ReplyToCommand(client, "Usage: /mkturret "); + return Plugin_Handled; + } + char arg[16]; + GetCmdArg(1, arg, sizeof(arg)); + + float pos[3]; + GetClientEyePosition(client, pos); + float ang[3]; + GetClientEyeAngles(client, ang); + ang[0] = 0.0; + ang[2] = 0.0; + // pos[2] += 10.0; + if(StrEqual(arg, "laser")) { + int base = CreateParticleNamed(ENT_PORTAL_NAME, PARTICLE_ELMOS, pos, NULL_VECTOR); + SetupLaserTurret(base, TURRET_ACTIVATION_TIME); + ReplyToCommand(client, "New laser turret (%d) will activate in %.0f seconds", base, TURRET_ACTIVATION_TIME); + } else { + GetCursorLocation(client, pos); + MountedGun type = MountedGun_Minigun; + if(StrEqual(arg, "minigun")) { + type = MountedGun_Minigun; + } else if(StrEqual(arg, "50cal", false)) { + type = MountedGun_50Cal; + } else { + ReplyToCommand(client, "Unknown turret type. Usage: /mkturret "); + return Plugin_Handled; + } + // TODO: create minigun + int gun = CreateEntityByName(MountedGunClassname[type]); + DispatchKeyValue(gun, "targetname", "turret"); + DispatchKeyValue(gun, "model", MountedGunModel[type]); + TeleportEntity(gun, pos, ang, NULL_VECTOR); + DispatchSpawn(gun); + AddMountedGun(gun, type); + ReplyToCommand(client, "New mounted gun spawned."); + return Plugin_Handled; + } + + return Plugin_Handled; +} + +public Action Command_ManualTarget(int client, int args) { + // Remove the activator particles + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "info_particle_system")) != INVALID_ENT_REFERENCE) { + if(view_as(turretState[entity]) > 0) { + DeactivateTurret(entity); + } + } + + if(manualTargetter == client) { + manualTargetter = 0; + ReplyToCommand(client, "No longer manually targetting"); + return Plugin_Handled; + } else if(manualTargetter > 0) { + ReplyToCommand(manualTargetter, "%N is now manually targetting", client); + } + if(turretCount == 0) { + ReplyToCommand(client, "There are no turrets to manually target"); + } else { + manualTargetter = client; + ReplyToCommand(client, "Now manually targetting"); + } + return Plugin_Handled; +} + +Action Command_RemoveTurrets(int client, int args) { + int count = ClearTurrets(true); + ReplyToCommand(client, "Removed %d turrets", count); + return Plugin_Handled; +} + +Action Command_Debug(int client, int args) { + if(g_debugTracer == client) { + g_debugTracer = 0; + ReplyToCommand(client, "Debug mode off"); + } else { + g_debugTracer = client; + ReplyToCommand(client, "Debug mode on"); + } +} + +Action Command_RemoveLaserTurret(int client, int args) { + if(turretIds.Length == 0) { + ReplyToCommand(client, "No turrets to remove"); + } else { + int lastTurret = turretIds.Get(turretIds.Length - 1); + ReplyToCommand(client, "Removed last turret %d", lastTurret); + } + return Plugin_Handled; +} + +Action Command_RemoveTurret(int client, int args) { + int target = GetClientAimTarget(client, false); + if(target >= MaxClients) { + int targetRef = EntIndexToEntRef(target); + for(int i = 0; i < MTurretCount; i++) { + if(MTurret[i].entity == targetRef) { + RemoveMounted(i); + ReplyToCommand(client, "Removed mounted turret #%d", i); + return Plugin_Handled; + } + } + ReplyToCommand(client, "Not a valid turret"); + } else { + ReplyToCommand(client, "You are not looking at a turret"); + } + return Plugin_Handled; +} + + +bool IsTargetValid(int targetRef) { + if(!IsValidEntity(targetRef)) return false; + return GetEntProp(targetRef, Prop_Data, "m_iHealth") > 0; +} + +void GetAngles(const float pos[3], const float endPos[3], float angles[3]) { + float result[3]; + MakeVectorFromPoints(endPos, pos, result); + GetVectorAngles(result, angles); + if(angles[0] >= 270){ + angles[0] -= 270; + angles[0] = (90-angles[0]); + }else{ + if(angles[0] <= 90){ + angles[0] *= -1; + } + } + angles[1] -= 180; +} + +void ShowTracer(float pos[3], float endPos[3]) { + TE_SetupParticle(g_iTracerIndex, pos, endPos); + TE_SendToAll(); +} + +Address GetStudioHdr(const char[] model) { + if (!model[0]) { + LogError("empty model path"); + } + // Create a new CStudioHdr variable based on the model path. + Address CStudioHdr = SDKCall(SDKCall_LoadModel, model); + if (!CStudioHdr) { + return Address_Null; + } + // Load 'studiohdr_t *m_pStudioHdr' from 'CStudioHdr' pointer. (can be treated as if it was a studiohdr_t **) + Address m_pStudioHdr = view_as
(LoadFromAddress(CStudioHdr, NumberType_Int32)); + // Delete the CStudioHdr variable to not leak memory. + SDKCall(SDKCall_DeleteModel, CStudioHdr); + return m_pStudioHdr; +} + +void SetPoseParameter(int entity, int iParameter, float flStart, float flEnd, float flValue) { + float ctlValue = (flValue - flStart) / (flEnd - flStart); + if (ctlValue < 0) ctlValue = 0.0; + if (ctlValue > 1) ctlValue = 1.0; + + SetEntPropFloat(entity, Prop_Send, "m_flPoseParameter", ctlValue, iParameter); +} + + +void SetPoseControllerParameter(int entity, const char[] parameter, float flStart, float flEnd, float flValue) { + float ctlValue = (flValue - flStart) / (flEnd - flStart); + if (ctlValue < 0) ctlValue = 0.0; + if (ctlValue > 1) ctlValue = 1.0; + + SetVariantString(parameter); + AcceptEntityInput(entity, "SetPoseParameterName"); + SetVariantFloat(ctlValue); + AcceptEntityInput(entity, "SetPoseValue"); + PrintToServer("SetPoseControllerParameter: ent=%d param=%s value=%f", entity, parameter, ctlValue); +} + + +public Action Timer_Think(Handle h) { + if( manualTargetter > 0) return Plugin_Continue; + // Probably better to just store from CreateParticle + static int entity; + entity = -1; + // static char targetname[32]; + static float pos[3], targetPos[3], angles[3], turretAngles[3]; + static int count, target, tick; + for(int i = 0; i < MTurretCount; i++) { + GetEntPropVector(MTurret[i].entity, Prop_Send, "m_vecOrigin", pos); + GetEntPropVector(MTurret[i].entity, Prop_Send, "m_angRotation", turretAngles); + if(!IsTargetValid(MTurret[i].target)) { + MTurret[i].target = FindNearestVisibleEntity("infected", pos, TURRET_MAX_RANGE_INFECTED_OPTIMIZED, MTurret[i].entity); + } + + if(MTurret[i].target > 0 && !MTurret[i].cooling) { + // Map to a bogus value: + entityActiveMounted[MTurret[i].target] = i; + MTurret[i].heat += MOUNTED_HEAT_INCREASE_RATE[MTurret[i].type]; + // PrintToServer("mg%d warming - heat:%f min:%f", i, MTurret[i].heat, MOUNTED_HEAT_MIN[MTurret[i].type]); + if(MTurret[i].heat >= 1.0) { + MTurret[i].heat = 1.0; + MTurret[i].cooling = true; + SetEntProp(MTurret[i].entity, Prop_Send, "m_firing", 0); + SetEntProp(MTurret[i].entity, Prop_Send, "m_overheated", 1); + } + else if(MTurret[i].heat >= MOUNTED_HEAT_MIN[MTurret[i].type] && GetGameTime() >= MTurret[i].nextFire) { + // Can fire now + SetEntProp(MTurret[i].entity, Prop_Send, "m_firing", 1); + // TODO: look at + if(MTurret[i].type == MountedGun_50Cal) + EmitSoundToAll(SOUND_FIRE, 0, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 1.0, SNDPITCH_NORMAL, -1, pos, NULL_VECTOR, true, 0.0); + GetEntPropVector(MTurret[i].target, Prop_Send, "m_vecOrigin", targetPos); + targetPos[2] += 40.0; // hit infected better + GetAngles(pos, targetPos, angles); + float angle = 0.5 + (angles[1] - turretAngles[1]) / FLOAT_PI; + SetVariantString("Minigun_Horizontal"); + AcceptEntityInput(MTurret[i].poseController, "SetPoseParameterName"); + SetVariantFloat(angle); + AcceptEntityInput(MTurret[i].poseController, "SetPoseValue"); + PrintToConsoleAll("angle:%f", angle); + // SetPoseControllerParameter(MTurret[i].poseController, "MiniGun_Vertical", -90.0, 90.0, angle); + // angle = 0.5 + (angles[0] - turretAngles[0]) / FLOAT_PI; + // SetPoseControllerParameter(MTurret[i].poseController, "MiniGun_Horizontal", -90.0, 90.0, angle); + // SetPoseParameter(MTurret[i].entity, 0, -90.0, 90.0, angles[0]); + // SetPoseParameter(MTurret[i].entity, 1, -90.0, 90.0, angles[1]); + TR_TraceRay(pos, targetPos, 0, RayType_EndPoint); + if(TR_DidHit()) { + // Obstacle + TR_GetEndPosition(targetPos); + EmitSoundToAll(SOUND_IMPACT_MISS, 0, SNDCHAN_AUTO, SNDLEVEL_NORMAL, SND_NOFLAGS, 1.0, SNDPITCH_NORMAL, -1, targetPos, NULL_VECTOR, true, 0.0); + } else { + EmitSoundToAll(SOUND_IMPACT_HIT, 0, SNDCHAN_AUTO, SNDLEVEL_NORMAL, SND_NOFLAGS, 1.0, SNDPITCH_NORMAL, -1, targetPos, NULL_VECTOR, true, 0.0); + // TODO: improve damage + SDKHooks_TakeDamage(MTurret[i].target, MTurret[i].entity, MTurret[i].entity, MOUNTED_DAMAGE[MTurret[i].type], DMG_BLAST); + } + TE_SetupTracerSound(pos, targetPos); + TE_SendToAll(); + // Get the end of the barrel + GetHorizontalPositionFromOrigin(pos, turretAngles, 10.0, pos); + pos[2] += 45.0; + ShowTracer(pos, targetPos); + TE_SetupMuzzleFlash(pos, turretAngles, 1.0, 1); + TE_SendToAll(); + // For now, make 50 cal swap target (for commons) + if(MTurret[i].type == MountedGun_50Cal) { + MTurret[i].target = INVALID_ENT_REFERENCE; + } + MTurret[i].nextFire = GetGameTime() + MOUNTED_FIRE_RATE[MTurret[i].type]; + } + } else { + MTurret[i].heat -= HEAT_DECREASE_RATE; + SetEntProp(MTurret[i].entity, Prop_Send, "m_firing", 0); + if(MTurret[i].heat < 0.0) { + MTurret[i].heat = 0.0; + MTurret[i].cooling = false; + SetEntProp(MTurret[i].entity, Prop_Send, "m_overheated", 0); + } + } + SetEntPropFloat(MTurret[i].entity, Prop_Send, "m_heat", MTurret[i].heat); + } + if(turretCount > 0) { + entity = -1; + while ((entity = FindEntityByClassname(entity, "info_particle_system")) != INVALID_ENT_REFERENCE) { + // GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + // if(StrEqual(targetname, ENT_PORTAL_NAME)) { + if(view_as(turretState[entity]) > 0) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + if(turretState[entity] == Turret_Active) { + // Keep targetting if can view + target = EntRefToEntIndex(turretActiveEntity[entity]); + if(target > 0 && IsValidEntity(target)) { + if(target <= MaxClients) { + if(IsPlayerAlive(target) && GetEntProp(target, Prop_Data, "m_bClientSideRagdoll") == 0 && CanSeeEntity(pos, target)) { + FireTurretAuto(pos, target, turretDamage[entity]); + continue; + } + } else if(CanSeeEntity(pos, target)) { + FireTurretAuto(pos, target, turretDamage[entity]); + continue; + } + } + DeactivateTurret(entity); + } + // Skip activation if a survivor is too close + if(FindNearestClient(TEAM_SURVIVORS, pos, TURRET_MAX_RANGE_HUMANS_OPTIMIZED) > 0) { + continue; + } + + bool inNormalPhase = ((tick + turretPhaseOffset[entity]) % _TURRET_PHASE_TICKS) <= TURRET_NORMAL_PHASE_TICKS; + + // Find a target, in this order: Tank Rock -> Specials -> Infected + float damage = cv_autoBaseDamage.FloatValue; + target = -1; + if(inNormalPhase) { + target = FindNearestVisibleEntity("tank_rock", pos, TURRET_MAX_RANGE_SPECIALS_OPTIMIZED, entity); + if(target > 0) { + CreateTimer(1.2, Timer_KillRock, EntIndexToEntRef(target)); + damage = 1000.0; + } + if(target <= 0) target = FindNearestVisibleClient(TEAM_SPECIALS, pos, TURRET_MAX_RANGE_SPECIALS_OPTIMIZED); + } + if(target <= 0) target = FindNearestVisibleEntity("infected", pos, TURRET_MAX_RANGE_INFECTED_OPTIMIZED, entity); + if(target > 0) { + turretDamage[entity] = damage; + entityActiveTurret[target] = entity; + turretActiveEntity[entity] = EntIndexToEntRef(target); + turretActivatorParticle[entity] = EntIndexToEntRef(CreateParticleNamed("turret_activate", PARTICLE_TES1, pos, NULL_VECTOR)); + // AcceptEntityInput(turretActivatorParticle[entity], "Start"); + FireTurretAuto(pos, target, turretDamage[entity]); + turretState[entity] = Turret_Active; + } + // Optimization incase there's multiple info_particle_system + if(++count > turretCount) { + count = 0; + break; + } + } + } + if(++tick >= _TURRET_PHASE_TICKS) { + tick = 0; + } + } + return Plugin_Continue; +} + + +public Action Timer_KillRock(Handle h, int ref) { + int rock = EntRefToEntIndex(ref); + if(rock != INVALID_ENT_REFERENCE) { + L4D_DetonateProjectile(rock); + } + return Plugin_Handled; +} + +static float TURRET_LASER_COLOR[3] = { 0.0, 255.0, 255.0 }; + +void FireTurretAuto(const float origin[3], int targetEntity, float damage = 105.0) { + int laser = CreateLaserAuto(origin, targetEntity, TURRET_LASER_COLOR, damage, 1.0, 0.2); + EmitSoundToAll(SOUND_LASER_FIRE, laser, SNDCHAN_WEAPON, .flags = SND_CHANGEPITCH, .pitch = 150); + turretIsActiveLaser[laser] = true; +} + +void FireTurret(const float origin[3], const char[] targetName, float damage = 105.0, bool emitSound = true) { + int laser = CreateLaser(origin, targetName, TURRET_LASER_COLOR, damage, 1.0, 0.1); + if(emitSound) + EmitSoundToAll(SOUND_LASER_FIRE, laser, SNDCHAN_WEAPON, .flags = SND_CHANGEPITCH, .pitch = 150); + turretIsActiveLaser[laser] = true; +} + +stock int CreateLaser(const float origin[3], const char[] targetName, float color[3], float damage, float width, float duration) { + int laser = CreateEntityByName("env_laser"); + if(laser > 0) { + DispatchKeyValue(laser, "targetname", "sm_laser"); + DispatchKeyValue(laser, "LaserTarget", targetName); + DispatchKeyValue(laser, "spawnflags", "1"); + // DispatchKeyValue(laser, "dissolvetype", "2"); + DispatchKeyValue(laser, "NoiseAmplitude", "1"); + DispatchKeyValueFloat(laser, "damage", damage); + DispatchKeyValueFloat(laser, "life", duration); + DispatchKeyValueVector(laser, "rendercolor", color); + DispatchKeyValue(laser, "texture", "sprites/laserbeam.spr"); + + TeleportEntity(laser, origin); + SetEntPropFloat(laser, Prop_Data, "m_fWidth", width); + + DispatchSpawn(laser); + + if(duration > 0) + CreateTimer(duration, Timer_Kill, laser); + } + return laser; +} + +// Creates a beam from beginTarget to endTarget. If target name starts with NUL, then will not be set. See env_beam on wiki +stock int CreateBeam(const char[] beginTarget, const float center[3], const char[] endTarget, float color[3], float damage, float width, float duration) { + int laser = CreateEntityByName("env_beam"); + if(laser > 0) { + DispatchKeyValue(laser, "targetname", "sm_laserbeam"); + if(beginTarget[0] != '\0') + DispatchKeyValue(laser, "LightningStart", beginTarget); + if(endTarget[0] != '\0') + DispatchKeyValue(laser, "LightningEnd", endTarget); + DispatchKeyValue(laser, "spawnflags", "1"); + // DispatchKeyValue(laser, "dissolvetype", "2"); + DispatchKeyValue(laser, "NoiseAmplitude", "1"); + DispatchKeyValueFloat(laser, "damage", damage); + DispatchKeyValueFloat(laser, "life", duration); + DispatchKeyValueVector(laser, "rendercolor", color); + DispatchKeyValue(laser, "texture", "sprites/laserbeam.spr"); + + TeleportEntity(laser, center); + DispatchKeyValueFloat(laser, "BoltWidth", width); + + DispatchSpawn(laser); + + if(duration > 0) + CreateTimer(duration, Timer_Kill, laser); + } + return laser; +} + + +stock int CreateLaserAuto(const float origin[3], int targetEnt, float color[3], float damage = 0.0, float width, float duration = 5.0, bool createInfoTarget = true) { + static char targetName[32]; + Format(targetName, sizeof(targetName), "laser_target_%d", targetEnt); + + static float pos[3]; + GetEntPropVector(targetEnt, Prop_Send, "m_vecOrigin", pos); + pos[2] += 30.0; + int target = CreateTarget(pos, targetName, duration); + SetParent(target, targetEnt); + + return CreateLaser(origin, targetName, color, damage, width, duration); +} + +int CreateTarget(const float origin[3], const char[] targetName, float duration = 0.0) { + int target = CreateEntityByName("info_target"); + DispatchKeyValue(target, "targetname", targetName); + + TeleportEntity(target, origin, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(target); + if(duration > 0.0) { + CreateTimer(duration, Timer_Kill, target); + } + return target; +} + + +stock int FindNearestClient(int team, const float origin[3], float maxRange = 0.0) { + int client = -1; + float closestDist, pos[3]; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == team && !pendingDeletion[i]) { + GetClientAbsOrigin(i, pos); + float distance = GetVectorDistance(origin, pos, true); + if(maxRange > 0.0 && distance > maxRange) continue; + if(client == -1 || distance <= closestDist) { + client = i; + closestDist = distance; + } + } + } + return client; +} + +stock int FindNearestVisibleClient(int team, const float origin[3], float maxRange = 0.0) { + int client = -1; + float closestDist, pos[3]; + for(int i = 1; i <= MaxClients; i++) { + if(!pendingDeletion[i] && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == team) { + GetClientAbsOrigin(i, pos); + float distance = GetVectorDistance(origin, pos, true); + if(maxRange > 0.0 && distance > maxRange) continue; + if(distance <= closestDist || client == -1) { + if(CanSeePoint(origin, pos)) { + // Priority: Pinned survivors + if(L4D_GetPinnedSurvivor(i) > 0) { + return i; + } + client = i; + closestDist = distance; + } + } + } + } + return client; +} + +stock int FindNearVisibleEntityCone(const char[] classname, const float origin[3], const float angles[3], float maxAngles, float maxRange, int ignoreEntity) { + int entity = -1; + static float pos[3]; + while ((entity = FindEntityByClassname(entity, classname)) != INVALID_ENT_REFERENCE) { + // Skip entity, it's already being targetted + if(entityActiveTurret[entity] > 0 || entityActiveMounted[entity] > 0) continue; + bool ragdolled = GetEntProp(entity, Prop_Data, "m_bClientSideRagdoll") == 1; + if(ragdolled) continue; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + if(maxRange > 0.0 && GetVectorDistance(origin, pos, true) > maxRange) continue; + pos[2] += 40.0; + // TODO: fail if the computed angles to reach 'pos' are > angles + maxAngles + if(CanSeePoint(origin, pos, ignoreEntity)) { + return entity; + } + return entity; + } + return -1; +} + +stock int FindNearestVisibleEntity(const char[] classname, const float origin[3], float maxRange = 0.0, int ignoreEntity = 0) { + int entity = -1; + static float pos[3]; + while ((entity = FindEntityByClassname(entity, classname)) != INVALID_ENT_REFERENCE) { + // Skip entity, it's already being targetted + if(entityActiveTurret[entity] > 0 || entityActiveMounted[entity] > 0) continue; + bool ragdolled = GetEntProp(entity, Prop_Data, "m_bClientSideRagdoll") == 1; + if(ragdolled) continue; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos); + if(maxRange > 0.0 && GetVectorDistance(origin, pos, true) > maxRange) continue; + pos[2] += 40.0; + if(CanSeePoint(origin, pos, ignoreEntity)) { + return entity; + } + return entity; + } + return -1; +} + +stock bool CanSeePoint(const float origin[3], const float point[3], int ignoreEntity = 0) { + TR_TraceRayFilter(origin, point, MASK_SHOT, RayType_EndPoint, Filter_CanSeeEntity, ignoreEntity); + + return !TR_DidHit(); // Can see point if no collisions +} + +stock bool CanSeeEntity(const float origin[3], int entity) { + static float point[3]; + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", point); + TR_TraceRayFilter(origin, point, MASK_SHOT, RayType_EndPoint, Filter_CanSeeEntity, entity); + + return TR_GetEntityIndex() == entity; // Can see point if no collisions +} + +bool Filter_CanSeeEntity(int entity, int contentsMask, int data) { + return entity != data; +} + +bool Filter_IgnoreEntityWorld(int entity, int contentsMask, int data) { + return entity != data && entity != 0; +} + + +public void OnMapStart() { + PrecacheParticle(PARTICLE_ELMOS); + PrecacheParticle(PARTICLE_TES1); + g_iTracerIndex = GetParticleIndex(PARTICLE_WEAPON_TRACER); + g_iBeamSprite = PrecacheModel("sprites/laser.vmt", true); + g_iLaserIndex = PrecacheModel("materials/sprites/laserbeam.vmt", true); + PrecacheSound(SOUND_LASER_FIRE); + PrecacheSound(SOUND_FIRE); + PrecacheSound(SOUND_IMPACT_HIT); + PrecacheSound(SOUND_IMPACT_MISS); + PrecacheModel(MountedGunModel[0]); + PrecacheModel(MountedGunModel[1]); + if(g_iLaserIndex == 0) { + LogError("g_iLaserIndex failed"); + } +} + + +stock int CreateParticleNamed(const char[] targetname, const char[] sParticle, const float vPos[3], const float vAng[3], int parent = 0) { + int entity = CreateEntityByName("info_particle_system"); + if( entity != -1 ) { + DispatchKeyValue(entity, "effect_name", sParticle); + DispatchKeyValue(entity, "targetname", targetname); + DispatchSpawn(entity); + ActivateEntity(entity); + AcceptEntityInput(entity, "start"); + + if(parent){ + SetParent(entity, parent); + } + + TeleportEntity(entity, vPos, vAng, NULL_VECTOR); + + // Refire + float refire = 0.2; + static char sTemp[64]; + Format(sTemp, sizeof(sTemp), "OnUser1 !self:Stop::%f:-1", refire - 0.05); + SetVariantString(sTemp); + AcceptEntityInput(entity, "AddOutput"); + Format(sTemp, sizeof(sTemp), "OnUser1 !self:FireUser2::%f:-1", refire); + SetVariantString(sTemp); + AcceptEntityInput(entity, "AddOutput"); + AcceptEntityInput(entity, "FireUser1"); + + SetVariantString("OnUser2 !self:Start::0:-1"); + AcceptEntityInput(entity, "AddOutput"); + SetVariantString("OnUser2 !self:FireUser1::0:-1"); + AcceptEntityInput(entity, "AddOutput"); + + return entity; + } + return -1; +} +/*#define MAX_IGNORE_TRACE 2 +static char IGNORE_TRACE[MAX_IGNORE_TRACE][] = { + "env_physics_blocker", + "env_player_blocker" +};*/ +#define MAX_WHITELISTED_AUTO_AIM_TARGETS 3 +static char WHITELISTED_AUTO_AIM_TARGETS[MAX_WHITELISTED_AUTO_AIM_TARGETS][] = { + "tank_rock", + "infected", + "witch" +}; + + +bool Filter_ManualTarget(int entity, int contentsMask, int data) { + if(entity == 0 || entity == data) return true; + if(entity == manualTarget || entity == manualTargetter) return false; + return true; + /*static char classname[32]; + GetEntityClassname(entity, classname, sizeof(classname)); + for(int i = 0; i < MAX_IGNORE_TRACE; i++) { + if(StrEqual(IGNORE_TRACE[i], classname)) { + return false; + } + } + return true;*/ +} + +bool Filter_ManualTargetSights(int entity, int contentsMask, int data) { + if(entity == 0 || entity == data) return true; + if(entity == manualTarget || entity == manualTargetter) return false; + if(entity <= MaxClients) return GetClientTeam(entity) == 3; + static char classname[32]; + GetEntityClassname(entity, classname, sizeof(classname)); + for(int i = 0; i < MAX_WHITELISTED_AUTO_AIM_TARGETS; i++) { + if(StrEqual(WHITELISTED_AUTO_AIM_TARGETS[i], classname)) { + return false; + } + } + return true; +} + +float HULL_DEBUG_MIN[3] = { -50.0, -50.0, -20.0 }; +float HULL_DEBUG_MAX[3] = { 50.0, 50.0, 20.0 }; + +bool DebugEnumerator(int entity, int data) { + if(entity == 0 || entity == data) return false; + GlowEntity(entity, 3.0); + return false; +} + +public Action OnPlayerRunCmd(int client, int& buttons, int& impulse, float vel[3], float angles[3], int& weapon, int& subtype, int& cmdnum, int& tickcount, int& seed, int mouse[2]) { + if(client == g_debugTracer) { + float pos[3]; + float ang[3]; + GetClientEyePosition(client, pos); + GetClientEyeAngles(client, ang); + TR_EnumerateEntitiesSphere(pos, 100.0, PARTITION_NON_STATIC_EDICTS, DebugEnumerator, client); + // TR_TraceHullFilter(pos, ang, HULL_DEBUG_MIN, HULL_DEBUG_MAX, MASK_SOLID, Filter_IgnoreEntityWorld, client); + // if(TR_DidHit()) { + // TR_GetEndPosition(pos); + + // // TODO: use enumerator + // int ent = TR_GetEntityIndex(); + // PrintCenterText(client, "HIT %d - %.0f %.0f %.0f", ent, pos[0], pos[1], pos[2]); + // if(ent > 0) { + // GlowEntity(ent, 3.0); + // } + // } else { + // PrintCenterText(client, "MISS"); + // } + } + if(client == manualTargetter && turretCount > 0 && tickcount % 3 == 0) { + static float pos[3], aimPos[3], orgPos[3]; + GetClientEyePosition(client, orgPos); + + // Run a ray trace to find a suitable position + // TODO: Possibly run per-turret for more accurate preview... but it's already lag fest + TR_TraceRayFilter(orgPos, angles, MASK_SHOT, RayType_Infinite, Filter_ManualTarget); + if(manualTarget <= 0 || !IsValidEntity(manualTarget)) manualTarget = CreateTarget(aimPos, MANUAL_TARGETNAME); + + // Disable aim snapping if player is holding WALK (which is apparently IN_SPEED) + bool aimSnapping = ~buttons & IN_SPEED > 0; + int targetEntity = TR_GetEntityIndex(); + TR_GetEndPosition(aimPos); + + if(aimSnapping) + ComputeAutoAim(targetEntity, aimPos); + + TeleportEntity(manualTarget, aimPos, NULL_VECTOR, NULL_VECTOR); + + if(buttons & IN_ATTACK) { + PhysicsExplode(aimPos, 20, 20.0, true); + TE_SetupExplodeForce(aimPos, 20.0, 20.0); + } + + // Activate all turrets + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, "info_particle_system")) != INVALID_ENT_REFERENCE) { + if(view_as(turretState[entity]) > 0) { + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", orgPos); + if(buttons & IN_ATTACK) { + FireTurret(orgPos, MANUAL_TARGETNAME, cv_manualBaseDamage.FloatValue, tickcount % 6 == 0); + } else { + TR_TraceRayFilter(orgPos, aimPos, MASK_SOLID, RayType_EndPoint, Filter_ManualTargetSights, targetEntity); + pos = aimPos; + if(TR_DidHit()) { + TR_GetEndPosition(pos); + TE_SetupBeamPoints(orgPos, pos, g_iLaserIndex, 0, 0, 1, 0.1, 0.1, 0.1, 0, 0.0, COLOR_RED_LIGHT, 1); + } else { + TE_SetupBeamPoints(orgPos, aimPos, g_iLaserIndex, 0, 0, 1, 0.1, 0.1, 0.1, 0, 0.0, COLOR_RED, 2); + } + // if(aimSnapping) ComputeAutoAim(TR_GetEntityIndex(), pos); + TE_SendToAll(); + } + } + } + + buttons &= ~IN_ATTACK; + SetEntPropFloat(client, Prop_Send, "m_flNextAttack", GetGameTime() + 1.0); + return Plugin_Changed; + } + return Plugin_Continue; +} + +bool ComputeAutoAim(int possibleTarget, float pos[3]) { + + static char classname[64]; + + if(possibleTarget > 0) { + if(possibleTarget > MaxClients) { + // Check if aimed non-player entity is an entity to be auto aimed at + GetEntityClassname(possibleTarget, classname, sizeof(classname)); + for(int i = 0; i < MAX_WHITELISTED_AUTO_AIM_TARGETS; i++) { + if(StrEqual(WHITELISTED_AUTO_AIM_TARGETS[i], classname)) { + GetEntPropVector(possibleTarget, Prop_Send, "m_vecOrigin", pos); + pos[2] += 40.0; + return true; + } + } + } else if(GetClientTeam(possibleTarget) == 3) { + // Target is an infected player, auto aim + GetClientEyePosition(possibleTarget, pos); + pos[2] -= 15.0; + return true; + } + } + return false; +} + +public Action Timer_Kill(Handle h, int target) { + if(IsValidEntity(target)) // TODO: See if necessary + AcceptEntityInput(target, "Kill"); + return Plugin_Handled; +} + diff --git a/scripting/l4d2_vocalize_control.sp b/scripting/l4d2_vocalize_control.sp new file mode 100644 index 0000000..c2f2cb6 --- /dev/null +++ b/scripting/l4d2_vocalize_control.sp @@ -0,0 +1,110 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +//#include + +public Plugin myinfo = +{ + name = "L4D2 Vocalize Control", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +ArrayList gaggedPlayers[MAXPLAYERS]; + +public void OnPluginStart() +{ + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead2) + { + SetFailState("This plugin is for L4D2 only."); + } + + for(int i = 0; i < sizeof(gaggedPlayers); i++) { + gaggedPlayers[i] = new ArrayList(MAXPLAYERS - 1); + } + + HookEvent("player_disconnect", Event_PlayerDisconnect); + + RegConsoleCmd("sm_vgag", Cmd_VGag, "Gags a player\'s vocalizations locally"); + AddNormalSoundHook(SoundHook); +} + +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + //Clear the player's list of gagged + gaggedPlayers[client].Clear(); + //Remove this player from any other player's gag list + for(int i = 0; i <= MaxClients; i++) { + int index = gaggedPlayers[i].FindValue(client); + if(index > -1) { + gaggedPlayers[i].Erase(index); + } + } + } +} + +public Action Cmd_VGag(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Usage: sm_vgag - vocalize gag someone for yourself only"); + } else { + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + MAXPLAYERS, + COMMAND_FILTER_ALIVE | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + for (int i = 0; i < target_count; i++) { + int playerIndex = gaggedPlayers[client].FindValue(target_list[i]); + if(playerIndex > -1) { + gaggedPlayers[client].Erase(playerIndex); + ReplyToCommand(client, "Vocalize ungagged %N for yourself.", target_list[i]); + }else{ + gaggedPlayers[client].Push(target_list[i]); + ReplyToCommand(client, "Vocalize gagged %N for yourself. Type command again to ungag.", target_list[i]); + } + } + } + return Plugin_Handled; +} + +public Action SoundHook(int clients[MAXPLAYERS], int& numClients, char sample[PLATFORM_MAX_PATH], int& entity, int& channel, float& volume, int& level, int& pitch, int& flags, char soundEntry[PLATFORM_MAX_PATH], int& seed) { + if(numClients > 0 && entity > 0 && entity <= MaxClients) { + if(StrContains(sample, "survivor\\voice") > -1) { + for(int i = 0; i < numClients; i++) { + int client = clients[i]; + if(gaggedPlayers[client].FindValue(entity) > -1) { + // Swap gagged player to end of list, then reduce array count by one. + int swap = clients[numClients - 1]; + clients[numClients - 1] = client; + clients[i] = swap; + numClients -= 1; + return Plugin_Handled; + } + } + } + + } + return Plugin_Continue; +} diff --git a/scripting/l4d_anti_rush.sp b/scripting/l4d_anti_rush.sp new file mode 100644 index 0000000..a3c64a8 --- /dev/null +++ b/scripting/l4d_anti_rush.sp @@ -0,0 +1,1057 @@ +/* +* Anti Rush +* Copyright (C) 2023 Silvers +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + + + +#define PLUGIN_VERSION "1.19" +#define DEBUG_BENCHMARK 0 // 0=Off. 1=Benchmark logic function. + +/*====================================================================================== + Plugin Info: + +* Name : [L4D & L4D2] Anti Rush +* Author : SilverShot +* Descrp : Slowdown or teleport rushers and slackers back to the group. Uses flow distance for accuracy. +* Link : https://forums.alliedmods.net/showthread.php?t=322392 +* Plugins : https://sourcemod.net/plugins.php?exact=exact&sortby=title&search=1&author=Silvers + +======================================================================================== + Change Log: + +1.19 (10-Mar-2023) + - Added cvar "l4d_anti_rush_health" to hurt players who are rushing. Requested by "Voevoda". + - Changed cvar "l4d_anti_rush_type" to allow disabling teleport or slowdown, to only enable health drain. + - Translation phrases updated to support the health drain only type. Thanks to "Voevoda" and "HarryPotter" for updating Russian and Chinese translations. + +1.18 (01-Jun-2022) + - L4D1: Fixed throwing errors. + - L4D2: Added map "c5m5_bridge" to the data config. + +1.17 (04-Dec-2021) + - Changes to fix warnings when compiling on SourceMod 1.11. + +1.16 (19-Oct-2021) + - Plugin now ignores players who are being healed or revived, or players healing or reviving someone. Requested to "Psyk0tik". + +1.15 (09-Sep-2021) + - Fixed the last update breaking the plugin in L4D1. + +1.14 (25-Aug-2021) + - Plugin now ignores players being carried by the Charger. Thanks to "Darkwob" for reporting. + +1.13 (30-Jun-2021) + - Plugin now ignores players inside elevators. + +1.12 (16-Jun-2021) + - L4D1: Fixed throwing errors about missing property "m_type". Thanks to "Dragokas" for reporting. + +1.11 (20-Apr-2021) + - Added cvars "l4d_anti_rush_flags" and "l4d_anti_rush_ignore" to make players with certain flags immune to the plugins actions. Requested by "Shadowart". + +1.10a (12-Apr-2021) + - Updated data config "data/l4d_anti_rush.cfg" with new triggers. Thanks to "jeremyvillanueva" for providing. + +1.10 (23-Mar-2021) + - Cleaning source code from last update. + - Fixed potentially using the wrong "add" range from the config. + +1.9 (22-Mar-2021) + - Added optional config "data/l4d_anti_rush.cfg" to extend the trigger detection range during certain crescendo events. Requested by "SilentBr". + +1.8 (09-Oct-2020) + - Changed cvar "l4d_anti_rush_finale" to allow working in Gauntlet type finales only. Thanks to "Xanaguy" for requesting. + - Renamed cvar "l4d_anti_rush_inacpped" to "l4d_anti_rush_incapped" fixing spelling mistake. + +1.7 (09-Oct-2020) + - Added cvar "l4d_anti_rush_tanks" to control if the plugins active when any tank is alive. + - Fixed not resetting slowdown on team change or player death (optimization). + +1.6 (15-Jul-2020) + - Optionally added left4dhooks forwards "L4D_OnGetCrouchTopSpeed" and "L4D_OnGetWalkTopSpeed" to modify speed when walking or crouched. + - Uncomment the section and recompile if you want to enable. Only required to slowdown players more than default. + - Thanks to "SilentBr" for reporting. + +1.5 (10-May-2020) + - Added Traditional Chinese and Simplified Chinese translations. Thanks to "fbef0102". + - Extra checks to prevent "IsAllowedGameMode" throwing errors. + - Various changes to tidy up code. + +1.4 (10-Apr-2020) + - Added Hungarian translations. Thanks to "KasperH" for providing. + - Added Russian translations. Thanks to "Dragokas" for updating with new phrases. + - Added cvar "l4d_anti_rush_incapped" to ignored incapped players from being used to calculate rushers or slackers distance. + - Added cvars "l4d_anti_rush_warn_last" and "l4d_anti_rush_warn_lead" to warn players about being teleported or slowed down. + - Added cvar "l4d_anti_rush_warn_time" to control how often someone is warned. + - Removed minimum value being set for "l4d_anti_rush_range_lead" cvar which prevented turning off lead feature. + - The cvars "l4d_anti_rush_range_last" and "l4d_anti_rush_range_lead" minimum values are now set internally (1500.0). + - Translation files and plugin updated. + +1.3 (09-Apr-2020) + - Added reset slowdown in case players are out-of-bound or have invalid flow distances to calculate the range. + - Increased minimum value of "l4d_anti_rush_range_lead" cvar from 500.0 to 1000.0. + - Removed minimum value being set for "l4d_anti_rush_range_last" cvar. Thanks to "Alex101192" for reporting. + +1.2 (08-Apr-2020) + - Added cvar "l4d_anti_rush_finale" to allow or disallow the plugin in finales. + +1.1 (07-Apr-2020) + - Changed how the plugin functions. Now calculates rushers/slackers by their flow distance to the nearest half of Survivors. + - Fixed not accounting for multiple rushers with "type 2" setting. + - Fixed "IsAllowedGameMode" from throwing errors when the "_tog" cvar was changed before MapStart. + +1.0 (26-Mar-2020) + - Added Russian translations to the .zip. Thanks to "KRUTIK" for providing. + - No other changes. + +1.0 (26-Mar-2020) + - Initial release. + +======================================================================================*/ + +#pragma semicolon 1 +#pragma newdecls required + +#include +#include +#include +#include + +#if DEBUG_BENCHMARK +#include +Handle g_Prof; +float g_fBenchMin; +float g_fBenchMax; +float g_fBenchAvg; +float g_iBenchTicks; +#endif + +#define CVAR_FLAGS FCVAR_NONE +#define MINIMUM_RANGE 1500.0 // Minimum range for last and lead cvars. +#define EVENTS_CONFIG "data/l4d_anti_rush.cfg" + + +ConVar g_hCvarAllow, g_hCvarMPGameMode, g_hCvarModes, g_hCvarModesOff, g_hCvarModesTog, g_hCvarFinale, g_hCvarFlags, g_hCvarIgnore, g_hCvarHealth, g_hCvarIncap, g_hCvarPlayers, g_hCvarRangeLast, g_hCvarRangeLead, g_hCvarSlow, g_hCvarTank, g_hCvarText, g_hCvarTime, g_hCvarType, g_hCvarWarnLast, g_hCvarWarnLead, g_hCvarWarnTime; +float g_fCvarHealth, g_fCvarRangeLast, g_fCvarRangeLead, g_fCvarSlow, g_fCvarTime, g_fCvarWarnLast, g_fCvarWarnLead, g_fCvarWarnTime; +int g_iCvarFinale, g_iCvarFlags, g_iCvarIgnore, g_iCvarIncap, g_iCvarPlayers, g_iCvarTank, g_iCvarText, g_iCvarType; +bool g_bCvarAllow, g_bMapStarted, g_bLeft4Dead2; + +bool g_bInhibit[MAXPLAYERS+1]; +float g_fHintLast[MAXPLAYERS+1]; +float g_fHintWarn[MAXPLAYERS+1]; +float g_fLastFlow[MAXPLAYERS+1]; +float g_fHighestFlow[MAXPLAYERS+1]; +Handle g_hTimer; + +char g_sMap[PLATFORM_MAX_PATH]; +bool g_bFoundMap; +bool g_bEventStarted; +float g_fEventExtended; + + +ArrayList g_hElevators; +GlobalForward g_OnRushForward; + + +// ==================================================================================================== +// PLUGIN INFO / START / END +// ==================================================================================================== +public Plugin myinfo = +{ + name = "[L4D & L4D2] Anti Rush", + author = "SilverShot", + description = "Slowdown or teleport rushers and slackers back to the group. Uses flow distance for accuracy.", + version = PLUGIN_VERSION, + url = "https://forums.alliedmods.net/showthread.php?t=322392" +} + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + EngineVersion test = GetEngineVersion(); + + if( test == Engine_Left4Dead ) g_bLeft4Dead2 = false; + else if( test == Engine_Left4Dead2 ) g_bLeft4Dead2 = true; + else + { + strcopy(error, err_max, "Plugin only supports Left 4 Dead 1 & 2."); + return APLRes_SilentFailure; + } + + return APLRes_Success; +} + +public void OnPluginStart() +{ + LoadTranslations("anti_rush.phrases"); + + g_hCvarAllow = CreateConVar( "l4d_anti_rush_allow", "1", "0=Plugin off, 1=Plugin on.", CVAR_FLAGS ); + g_hCvarModes = CreateConVar( "l4d_anti_rush_modes", "", "Turn on the plugin in these game modes, separate by commas (no spaces). (Empty = all).", CVAR_FLAGS ); + g_hCvarModesOff = CreateConVar( "l4d_anti_rush_modes_off", "", "Turn off the plugin in these game modes, separate by commas (no spaces). (Empty = none).", CVAR_FLAGS ); + g_hCvarModesTog = CreateConVar( "l4d_anti_rush_modes_tog", "0", "Turn on the plugin in these game modes. 0=All, 1=Coop, 2=Survival, 4=Versus, 8=Scavenge. Add numbers together.", CVAR_FLAGS ); + g_hCvarFinale = CreateConVar( "l4d_anti_rush_finale", g_bLeft4Dead2 ? "2" : "0", "Should the plugin activate in finales. 0=Off. 1=All finales. 2=Gauntlet type finales (L4D2 only).", CVAR_FLAGS ); + g_hCvarFlags = CreateConVar( "l4d_anti_rush_flags", "", "Players with these flags will be immune from teleporting forward when behind or slowing down when ahead.", CVAR_FLAGS ); + g_hCvarHealth = CreateConVar( "l4d_anti_rush_health", "0", "0=Off. Amount of health to remove every second when someone is rushing.", CVAR_FLAGS); + g_hCvarIgnore = CreateConVar( "l4d_anti_rush_ignore", "0", "Should players with the immune flags be counted toward total flow distance. 0=Ignore them. 1=Count them.", CVAR_FLAGS ); + g_hCvarIncap = CreateConVar( "l4d_anti_rush_incapped", "0", "0=Off. How many survivors must be incapped before ignoring them in calculating rushers and slackers.", CVAR_FLAGS ); + g_hCvarPlayers = CreateConVar( "l4d_anti_rush_players", "3", "Minimum number of alive survivors before the function kicks in. Must be 3 or greater otherwise the lead/last and average cannot be detected.", CVAR_FLAGS, true, 3.0 ); + g_hCvarRangeLast = CreateConVar( "l4d_anti_rush_range_last", "3000.0", "0.0=Off. How far behind someone can travel from the average Survivor distance before being teleported forward.", CVAR_FLAGS ); + g_hCvarRangeLead = CreateConVar( "l4d_anti_rush_range_lead", "3000.0", "How far forward someone can travel from the average Survivor distance before being teleported, slowed down or health drained.", CVAR_FLAGS, true, MINIMUM_RANGE ); + g_hCvarSlow = CreateConVar( "l4d_anti_rush_slow", "75.0", "Maximum speed someone can travel when being slowed down.", CVAR_FLAGS, true, 20.0 ); + g_hCvarTank = CreateConVar( "l4d_anti_rush_tanks", "1", "0=Off. 1=On. Should Anti-Rush be enabled when there are active Tanks.", CVAR_FLAGS ); + g_hCvarText = CreateConVar( "l4d_anti_rush_text", "1", "0=Off. 1=Print To Chat. 2=Hint Text. Display a message to someone rushing, or falling behind.", CVAR_FLAGS ); + g_hCvarTime = CreateConVar( "l4d_anti_rush_time", "10", "How often to print the message to someone if slowdown is enabled and affecting them.", CVAR_FLAGS ); + g_hCvarType = CreateConVar( "l4d_anti_rush_type", "1", "What to do with rushers. 0=Ignore (used for health drain / forward only). 1=Slowdown player speed when moving forward. 2=Teleport back to group.", CVAR_FLAGS ); + g_hCvarWarnLast = CreateConVar( "l4d_anti_rush_warn_last", "2500.0", "How far behind someone can travel from the average Survivor distance before being warned about being teleported.", CVAR_FLAGS, true, MINIMUM_RANGE ); + g_hCvarWarnLead = CreateConVar( "l4d_anti_rush_warn_lead", "2500.0", "How far forward someone can travel from the average Survivor distance before being warned about being teleported or slowed down.", CVAR_FLAGS, true, MINIMUM_RANGE ); + g_hCvarWarnTime = CreateConVar( "l4d_anti_rush_warn_time", "15.0", "0.0=Off. How often to print a message to someone warning them they are ahead or behind and will be teleported or slowed down.", CVAR_FLAGS ); + CreateConVar( "l4d_anti_rush_version", PLUGIN_VERSION, "Anti Rush plugin version.", FCVAR_NOTIFY|FCVAR_DONTRECORD); + AutoExecConfig(true, "l4d_anti_rush"); + + g_hCvarMPGameMode = FindConVar("mp_gamemode"); + g_hCvarMPGameMode.AddChangeHook(ConVarChanged_Allow); + g_hCvarModes.AddChangeHook(ConVarChanged_Allow); + g_hCvarModesOff.AddChangeHook(ConVarChanged_Allow); + g_hCvarModesTog.AddChangeHook(ConVarChanged_Allow); + g_hCvarAllow.AddChangeHook(ConVarChanged_Allow); + g_hCvarFinale.AddChangeHook(ConVarChanged_Cvars); + g_hCvarFlags.AddChangeHook(ConVarChanged_Cvars); + g_hCvarHealth.AddChangeHook(ConVarChanged_Cvars); + g_hCvarIgnore.AddChangeHook(ConVarChanged_Cvars); + g_hCvarIncap.AddChangeHook(ConVarChanged_Cvars); + g_hCvarPlayers.AddChangeHook(ConVarChanged_Cvars); + g_hCvarRangeLast.AddChangeHook(ConVarChanged_Cvars); + g_hCvarRangeLead.AddChangeHook(ConVarChanged_Cvars); + g_hCvarTank.AddChangeHook(ConVarChanged_Cvars); + g_hCvarText.AddChangeHook(ConVarChanged_Cvars); + g_hCvarSlow.AddChangeHook(ConVarChanged_Cvars); + g_hCvarTime.AddChangeHook(ConVarChanged_Cvars); + g_hCvarType.AddChangeHook(ConVarChanged_Cvars); + g_hCvarWarnLast.AddChangeHook(ConVarChanged_Cvars); + g_hCvarWarnLead.AddChangeHook(ConVarChanged_Cvars); + g_hCvarWarnTime.AddChangeHook(ConVarChanged_Cvars); + + g_hElevators = new ArrayList(); + + #if DEBUG_BENCHMARK + g_Prof = CreateProfiler(); + #endif + + g_OnRushForward = new GlobalForward("OnAntiRush", ET_Event, Param_Cell, Param_CellByRef, Param_Float); +} + + + +// ==================================================================================================== +// CVARS +// ==================================================================================================== +public void OnConfigsExecuted() +{ + IsAllowed(); +} + +void ConVarChanged_Allow(Handle convar, const char[] oldValue, const char[] newValue) +{ + IsAllowed(); +} + +void ConVarChanged_Cvars(Handle convar, const char[] oldValue, const char[] newValue) +{ + GetCvars(); +} + +void GetCvars() +{ + char sTemp[32]; + g_hCvarFlags.GetString(sTemp, sizeof(sTemp)); + g_iCvarFlags = ReadFlagString(sTemp); + g_iCvarIgnore = g_hCvarIgnore.IntValue; + + g_iCvarFinale = g_hCvarFinale.IntValue; + g_fCvarHealth = g_hCvarHealth.FloatValue; + g_iCvarIncap = g_hCvarIncap.IntValue; + g_iCvarPlayers = g_hCvarPlayers.IntValue; + g_fCvarTime = g_hCvarTime.FloatValue; + g_iCvarTank = g_hCvarTank.IntValue; + g_iCvarText = g_hCvarText.IntValue; + g_fCvarSlow = g_hCvarSlow.FloatValue; + g_iCvarType = g_hCvarType.IntValue; + g_fCvarRangeLast = g_hCvarRangeLast.FloatValue; + g_fCvarRangeLead = g_hCvarRangeLead.FloatValue; + g_fCvarWarnLast = g_hCvarWarnLast.FloatValue; + g_fCvarWarnLead = g_hCvarWarnLead.FloatValue; + g_fCvarWarnTime = g_hCvarWarnTime.FloatValue; + + if( g_fCvarRangeLast && g_fCvarRangeLast < MINIMUM_RANGE ) g_fCvarRangeLast = MINIMUM_RANGE; + if( g_fCvarRangeLead && g_fCvarRangeLead < MINIMUM_RANGE ) g_fCvarRangeLead = MINIMUM_RANGE; + if( g_fCvarWarnLast && g_fCvarWarnLast < MINIMUM_RANGE ) g_fCvarWarnLast = MINIMUM_RANGE; + if( g_fCvarWarnLead && g_fCvarWarnLead < MINIMUM_RANGE ) g_fCvarWarnLead = MINIMUM_RANGE; +} + +void IsAllowed() +{ + bool bCvarAllow = g_hCvarAllow.BoolValue; + bool bAllowMode = IsAllowedGameMode(); + GetCvars(); + + if( g_bCvarAllow == false && bCvarAllow == true && bAllowMode == true ) + { + g_bCvarAllow = true; + + HookEvent("round_start", Event_RoundStart); + HookEvent("round_end", Event_RoundEnd); + HookEvent("player_death", Event_PlayerDeath); + HookEvent("player_team", Event_PlayerTeam); + + Event_RoundStart(null, "", false); + } + + else if( g_bCvarAllow == true && (bCvarAllow == false || bAllowMode == false) ) + { + g_bCvarAllow = false; + + UnhookEvent("round_start", Event_RoundStart); + UnhookEvent("round_end", Event_RoundEnd); + UnhookEvent("player_death", Event_PlayerDeath); + UnhookEvent("player_team", Event_PlayerTeam); + + ResetSlowdown(); + ResetPlugin(); + } +} + +int g_iCurrentMode; +bool IsAllowedGameMode() +{ + if( g_hCvarMPGameMode == null ) + return false; + + int iCvarModesTog = g_hCvarModesTog.IntValue; + if( iCvarModesTog != 0 ) + { + if( g_bMapStarted == false ) + return false; + + g_iCurrentMode = 0; + + int entity = CreateEntityByName("info_gamemode"); + if( IsValidEntity(entity) ) + { + DispatchSpawn(entity); + HookSingleEntityOutput(entity, "OnCoop", OnGamemode, true); + HookSingleEntityOutput(entity, "OnSurvival", OnGamemode, true); + HookSingleEntityOutput(entity, "OnVersus", OnGamemode, true); + HookSingleEntityOutput(entity, "OnScavenge", OnGamemode, true); + ActivateEntity(entity); + AcceptEntityInput(entity, "PostSpawnActivate"); + if( IsValidEntity(entity) ) // Because sometimes "PostSpawnActivate" seems to kill the ent. + RemoveEdict(entity); // Because multiple plugins creating at once, avoid too many duplicate ents in the same frame + } + + if( g_iCurrentMode == 0 ) + return false; + + if( !(iCvarModesTog & g_iCurrentMode) ) + return false; + } + + char sGameModes[64], sGameMode[64]; + g_hCvarMPGameMode.GetString(sGameMode, sizeof(sGameMode)); + Format(sGameMode, sizeof(sGameMode), ",%s,", sGameMode); + + g_hCvarModes.GetString(sGameModes, sizeof(sGameModes)); + if( sGameModes[0] ) + { + Format(sGameModes, sizeof(sGameModes), ",%s,", sGameModes); + if( StrContains(sGameModes, sGameMode, false) == -1 ) + return false; + } + + g_hCvarModesOff.GetString(sGameModes, sizeof(sGameModes)); + if( sGameModes[0] ) + { + Format(sGameModes, sizeof(sGameModes), ",%s,", sGameModes); + if( StrContains(sGameModes, sGameMode, false) != -1 ) + return false; + } + + return true; +} + +void OnGamemode(const char[] output, int caller, int activator, float delay) +{ + if( strcmp(output, "OnCoop") == 0 ) + g_iCurrentMode = 1; + else if( strcmp(output, "OnSurvival") == 0 ) + g_iCurrentMode = 2; + else if( strcmp(output, "OnVersus") == 0 ) + g_iCurrentMode = 4; + else if( strcmp(output, "OnScavenge") == 0 ) + g_iCurrentMode = 8; +} + + + +// ==================================================================================================== +// HOOK CUSTOM ARLARM EVENTS +// ==================================================================================================== +int g_iSectionLevel; + +void LoadEventConfig() +{ + g_bFoundMap = false; + + char sPath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sPath, sizeof(sPath), EVENTS_CONFIG); + if( FileExists(sPath) ) + { + ParseConfigFile(sPath); + } +} + +bool ParseConfigFile(const char[] file) +{ + SMCParser parser = new SMCParser(); + SMC_SetReaders(parser, ColorConfig_NewSection, ColorConfig_KeyValue, ColorConfig_EndSection); + parser.OnEnd = ColorConfig_End; + + char error[128]; + int line = 0, col = 0; + SMCError result = parser.ParseFile(file, line, col); + + if( result != SMCError_Okay ) + { + parser.GetErrorString(result, error, sizeof(error)); + SetFailState("%s on line %d, col %d of %s [%d]", error, line, col, file, result); + } + + delete parser; + return (result == SMCError_Okay); +} + +SMCResult ColorConfig_NewSection(Handle parser, const char[] section, bool quotes) +{ + g_iSectionLevel++; + + // Map + if( g_iSectionLevel == 2 && strcmp(section, g_sMap) == 0 ) + { + g_bFoundMap = true; + } else { + g_bFoundMap = false; + } + + return SMCParse_Continue; +} + +SMCResult ColorConfig_KeyValue(Handle parser, const char[] key, const char[] value, bool key_quotes, bool value_quotes) +{ + // On / Off + if( g_iSectionLevel == 2 && g_bFoundMap ) + { + if( strcmp(key, "add") == 0 ) + { + g_fEventExtended = StringToFloat(value); + } else { + static char sSplit[3][64]; + + int len = ExplodeString(value, ":", sSplit, sizeof(sSplit), sizeof(sSplit[])); + if( len != 3 ) + { + LogError("Malformed string in l4d_anti_rush.cfg. Section [%s] key [%s] value [%s].", g_sMap, key, value); + } else { + int entity = FindByClassTargetName(sSplit[0], sSplit[1]); + if( entity != INVALID_ENT_REFERENCE ) + { + if( strcmp(key, "1") == 0 ) + { + HookSingleEntityOutput(entity, sSplit[2], OutputStart); + } + else if( strcmp(key, "0") == 0 ) + { + HookSingleEntityOutput(entity, sSplit[2], OutputStop); + } + } + } + } + } + + return SMCParse_Continue; +} + +void OutputStart(const char[] output, int caller, int activator, float delay) +{ + g_bEventStarted = true; +} + +void OutputStop(const char[] output, int caller, int activator, float delay) +{ + g_bEventStarted = false; +} + + +SMCResult ColorConfig_EndSection(Handle parser) +{ + g_iSectionLevel--; + return SMCParse_Continue; +} + +void ColorConfig_End(Handle parser, bool halted, bool failed) +{ + if( failed ) + SetFailState("Error: Cannot load the config file: \"%s\"", EVENTS_CONFIG); +} + +int FindByClassTargetName(const char[] sClass, const char[] sTarget) +{ + char sName[64]; + int entity = INVALID_ENT_REFERENCE; + + // Is targetname numeric? + bool numeric = true; + for( int i = 0; i < strlen(sTarget); i++ ) + { + if( IsCharNumeric(sTarget[i]) == false ) + { + numeric = false; + break; + } + } + + // Search by hammer ID or targetname + while( (entity = FindEntityByClassname(entity, sClass)) != INVALID_ENT_REFERENCE ) + { + if( numeric ) + { + if( GetEntProp(entity, Prop_Data, "m_iHammerID") == StringToInt(sTarget) ) return entity; + } else { + GetEntPropString(entity, Prop_Data, "m_iName", sName, sizeof(sName)); + if( strcmp(sTarget, sName) == 0 ) return entity; + } + } + return INVALID_ENT_REFERENCE; +} + + + +// ==================================================================================================== +// EVENTS +// ==================================================================================================== +void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) +{ + delete g_hTimer; + + // Finales allowed, or not finale + if( g_iCvarFinale || (g_iCvarFinale == 0 && L4D_IsMissionFinalMap() == false) ) + { + // Gauntlet finale only + if( g_iCvarFinale == 2 && g_bLeft4Dead2 ) + { + int entity = FindEntityByClassname(-1, "trigger_finale"); + if( entity != -1 ) + { + if( GetEntProp(entity, Prop_Data, "m_type") != 1 ) return; + } + } + + g_hTimer = CreateTimer(1.0, TimerTest, _, TIMER_REPEAT); + + LoadEventConfig(); + } + + // Get elevators + g_hElevators.Clear(); + + int entity = -1; + while( (entity = FindEntityByClassname(entity, "func_elevator")) != INVALID_ENT_REFERENCE ) + { + g_hElevators.Push(EntIndexToEntRef(entity)); + } +} + +void Event_RoundEnd(Event event, const char[] name, bool dontBroadcast) +{ + ResetSlowdown(); + ResetPlugin(); +} + +void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if( client ) + { + ResetClient(client); + } +} + +void Event_PlayerTeam(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if( client ) + { + ResetClient(client); + } +} + +public void OnMapStart() +{ + GetCurrentMap(g_sMap, sizeof(g_sMap)); + g_bMapStarted = true; +} + +public void OnMapEnd() +{ + g_bMapStarted = false; + ResetPlugin(); +} + +void ResetPlugin() +{ + for( int i = 1; i <= MAXPLAYERS; i++ ) + { + ResetClient(i); + } + + delete g_hTimer; + + g_hElevators.Clear(); + g_fEventExtended = 0.0; + g_bEventStarted = false; +} + +void ResetClient(int i) +{ + g_bInhibit[i] = false; + g_fHintLast[i] = 0.0; + g_fHintWarn[i] = 0.0; + g_fLastFlow[i] = 0.0; + g_fHighestFlow[i] = 0.0; + + SDKUnhook(i, SDKHook_PreThinkPost, PreThinkPost); +} + +void ResetSlowdown() +{ + for( int i = 1; i <= MaxClients; i++ ) + { + if( g_bInhibit[i] && IsClientInGame(i) ) + { + SDKUnhook(i, SDKHook_PreThinkPost, PreThinkPost); + } + + g_bInhibit[i] = false; + } +} + + + +// ==================================================================================================== +// LOGIC +// ==================================================================================================== +Action TimerTest(Handle timer) +{ + if( !g_bMapStarted ) return Plugin_Continue; + + #if DEBUG_BENCHMARK + StartProfiling(g_Prof); + #endif + + static bool bTanks; + if( g_iCvarTank == 0 ) + { + if( L4D2_GetTankCount() > 0 ) + { + if( !bTanks ) + { + bTanks = true; + ResetSlowdown(); + } + + return Plugin_Continue; + } else { + bTanks = false; + } + } + + float currentFlow; + int count, countflow, index; + + // Get survivors flow distance + ArrayList aList = new ArrayList(2); + + // Account for incapped + int clients[MAXPLAYERS+1]; + int incapped, client; + + // Check valid survivors, count incapped + for( int i = 1; i <= MaxClients; i++ ) + { + if( IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) ) + { + // Immune players - ignore from flow calculations + if( g_iCvarFlags != 0 && g_iCvarIgnore == 0 && CheckCommandAccess(client, "", g_iCvarFlags, true) ) + { + continue; + } + + // Count + clients[count++] = i; + + if( g_iCvarIncap ) + { + if( GetEntProp(i, Prop_Send, "m_isIncapacitated", 1) ) + incapped++; + } + } + } + + for( int i = 0; i < count; i++ ) + { + client = clients[i]; + + // Ignore incapped + if( g_iCvarIncap && incapped >= g_iCvarIncap && GetEntProp(client, Prop_Send, "m_isIncapacitated", 1) ) + continue; + + // Ignore healing / using stuff + if( g_bLeft4Dead2 && GetEntPropEnt(client, Prop_Send, "m_useActionTarget") > 0 ) + continue; + + // Ignore reviving + if( GetEntPropEnt(client, Prop_Send, "m_reviveOwner") > 0 || GetEntPropEnt(client, Prop_Send, "m_reviveTarget") > 0 ) + continue; + + // Ignore pinned by Charger + if( g_bLeft4Dead2 && GetEntPropEnt(client, Prop_Send, "m_carryAttacker") != -1 ) + continue; + + // Ignore in Elevator + int lift = GetEntPropEnt(client, Prop_Send, "m_hGroundEntity"); + if( lift > MaxClients ) + { + lift = EntIndexToEntRef(lift); + if( g_hElevators.FindValue(lift) != -1 ) + continue; + } + + // Get flow + currentFlow = L4D2Direct_GetFlowDistance(client); + + + if( currentFlow && currentFlow != -9999.0 ) // Invalid flows + { + // Only get the highest flow + if(currentFlow > g_fHighestFlow[client]) { + g_fHighestFlow[client] = currentFlow; + } + countflow++; + index = aList.Push(currentFlow); + aList.Set(index, client, 1); + } + // Reset slowdown if players flow is invalid + else if( g_bInhibit[client] == true ) + { + g_bInhibit[client] = false; + SDKUnhook(client, SDKHook_PreThinkPost, PreThinkPost); + } + } + + // In case not enough players or some have invalid flow distance, we still need an average. + if( countflow >= g_iCvarPlayers ) + { + aList.Sort(Sort_Descending, Sort_Float); + + int clientAvg; + float lastFlow; + float distance; + + + + // Detect rushers + if( g_fCvarRangeLead ) + { + // Loop through survivors from highest flow + for( int i = 0; i < countflow; i++ ) + { + client = aList.Get(i, 1); + + // Immune players + if( g_iCvarFlags != 0 && g_iCvarIgnore == 1 && CheckCommandAccess(client, "", g_iCvarFlags, true) ) + { + continue; + } + + bool flowBack = true; + + // Only check nearest half of survivor pack. + if( i < countflow / 2 ) + { + currentFlow = aList.Get(i, 0); + + // Loop through from next survivor to mid-way through the pack. + for( int x = i + 1; x <= countflow / 2; x++ ) + { + // We instead use the highest flow for the other survivors, to prevent survivors going back from triggering antirush on a player + // The player we check uses their latest flow to prevent issues if they themselves glitched ahead in somecase then returned. + lastFlow = g_fHighestFlow[x]; + if(lastFlow <= 0.0) continue; + distance = currentFlow - lastFlow; + if( g_bEventStarted ) distance -= g_fEventExtended; + + // Warn ahead hint + if( g_iCvarText && g_fCvarWarnTime && g_fCvarWarnLead && distance > g_fCvarWarnLead && distance < g_fCvarRangeLead && g_fHintWarn[client] < GetGameTime() ) + { + g_fHintWarn[client] = GetGameTime() + g_fCvarWarnTime; + + switch( g_iCvarType ) + { + case 0: ClientHintMessage(client, "Warn_Health"); + case 1: ClientHintMessage(client, "Warn_Slowdown"); + case 2: ClientHintMessage(client, "Warn_Ahead"); + } + } + + // Compare higher flow with next survivor, they're rushing + if( distance > g_fCvarRangeLead ) + { + int punishType = g_iCvarType, result; + + Call_StartForward(g_OnRushForward); + Call_PushCell(client); + Call_PushCellRef(punishType); + Call_PushFloat(distance); + + if(Call_Finish(result) == SP_ERROR_NONE && result > 0) break; + + // PrintToServer("RUSH: %N %f", client, distance); + flowBack = false; + + // Slowdown enabled? + if( g_fCvarHealth || punishType == 1 ) + { + // Inhibit moving forward + // Only check > or < because when == the same flow distance, they're either already being slowed or running back, so we don't want to change/affect them within the same flow NavMesh. + if( currentFlow > g_fLastFlow[client] ) + { + g_fLastFlow[client] = currentFlow; + + if( g_iCvarType == 1 && g_bInhibit[client] == false ) + { + g_bInhibit[client] = true; + SDKHook(client, SDKHook_PreThinkPost, PreThinkPost); + } + + // Hint + if( g_iCvarText && g_fHintLast[client] < GetGameTime() ) + { + g_fHintLast[client] = GetGameTime() + g_fCvarTime; + + switch( g_iCvarType ) + { + case 0: ClientHintMessage(client, "Rush_Health"); + case 1: ClientHintMessage(client, "Rush_Slowdown"); + } + } + + // Hurt for rushing? + if( g_fCvarHealth ) + { + SDKHooks_TakeDamage(client, 0, 0, g_fCvarHealth); + } + } + else if( currentFlow < g_fLastFlow[client] ) + { + flowBack = true; + g_fLastFlow[client] = currentFlow; + } + } + + + + // Teleport enabled? + if( punishType == 2 && IsClientPinned(client) == false ) + { + clientAvg = aList.Get(x, 1); + float vPos[3]; + GetClientAbsOrigin(clientAvg, vPos); + + // Hint + if( g_iCvarText) + { + ClientHintMessage(client, "Rush_Ahead"); + } + + TeleportEntity(client, vPos, NULL_VECTOR, NULL_VECTOR); + } + + break; + } + } + } + + // Running back, allow full speed + if( flowBack && g_bInhibit[client] == true ) + { + g_bInhibit[client] = false; + SDKUnhook(client, SDKHook_PreThinkPost, PreThinkPost); + } + } + } + + + + // Teleport slacker + if( g_fCvarRangeLast ) + { + // Loop through survivors from lowest flow to mid-way through the pack. + for( int i = countflow - 1; i > countflow / 2; i-- ) + { + client = aList.Get(i, 1); + + // Immune players + if( g_iCvarFlags != 0 && g_iCvarIgnore == 1 && CheckCommandAccess(client, "", g_iCvarFlags, true) ) + { + continue; + } + + currentFlow = aList.Get(i, 0); + + // Loop through from next survivor to mid-way through the pack. + for( int x = i - 1; x < countflow; x++ ) + { + lastFlow = g_fHighestFlow[x]; + distance = lastFlow - currentFlow; + if( g_bEventStarted ) distance -= g_fEventExtended; + + // Warn behind hint + if( g_iCvarText && g_fCvarWarnTime && g_fCvarWarnLast && distance > g_fCvarWarnLast && distance < g_fCvarRangeLead && g_fHintWarn[client] < GetGameTime() ) + { + g_fHintWarn[client] = GetGameTime() + g_fCvarWarnTime; + + ClientHintMessage(client, "Warn_Behind"); + } + + // Compare lower flow with next survivor, they're behind + if( distance > g_fCvarRangeLast && IsClientPinned(client) == false ) + { + // PrintToServer("SLOW: %N %f", client, distance); + clientAvg = aList.Get(x, 1); + float vPos[3]; + GetClientAbsOrigin(clientAvg, vPos); + + // Hint + if( g_iCvarText ) + { + ClientHintMessage(client, "Rush_Behind"); + } + + TeleportEntity(client, vPos, NULL_VECTOR, NULL_VECTOR); + break; + } + } + } + } + } + else + { + ResetSlowdown(); + } + + delete aList; + + #if DEBUG_BENCHMARK + StopProfiling(g_Prof); + float speed = GetProfilerTime(g_Prof); + if( speed < g_fBenchMin ) g_fBenchMin = speed; + if( speed > g_fBenchMax ) g_fBenchMax = speed; + g_fBenchAvg += speed; + g_iBenchTicks++; + + PrintToServer("Anti Rush benchmark: %f (Min %f. Avg %f. Max %f)", speed, g_fBenchMin, g_fBenchAvg / g_iBenchTicks, g_fBenchMax); + #endif + + return Plugin_Continue; +} + +/* Remove this line to enable, if you want to limit speed (slower) than default when walking/crouched. +public Action L4D_OnGetCrouchTopSpeed(int target, float &retVal) +{ + if( g_bInhibit[target] ) + { + retVal = g_fCvarSlow; + return Plugin_Handled; + } + + return Plugin_Continue; +} + +public Action L4D_OnGetWalkTopSpeed(int target, float &retVal) +{ + if( g_bInhibit[target] ) + { + retVal = g_fCvarSlow; + return Plugin_Handled; + } + + return Plugin_Continue; +} +// */ + +void PreThinkPost(int client) +{ + SetEntPropFloat(client, Prop_Send, "m_flMaxspeed", g_fCvarSlow); +} + +void ClientHintMessage(int client, const char[] translation) +{ + static char sMessage[256]; + Format(sMessage, sizeof(sMessage), "%T", translation, client); + + if( g_iCvarText == 1 ) + { + ReplaceColors(sMessage, sizeof(sMessage), false); + PrintToChat(client, sMessage); + } else { + ReplaceColors(sMessage, sizeof(sMessage), true); + PrintHintText(client, sMessage); + } +} + +void ReplaceColors(char[] translation, int size, bool hint) +{ + ReplaceString(translation, size, "{white}", hint ? "" : "\x01"); + ReplaceString(translation, size, "{cyan}", hint ? "" : "\x03"); + ReplaceString(translation, size, "{orange}", hint ? "" : "\x04"); + ReplaceString(translation, size, "{green}", hint ? "" : "\x05"); +} + +bool IsClientPinned(int client) +{ + if( GetEntProp(client, Prop_Send, "m_isIncapacitated", 1) || + GetEntProp(client, Prop_Send, "m_isHangingFromLedge", 1) || + GetEntPropEnt(client, Prop_Send, "m_tongueOwner") > 0 || + GetEntPropEnt(client, Prop_Send, "m_pounceAttacker") > 0 + ) return true; + + if( g_bLeft4Dead2 && + ( + GetEntPropEnt(client, Prop_Send, "m_jockeyAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_carryAttacker") > 0 || + GetEntPropEnt(client, Prop_Send, "m_pummelAttacker") > 0 + )) return true; + + return false; +} \ No newline at end of file diff --git a/scripting/l4d_reservetheserver.sp b/scripting/l4d_reservetheserver.sp new file mode 100644 index 0000000..fbe3564 --- /dev/null +++ b/scripting/l4d_reservetheserver.sp @@ -0,0 +1,201 @@ +#define PLUGIN_VERSION "1.1.0" +#define MAX_LINE_WIDTH 64 + +#define MESSAGE_FOR_PLAYERS_LINE1 "" +#define MESSAGE_FOR_PLAYERS_LINE2 "\x04RECEIVED SERVER RESERVATION REQUEST" +#define MESSAGE_FOR_PLAYERS_LINE3 "\x04YOU WILL BE RETURNED TO LOBBY" +#define MESSAGE_FOR_PLAYERS_LINE4 "" + +#pragma semicolon 1 + +#include + +#pragma newdecls required + +ConVar PluginCvarSearchKey, PluginCvarMode, PluginCvarTimeout, PluginCvarImmuneLevel, + SteamGroupExclusiveCvar, SearchKeyCvar, HibernationCvar; + +int HibernationCvarValue; +bool isMapChange = false, doRestartMap = false; +char PluginSearchKeyString[MAX_LINE_WIDTH] = "", PluginCvarImmuneFlagString[MAX_LINE_WIDTH] = "", CurrentMapString[MAX_LINE_WIDTH] = ""; + +public Plugin myinfo = +{ + name = "Reserve The Server", + author = "Jack'lul [Edited by Dosergen]", + description = "Frees the server from all players and reserves it.", + version = PLUGIN_VERSION, + url = "https://forums.alliedmods.net/showthread.php?p=2084993" +} + +public void OnPluginStart() { + EngineVersion g_Game = GetEngineVersion(); + if(g_Game != Engine_Left4Dead && g_Game != Engine_Left4Dead2) { + SetFailState("This plugin is for L4D/L4D2 only."); + } + + CreateConVar("l4d_rts_version", PLUGIN_VERSION, "Reserve The Server plugin version", 0|FCVAR_NOTIFY|FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_DONTRECORD); + PluginCvarMode = CreateConVar("l4d_rts_mode", "1", "0 - only remove players using lobby vote, 1 - remove players using lobby vote and then disconnect server from matchmaking", 0, true, 0.0, true, 1.0); + PluginCvarSearchKey = CreateConVar("l4d_rts_searchkey", "", "sv_search_key will be set to this while server is reserved", 0); + PluginCvarTimeout = CreateConVar("l4d_rts_timeout", "30", "How long will the server stay disconnected from matchmaking? 0 - never restore matchmaking connection", 0, true, 0.0, true, 300.0); + PluginCvarImmuneLevel = CreateConVar("l4d_rts_immunelevel", "1", "Any player >= to this level will cancel the lobby vote.", 0); + + RegAdminCmd("sm_rts", Command_MakeReservation, ADMFLAG_KICK, "Free the server from all players, then reserve it."); + RegAdminCmd("sm_cr", Command_CancelReservation, ADMFLAG_KICK, "Cancel reservation and make server public again."); + RegAdminCmd("sm_forcelobby", Command_ForceLobby, ADMFLAG_BAN, "Force call vote to return to lobby"); + + SteamGroupExclusiveCvar = FindConVar("sv_steamgroup_exclusive"); + SearchKeyCvar = FindConVar("sv_search_key"); + HibernationCvar = FindConVar("sv_hibernate_when_empty"); + HibernationCvarValue = GetConVarInt(HibernationCvar); + + AutoExecConfig(true, "l4d_rts"); +} + +public void OnClientDisconnect(int client) { + if (client == 0 || isMapChange || IsFakeClient(client)) + return; + + if(doRestartMap == true) + CreateTimer(1.0, MapReloadCheck); +} + +public void OnMapEnd() { + isMapChange = true; + doRestartMap = false; +} + +public void OnMapStart() { + isMapChange = false; +} + +public Action Command_ForceLobby(int client, int args) { + Handle bf = StartMessageOne("VoteStart", client, USERMSG_RELIABLE); + BfWriteByte(bf, 0); + BfWriteByte(bf, client); + BfWriteString(bf, "returntolobby"); + BfWriteString(bf, ""); + BfWriteString(bf, ""); + EndMessage(); + PassVote(); +} + +public Action Command_MakeReservation(int client, int args) { + bool isAdminOnline, isServerEmpty = true; + if(client > 0) { + for (int i = 1; i <= MaxClients; i++) { + if (IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if (admin != INVALID_ADMIN_ID && GetAdminImmunityLevel(admin) >= PluginCvarImmuneLevel.IntValue) { + isAdminOnline = true; + break; + } + if(isServerEmpty) isServerEmpty = false; + } + } + } + //If there is no admins playing OR request is from server itself then reserve: + if(!isAdminOnline) + { + LogMessage("Received server reservation request."); + if(!isServerEmpty) { + if(GetConVarInt(PluginCvarMode) == 1) + { + doRestartMap = true; + ReplyToCommand(client, "Server will be freed from all players and reserved."); + } + else + ReplyToCommand(client, "Server will be freed from all players."); + + PrintToChatAll(MESSAGE_FOR_PLAYERS_LINE1); + PrintToChatAll(MESSAGE_FOR_PLAYERS_LINE2); + PrintToChatAll(MESSAGE_FOR_PLAYERS_LINE3); + PrintToChatAll(MESSAGE_FOR_PLAYERS_LINE4); + + CreateTimer(5.0, FreeTheServer); + } else if(GetConVarInt(PluginCvarMode) == 1) { + DisconnectFromMatchmaking(); + ReloadMap(); + } + } + else + ReplyToCommand(client, "Server reservation request denied - admin is online!"); + return Plugin_Handled; +} + +public Action Command_CancelReservation(int client, int args) { + CreateTimer(0.1, MakeServerPublic); +} + +public Action FreeTheServer(Handle timer) { + CallLobbyVote(); + PassVote(); + + if(GetConVarInt(PluginCvarMode) == 1) { + DisconnectFromMatchmaking(); + } +} + +public Action MakeServerPublic(Handle timer) { + ConnectToMatchmaking(); + + int notConnected = 0; + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientConnected (i) && IsClientInGame (i)) + break; + else + notConnected++; + } + + if(notConnected == MaxClients) + ReloadMap(); + + if(HibernationCvarValue != 0 && GetConVarInt(HibernationCvar) == 0) + SetConVarInt(HibernationCvar, 1); +} + +public Action MapReloadCheck(Handle timer) { + if (!isMapChange && doRestartMap) { + doRestartMap = false; + ReloadMap(); + } +} + +void CallLobbyVote() { + for (int iClient = 1; iClient <= MaxClients; iClient++) { + if (IsClientConnected (iClient) && IsClientInGame (iClient)) { + FakeClientCommand (iClient, "callvote returntolobby"); + } + } +} + +void PassVote() { + for(int iClient = 1; iClient <= MaxClients; iClient++) { + if (IsClientConnected (iClient) && IsClientInGame (iClient)) { + FakeClientCommand(iClient, "Vote Yes"); + } + } +} + +void ReloadMap() { + GetCurrentMap(CurrentMapString, sizeof(CurrentMapString)); + ServerCommand("map %s", CurrentMapString); +} + +void DisconnectFromMatchmaking() { + GetConVarString(PluginCvarSearchKey, PluginSearchKeyString, sizeof(PluginSearchKeyString)); + SetConVarInt(SteamGroupExclusiveCvar, 1); + SetConVarString(SearchKeyCvar, PluginSearchKeyString); + + if(HibernationCvarValue != 0) + SetConVarInt(HibernationCvar, 0); + + if(GetConVarFloat(PluginCvarTimeout)>0) + CreateTimer(GetConVarFloat(PluginCvarTimeout), MakeServerPublic); +} + +void ConnectToMatchmaking() { + SetConVarInt(SteamGroupExclusiveCvar, 0); + SetConVarString(SearchKeyCvar, ""); +} diff --git a/scripting/l4d_survivor_identity_fix.sp b/scripting/l4d_survivor_identity_fix.sp new file mode 100644 index 0000000..79f01a1 --- /dev/null +++ b/scripting/l4d_survivor_identity_fix.sp @@ -0,0 +1,541 @@ +#pragma semicolon 1 +#pragma newdecls required + +#define PLUGIN_NAME "[L4D1/2] Survivor Identity Fix for 5+ Survivors" +#define PLUGIN_AUTHOR "Merudo, Shadowysn" +#define PLUGIN_DESC "Fix bug where a survivor will change identity when a player connects/disconnects if there are 5+ survivors" +#define PLUGIN_VERSION "1.6" +#define PLUGIN_URL "https://forums.alliedmods.net/showthread.php?p=2403731#post2403731" +#define PLUGIN_NAME_SHORT "5+ Survivor Identity Fix" +#define PLUGIN_NAME_TECH "survivor_identity_fix" + +#include +#include +#include +#include +#include + +#define TEAM_SURVIVOR 2 +#define TEAM_PASSING 4 + +#define DEBUG 1 + + +#define GAMEDATA "l4d_survivor_identity_fix" +#define NAME_SetModel "CBasePlayer::SetModel" +#define SIG_SetModel_LINUX "@_ZN11CBasePlayer8SetModelEPKc" +#define SIG_SetModel_WINDOWS "\\x55\\x8B\\x2A\\x8B\\x2A\\x2A\\x56\\x57\\x50\\x8B\\x2A\\xE8\\x2A\\x2A\\x2A\\x2A\\x8B\\x2A\\x2A\\x2A\\x2A\\x2A\\x8B\\x2A\\x8B\\x2A\\x2A\\x8B" +#define SIG_L4D1SetModel_WINDOWS "\\x8B\\x2A\\x2A\\x2A\\x56\\x57\\x50\\x8B\\x2A\\xE8\\x2A\\x2A\\x2A\\x2A\\x8B\\x3D" + +char g_Models[MAXPLAYERS+1][128]; +static int g_iPendingCookieModel[MAXPLAYERS+1]; + +Handle hConf = null; +static Handle hDHookSetModel = null; +Cookie modelPrefCookie; +static ConVar hCookiesEnabled; +static bool isLateLoad, cookieModelsSet, isL4D1Survivors; +static int survivors; +static bool IsTemporarilyL4D2[MAXPLAYERS]; +static char currentMap[16]; +Handle cookieModelTimer; + +static Menu chooseMenu; + +// ------------------------------------------------------------------------ +// Models & survivor names so bots can be renamed +// ------------------------------------------------------------------------ +char survivor_names[8][] = { "Nick", "Rochelle", "Coach", "Ellis", "Bill", "Zoey", "Francis", "Louis"}; +char survivor_models[8][] = +{ + "models/survivors/survivor_gambler.mdl", + "models/survivors/survivor_producer.mdl", + "models/survivors/survivor_coach.mdl", + "models/survivors/survivor_mechanic.mdl", + "models/survivors/survivor_namvet.mdl", + "models/survivors/survivor_teenangst.mdl", + "models/survivors/survivor_biker.mdl", + "models/survivors/survivor_manager.mdl" +}; + + +/*TODO: Setup cookie preference setting: +Need to make sure if l4d1 that cookie preference correctly setting? +Probably if 'rochelle' && l4d1 -> rochelle model, zoey survivorType, or just leave as invalid roch + +*/ + +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESC, + version = PLUGIN_VERSION, + url = PLUGIN_URL +} + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + CreateNative("IdentityFix_SetPlayerModel", Native_SetPlayerModel); + if(late) isLateLoad = true; + return APLRes_Success; +} + +public void OnPluginStart() +{ + GetGamedata(); + + CreateConVar("l4d_survivor_identity_fix_version", PLUGIN_VERSION, "Survivor Change Fix Version", FCVAR_SPONLY|FCVAR_NOTIFY|FCVAR_DONTRECORD); + hCookiesEnabled = CreateConVar("l4d_survivor_identity_fix_cookies", "2.0", "0 -> Disable cookie preference, 1 -> Enable for 5+, 2 -> Enable for any amount"); + + HookEvent("player_bot_replace", Event_PlayerToBot, EventHookMode_Post); + HookEvent("bot_player_replace", Event_BotToPlayer, EventHookMode_Post); + HookEvent("game_newmap", Event_NewGame); + HookEvent("player_first_spawn", Event_PlayerFirstSpawn); + HookEvent("player_disconnect", Event_PlayerDisconnect); + HookEvent("finale_start", Event_FinaleStart); + HookEvent("player_spawn", Event_PlayerSpawn); + HookEvent("player_death", Event_PlayerDeath, EventHookMode_Pre); + + if(isLateLoad) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && IsPlayerAlive(i) && IsSurvivor(i)) + GetClientModel(i, g_Models[i], 64); + } + } + + chooseMenu = new Menu(Menu_ChooseSurvivor); + chooseMenu.SetTitle("Select survivor preference"); + chooseMenu.AddItem("c", "Clear Prefence"); + char info[2]; + for(int i = 0; i < sizeof(survivor_names); i++) { + Format(info, sizeof(info), "%d", (i+1)); + chooseMenu.AddItem(info, survivor_names[i]); + } + + modelPrefCookie = RegClientCookie("survivor_model", "Survivor model preference", CookieAccess_Public); + RegConsoleCmd("sm_survivor", Cmd_SetSurvivor, "Sets your preferred survivor"); +} + +// ------------------------------------------------------------------------ +// Stores the client of each survivor each time it is changed +// Needed because when Event_PlayerToBot fires, it's hunter model instead +// ------------------------------------------------------------------------ +public MRESReturn SetModel_Pre(int client, Handle hParams) +{ return MRES_Ignored; } // We need this pre hook even though it's empty, or else the post hook will crash the game. + +public MRESReturn SetModel(int client, Handle hParams) +{ + if (!IsValidClient(client)) return MRES_Ignored; + if (!IsSurvivor(client)) + { + g_Models[client][0] = '\0'; + return MRES_Ignored; + } + + char model[128]; + DHookGetParamString(hParams, 1, model, sizeof(model)); + if (StrContains(model, "models/infected", false) < 0) + { + strcopy(g_Models[client], 128, model); + } + return MRES_Ignored; +} + +// -------------------------------------- +// Bot replaced by player +// -------------------------------------- +public void Event_BotToPlayer(Handle event, const char[] name, bool dontBroadcast) +{ + int player = GetClientOfUserId(GetEventInt(event, "player")); + int bot = GetClientOfUserId(GetEventInt(event, "bot")); + + if (!IsValidClient(player) || !IsSurvivor(player) || IsFakeClient(player)) return; // ignore fake players (side product of creating bots) + + char model[128]; + GetClientModel(bot, model, sizeof(model)); + SetEntityModel(player, model); + strcopy(g_Models[player], 64, model); + SetEntProp(player, Prop_Send, "m_survivorCharacter", GetEntProp(bot, Prop_Send, "m_survivorCharacter")); +} + +// -------------------------------------- +// Player -> Bot +// -------------------------------------- +public void Event_PlayerToBot(Handle event, char[] name, bool dontBroadcast) +{ + int player = GetClientOfUserId(GetEventInt(event, "player")); + int bot = GetClientOfUserId(GetEventInt(event, "bot")); + + if (!IsValidClient(player) || !IsSurvivor(player) || IsFakeClient(player)) return; // ignore fake players (side product of creating bots) + if (g_Models[player][0] != '\0') + { + int playerType = GetEntProp(player, Prop_Send, "m_survivorCharacter"); + if(playerType >= 0 && playerType <= 7) { + SetEntProp(bot, Prop_Send, "m_survivorCharacter", playerType); + SetClientInfo(bot, "name", survivor_names[playerType]); + } else { + PrintToServer("[l4d_survivor_identity_fix]: Ignoring player's (%N) m_survivorCharacter due to out of range (%d)", player, playerType); + } + SetEntityModel(bot, g_Models[player]); // Restore saved model. Player model is hunter at this point + } +} + +void GetGamedata() +{ + char filePath[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, filePath, sizeof(filePath), "gamedata/%s.txt", GAMEDATA); + if( FileExists(filePath) ) + { + hConf = LoadGameConfigFile(GAMEDATA); // For some reason this doesn't return null even for invalid files, so check they exist first. + } + else + { + PrintToServer("[SM] %s plugin unable to get %i.txt gamedata file. Generating...", PLUGIN_NAME_SHORT, GAMEDATA); + + Handle fileHandle = OpenFile(filePath, "a+"); + if (fileHandle == null) + { SetFailState("[SM] Couldn't generate gamedata file!"); } + + WriteFileLine(fileHandle, "\"Games\""); + WriteFileLine(fileHandle, "{"); + WriteFileLine(fileHandle, " \"left4dead\""); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"Signatures\""); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"%s\"", NAME_SetModel); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"library\" \"server\""); + WriteFileLine(fileHandle, " \"linux\" \"%s\"", SIG_SetModel_LINUX); + WriteFileLine(fileHandle, " \"windows\" \"%s\"", SIG_L4D1SetModel_WINDOWS); + WriteFileLine(fileHandle, " \"mac\" \"%s\"", SIG_SetModel_LINUX); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, " \"left4dead2\""); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"Signatures\""); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"%s\"", NAME_SetModel); + WriteFileLine(fileHandle, " {"); + WriteFileLine(fileHandle, " \"library\" \"server\""); + WriteFileLine(fileHandle, " \"linux\" \"%s\"", SIG_SetModel_LINUX); + WriteFileLine(fileHandle, " \"windows\" \"%s\"", SIG_SetModel_WINDOWS); + WriteFileLine(fileHandle, " \"mac\" \"%s\"", SIG_SetModel_LINUX); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, " }"); + WriteFileLine(fileHandle, "}"); + + CloseHandle(fileHandle); + hConf = LoadGameConfigFile(GAMEDATA); + if (hConf == null) + { SetFailState("[SM] Failed to load auto-generated gamedata file!"); } + + PrintToServer("[SM] %s successfully generated %s.txt gamedata file!", PLUGIN_NAME_SHORT, GAMEDATA); + } + PrepDHooks(); +} + +void PrepDHooks() +{ + if (hConf == null) + { + SetFailState("Error: Gamedata not found"); + } + + hDHookSetModel = DHookCreateDetour(Address_Null, CallConv_THISCALL, ReturnType_Void, ThisPointer_CBaseEntity); + DHookSetFromConf(hDHookSetModel, hConf, SDKConf_Signature, NAME_SetModel); + DHookAddParam(hDHookSetModel, HookParamType_CharPtr); + DHookEnableDetour(hDHookSetModel, false, SetModel_Pre); + DHookEnableDetour(hDHookSetModel, true, SetModel); +} +//Reset the list of models on a new game -> no players. + +public void Event_NewGame(Event event, const char[] name, bool dontBroadcast) { + PrintToServer("Clearing models"); + for(int i = 1; i <= MaxClients; i++) { + g_Models[i][0] = '\0'; + } + survivors = 0; + cookieModelsSet = false; +} +//Checks if a user has a model preference cookie (set by native). If so, populate g_Models w/ it +public void OnClientCookiesCached(int client) { + return; + if(IsFakeClient(client) || hCookiesEnabled.IntValue == 0) return; + + char modelPref[2]; + modelPrefCookie.Get(client, modelPref, sizeof(modelPref)); + if(strlen(modelPref) > 0) { + //'type' starts at 1, 5 being other l4d1 survivors for l4d2 + int type; + if(StringToIntEx(modelPref, type) > 0) { + PrintToServer("%N has cookie for %s", client, survivor_models[type - 1][17]); + if(isL4D1Survivors && type > 4) { + strcopy(g_Models[client], 32, survivor_models[type - 5]); + g_iPendingCookieModel[client] = type - 5; + } else { + strcopy(g_Models[client], 32, survivor_models[type - 1]); + g_iPendingCookieModel[client] = type - 1; + } + } + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Cookies & Map Fixes +/////////////////////////////////////////////////////////////////////////////// +//Prevent issues with L4D1 characters being TP'd and stuck in brain dead form +public void OnMapStart() { + isL4D1Survivors = L4D2_GetSurvivorSetMap() == 1; + + survivors = 0; + + for(int i = 0; i < sizeof(survivor_models); i++) { + PrecacheModel(survivor_models[i], true); + } + + GetCurrentMap(currentMap, sizeof(currentMap)); +} + +//Either use preferred model OR find the least-used. +public void Event_PlayerFirstSpawn(Event event, const char[] name, bool dontBroadcast) { + if(hCookiesEnabled.IntValue > 0) + RequestFrame(Frame_CheckClient, event.GetInt("userid")); +} +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0) { + IsTemporarilyL4D2[client] = false; + g_Models[client][0] = '\0'; + if(!IsFakeClient(client) && survivors > 0) + survivors--; + } +} +public void Frame_CheckClient(int userid) { + int client = GetClientOfUserId(userid); + if(client > 0 && GetClientTeam(client) == 2 && !IsFakeClient(client)) { + int survivorThreshold = hCookiesEnabled.IntValue == 1 ? 4 : 0; + survivors++; + if(survivors > survivorThreshold) { + //A model is set: Fetched from cookie + if(g_iPendingCookieModel[client]) { + return; + CreateTimer(0.2, Timer_SetClientModel, userid); + }/* else { + CreateTimer(0.2, Timer_SetAllCookieModels); + }*/ //FIXME: Possibly causing people to become rochelle weirdly + }else{ + //Model was not set: Use least-used survivor. + + //RequestFrame(Frame_SetPlayerToLeastUsedModel, client); + } + } +} +public Action Timer_SetClientModel(Handle timer, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0) { + SetEntityModel(client, survivor_models[g_iPendingCookieModel[client] - 1]); + SetEntProp(client, Prop_Send, "m_survivorCharacter", g_iPendingCookieModel[client] - 1); + g_iPendingCookieModel[client] = 0; + } + return Plugin_Handled; +} +public Action Timer_SetAllCookieModels(Handle h) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && g_iPendingCookieModel[i] && GetClientTeam(i) == 2) { + // TODO: Proper implement + SetEntityModel(i, survivor_models[g_iPendingCookieModel[i] - 1]); + SetEntProp(i, Prop_Send, "m_survivorCharacter", g_iPendingCookieModel[i] - 1); + } + g_iPendingCookieModel[i] = 0; + } + return Plugin_Handled; +} + +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && client <= MaxClients && GetClientTeam(client) == 2) { + if(StrEqual(currentMap, "c6m1_riverbank")) { + //If player died as l4d1 character on first map, revert it + RevertSwappedSurvivor(client); + }else if(StrEqual(currentMap, "c6m3_port")) { + //If player not swapped (joined, or via prev. map, switch) + if(IsTemporarilyL4D2[client]) + RequestFrame(Frame_RevertSwappedSurvivor, client); + else + RequestFrame(Frame_SwapSurvivor, client); + } + } +} +public Action Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { + //Switch players to L4D2 right before death. + if(StrEqual(currentMap, "c6m3_port") || StrEqual(currentMap, "c6m1_riverbank")) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && GetClientTeam(client) == 2) { + SwapL4D1Survivor(client, false); + } + } + return Plugin_Continue; +} + + +//On finale start: Set back to their L4D1 character. +public void Event_FinaleStart(Event event, const char[] name, bool dontBroadcast) { + if(StrEqual(currentMap, "c6m3_port")) { + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) { + RevertSwappedSurvivor(i); + } + } + } +} +public void Frame_SwapSurvivor(int client) { + if(IsClientConnected(client) && IsClientInGame(client)) + SwapL4D1Survivor(client, true); +} +public void Frame_RevertSwappedSurvivor(int client) { + if(IsClientConnected(client) && IsClientInGame(client)) + RevertSwappedSurvivor(client); +} + +void SwapL4D1Survivor(int client, bool showMessage) { + int playerType = GetEntProp(client, Prop_Send, "m_survivorCharacter"); + //If character is L4D1 Character (4: bill, etc..) then swap + if(playerType > 3) { + SetEntProp(client, Prop_Send, "m_survivorCharacter", playerType - 4); + IsTemporarilyL4D2[client] = true; + if(showMessage && GetUserAdmin(client) != INVALID_ADMIN_ID) { + PrintToChat(client, "Your survivor is temporarily swapped. Please do not change back, it should auto-revert after the elevator is done. This is to prevent a game bug with L4D1 Survivors on this map."); + } + LogMessage("SwapL4D1Survivor: Swapping %N (type=%d)", client, playerType); + } +} +void RevertSwappedSurvivor(int client) { + if(IsTemporarilyL4D2[client]) { + int playerType = GetEntProp(client, Prop_Send, "m_survivorCharacter"); + if(playerType < 3) { + SetEntProp(client, Prop_Send, "m_survivorCharacter", playerType + 4); + IsTemporarilyL4D2[client] = false; + LogMessage("RevertSwappedSurvivor: Reverting %N (type=%d)", client, playerType); + } + } +} + + +/////////////////////////////////////////////////////////////////////////////// +// Commands +/////////////////////////////////////////////////////////////////////////////// + +public Action Cmd_SetSurvivor(int client, int args) { + if(args > 0) { + char arg1[16]; + GetCmdArg(1, arg1, sizeof(arg1)); + if(arg1[0] == 'c') { + modelPrefCookie.Set(client, ""); + ReplyToCommand(client, "Your survivor preference has been reset"); + return Plugin_Handled; + } + int number; + if(StringToIntEx(arg1, number) > 0 && number >= 0 && number < 8) { + modelPrefCookie.Set(client, arg1); + ReplyToCommand(client, "Your survivor preference set to %s", survivor_names[number]); + return Plugin_Handled; + }else{ + int type = GetSurvivorId(arg1, false); // Use false to have every character have unique id + if(type > -1) { + strcopy(g_Models[client], 64, survivor_models[type]); + if(isL4D1Survivors) type = GetSurvivorId(arg1, true); // Then fetch the correct ids for the survivorCharacter + SetEntProp(client, Prop_Send, "m_survivorCharacter", type); + } + } + } + chooseMenu.Display(client, 0); + return Plugin_Handled; +} + +int Menu_ChooseSurvivor(Menu menu, MenuAction action, int activator, int item) { + if (action == MenuAction_Select) { + char info[2]; + menu.GetItem(item, info, sizeof(info)); + if(info[0] == 'c') { + modelPrefCookie.Set(activator, ""); + ReplyToCommand(activator, "Your survivor preference has been reset"); + }else{ + /*strcopy(g_Models[client], 64, survivor_models[type]); + if(isL4D1Survivors) type = GetSurvivorId(str, true); + SetEntProp(client, Prop_Send, "m_survivorCharacter", type);*/ + modelPrefCookie.Set(activator, info); + ReplyToCommand(activator, "Your survivor preference set to %s", survivor_names[StringToInt(info) - 1]); + } + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// Methods +/////////////////////////////////////////////////////////////////////////////// + +bool IsValidClient(int client, bool replaycheck = true) +{ + if (client <= 0 || client > MaxClients) return false; + if (!IsClientInGame(client)) return false; + if (replaycheck) + { + if (IsClientSourceTV(client) || IsClientReplay(client)) return false; + } + return true; +} + +bool IsSurvivor(int client) +{ + if (GetClientTeam(client) != TEAM_SURVIVOR && GetClientTeam(client) != TEAM_PASSING) return false; + return true; +} + +public int Native_SetPlayerModel(Handle plugin, int numParams) { + int client = GetNativeCell(1); + int character = GetNativeCell(2); + bool keep = GetNativeCell(3) == 1; + if(numParams != 2 && numParams != 3) { + ThrowNativeError(SP_ERROR_NATIVE, "Incorrect amount of parameters passed"); + return 3; + }else if(client < 1 || client > MaxClients || !IsClientInGame(client)) { + ThrowNativeError(SP_ERROR_INDEX, "Client index %d is not valid or is not in game", client); + return 2; + } else if(character < 0 || character > 7) { + ThrowNativeError(SP_ERROR_INDEX, "Character ID (%d) is not in range (0-7)", character); + return 1; + } else { + //Set a cookie to remember their model, starting at 1. + char charTypeStr[2]; + Format(charTypeStr, sizeof(charTypeStr), "%d", character + 1); + if(!IsFakeClient(client) && keep) + modelPrefCookie.Set(client, charTypeStr); + + strcopy(g_Models[client], 64, survivor_models[character]); + return 0; + } +} + +stock int GetSurvivorId(const char str[16], bool isL4D1 = false) { + if(str[0] == 'b') { + return isL4D1 ? 0 : 4; + } else if(str[0] == 'z') { + return isL4D1 ? 1 : 5; + } else if(str[0] == 'l') { + return isL4D1 ? 2 : 7; + } else if(str[0] == 'f') { + return isL4D1 ? 3 : 6; + } else if(str[0] == 'n') { + return 0; + } else if(str[0] == 'r') { + return 1; + } else if(str[0] == 'e') { + return 3; + } else if(str[0] == 'c') { + return 2; + } + return -1; +} \ No newline at end of file diff --git a/scripting/l4d_tank_hp_sprite.sp b/scripting/l4d_tank_hp_sprite.sp new file mode 100644 index 0000000..c3035cf --- /dev/null +++ b/scripting/l4d_tank_hp_sprite.sp @@ -0,0 +1,924 @@ +/** +// ==================================================================================================== +Change Log: + +1.0.6 (12-February-2021) + - Fixed custom model cvar typo. (thanks "weffer" for reporting) + +1.0.5 (11-February-2021) + - Fixed a bug not rendering custom sprites right after turning it on. + - Added one more custom sprite option with an alpha background filling the bar. + +1.0.4 (11-February-2021) + - Added custom sprite option. + +1.0.3 (08-February-2021) + - Fixed missing client in-game in visibility check. (thanks to "Krufftys Killers" and "Striker black") + +1.0.2 (08-February-2021) + - Fixed wrong value on max health calculation. + - Fixed sprite hiding behind tank rocks. + - Fixed sprite hiding while tank throws rocks (ability use). + - Moved visibility logic to timer handle. + +1.0.1 (30-January-2021) + - Public release. + +1.0.0 (21-April-2019) + - Private version. + +// ==================================================================================================== +*/ + +// ==================================================================================================== +// Plugin Info - define +// ==================================================================================================== +#define PLUGIN_NAME "[L4D1 & L4D2] Tank HP Sprite" +#define PLUGIN_AUTHOR "Mart" +#define PLUGIN_DESCRIPTION "Shows a sprite at the tank head that goes from green to red based on its HP" +#define PLUGIN_VERSION "1.0.5" +#define PLUGIN_URL "https://forums.alliedmods.net/showthread.php?t=330370" + +// ==================================================================================================== +// Plugin Info +// ==================================================================================================== +public Plugin myinfo = +{ + name = PLUGIN_NAME, + author = PLUGIN_AUTHOR, + description = PLUGIN_DESCRIPTION, + version = PLUGIN_VERSION, + url = PLUGIN_URL +} + +// ==================================================================================================== +// Includes +// ==================================================================================================== +#include +#include +#include + +// ==================================================================================================== +// Pragmas +// ==================================================================================================== +#pragma semicolon 1 +#pragma newdecls required + +// ==================================================================================================== +// Cvar Flags +// ==================================================================================================== +#define CVAR_FLAGS FCVAR_NOTIFY +#define CVAR_FLAGS_PLUGIN_VERSION FCVAR_NOTIFY|FCVAR_DONTRECORD|FCVAR_SPONLY + +// ==================================================================================================== +// Filenames +// ==================================================================================================== +#define CONFIG_FILENAME "l4d_tank_hp_sprite" + +// ==================================================================================================== +// Defines +// ==================================================================================================== +#define CLASSNAME_ENV_SPRITE "env_sprite" +#define CLASSNAME_ENV_TEXTURETOGGLE "env_texturetoggle" +#define CLASSNAME_TANK_ROCK "tank_rock" + +#define TEAM_SPECTATOR 1 +#define TEAM_SURVIVOR 2 +#define TEAM_INFECTED 3 +#define TEAM_HOLDOUT 4 + +#define FLAG_TEAM_NONE (0 << 0) // 0 | 0000 +#define FLAG_TEAM_SURVIVOR (1 << 0) // 1 | 0001 +#define FLAG_TEAM_INFECTED (1 << 1) // 2 | 0010 +#define FLAG_TEAM_SPECTATOR (1 << 2) // 4 | 0100 +#define FLAG_TEAM_HOLDOUT (1 << 3) // 8 | 1000 + +#define L4D1_ZOMBIECLASS_TANK 5 +#define L4D2_ZOMBIECLASS_TANK 8 + +#define MAXENTITIES 2048 + +// ==================================================================================================== +// Plugin Cvars +// ==================================================================================================== +static ConVar g_hCvar_Enabled; +static ConVar g_hCvar_ZAxis; +static ConVar g_hCvar_FadeDistance; +static ConVar g_hCvar_Sight; +static ConVar g_hCvar_AttackDelay; +static ConVar g_hCvar_AliveShow; +static ConVar g_hCvar_AliveModel; +static ConVar g_hCvar_AliveAlpha; +static ConVar g_hCvar_AliveScale; +static ConVar g_hCvar_DeadShow; +static ConVar g_hCvar_DeadModel; +static ConVar g_hCvar_DeadAlpha; +static ConVar g_hCvar_DeadScale; +static ConVar g_hCvar_DeadColor; +static ConVar g_hCvar_Team; +static ConVar g_hCvar_CustomModel; +static ConVar g_hCvar_CustomModelVMT; +static ConVar g_hCvar_CustomModelVTF; +static ConVar g_hCvar_AllSpecials; + +// ==================================================================================================== +// bool - Plugin Variables +// ==================================================================================================== +static bool g_bL4D2; +static bool g_bConfigLoaded; +static bool g_bEventsHooked; +static bool g_bCvar_Enabled; +static bool g_bCvar_Sight; +static bool g_bCvar_AttackDelay; +static bool g_bCvar_AliveShow; +static bool g_bCvar_DeadShow; +static bool g_bCvar_CustomModel; + +// ==================================================================================================== +// int - Plugin Variables +// ==================================================================================================== +static int g_iTankClass; +static int g_iCvar_AliveAlpha; +static int g_iCvar_DeadAlpha; +static int g_iCvar_FadeDistance; +static int g_iCvar_Team; + +// ==================================================================================================== +// float - Plugin Variables +// ==================================================================================================== +static float g_fVPlayerMins[3] = {-16.0, -16.0, 0.0}; +static float g_fVPlayerMaxs[3] = { 16.0, 16.0, 71.0}; +static float g_fVPos[3]; +static float g_fCvar_ZAxis; +static float g_fCvar_AttackDelay; +static float g_fCvar_AliveScale; +static float g_fCvar_DeadScale; + +// ==================================================================================================== +// string - Plugin Variables +// ==================================================================================================== +static char g_sCvar_AliveModel[100]; +static char g_sCvar_AliveAlpha[4]; +static char g_sCvar_AliveScale[5]; +static char g_sCvar_DeadModel[100]; +static char g_sCvar_DeadAlpha[4]; +static char g_sCvar_DeadScale[5]; +static char g_sCvar_DeadColor[12]; +static char g_sCvar_FadeDistance[5]; +static char g_sCvar_CustomModelVMT[100]; +static char g_sCvar_CustomModelVTF[100]; + +// ==================================================================================================== +// client - Plugin Variables +// ==================================================================================================== +static int gc_iTankSpriteRef[MAXPLAYERS+1] = { INVALID_ENT_REFERENCE, ... }; +static int gc_iTankSpriteFrameRef[MAXPLAYERS+1] = { INVALID_ENT_REFERENCE, ... }; +static bool gc_bVisible[MAXPLAYERS+1][MAXPLAYERS+1]; +static float gc_fLastAttack[MAXPLAYERS+1][MAXPLAYERS+1]; + +// ==================================================================================================== +// entity - Plugin Variables +// ==================================================================================================== +static bool ge_bInvalidTrace[MAXENTITIES+1]; +static int ge_iOwner[MAXENTITIES+1]; + +// ==================================================================================================== +// Plugin Start +// ==================================================================================================== +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + EngineVersion engine = GetEngineVersion(); + + if (engine != Engine_Left4Dead && engine != Engine_Left4Dead2) + { + strcopy(error, err_max, "This plugin only runs in \"Left 4 Dead\" and \"Left 4 Dead 2\" game"); + return APLRes_SilentFailure; + } + + g_bL4D2 = (engine == Engine_Left4Dead2); + g_iTankClass = (g_bL4D2 ? L4D2_ZOMBIECLASS_TANK : L4D1_ZOMBIECLASS_TANK); + + return APLRes_Success; +} + +/****************************************************************************************************/ + +public void OnPluginStart() +{ + CreateConVar("l4d_tank_hp_sprite_version", PLUGIN_VERSION, PLUGIN_DESCRIPTION, CVAR_FLAGS_PLUGIN_VERSION); + g_hCvar_Enabled = CreateConVar("l4d_tank_hp_sprite_enable", "1", "Enable/Disable the plugin.\n0 = Disable, 1 = Enable.", CVAR_FLAGS, true, 0.0, true, 1.0); + g_hCvar_ZAxis = CreateConVar("l4d_tank_hp_sprite_z_axis", "92", "Additional Z distance based on the tank position.", CVAR_FLAGS, true, 0.0); + g_hCvar_FadeDistance = CreateConVar("l4d_tank_hp_sprite_fade_distance", "-1", "Minimum distance that a client must be from the tank to see the sprite (both alive and dead sprites).\n-1 = Always visible.", CVAR_FLAGS, true, -1.0, true, 9999.0); + g_hCvar_Sight = CreateConVar("l4d_tank_hp_sprite_sight", "1", "Show the sprite to the survivor only if the Tank is on sight.\n0 = OFF, 1 = ON.", CVAR_FLAGS, true, 0.0, true, 1.0); + g_hCvar_AttackDelay = CreateConVar("l4d_tank_hp_sprite_attack_delay", "0.0", "Show the sprite to the survivor attacker, by this amount of time in seconds, after hitting the Tank.\n0 = OFF.", CVAR_FLAGS, true, 0.0); + g_hCvar_AliveShow = CreateConVar("l4d_tank_hp_sprite_alive_show", "1", "Show the alive sprite while tank is alive.\n0 = OFF, 1 = ON.", CVAR_FLAGS, true, 0.0, true, 1.0); + g_hCvar_AliveModel = CreateConVar("l4d_tank_hp_sprite_alive_model", "materials/vgui/healthbar_white.vmt", "Model of alive tank sprite."); + g_hCvar_AliveAlpha = CreateConVar("l4d_tank_hp_sprite_alive_alpha", "200", "Alpha of alive tank sprite.\n0 = Invisible, 255 = Fully Visible", CVAR_FLAGS, true, 0.0, true, 255.0); + g_hCvar_AliveScale = CreateConVar("l4d_tank_hp_sprite_alive_scale", "0.25", "Scale of alive tank sprite (increases both height and width).\nNote: Some range values maintain the same size. (e.g. from 0.0 to 0.38 the size doesn't change).", CVAR_FLAGS, true, 0.0); + g_hCvar_DeadShow = CreateConVar("l4d_tank_hp_sprite_dead_show", "1", "Show the dead sprite when a tank dies.\n0 = OFF, 1 = ON.", CVAR_FLAGS, true, 0.0, true, 1.0); + g_hCvar_DeadModel = CreateConVar("l4d_tank_hp_sprite_dead_model", "materials/sprites/death_icon.vmt", "Model of dead tank sprite."); + g_hCvar_DeadAlpha = CreateConVar("l4d_tank_hp_sprite_dead_alpha", "200", "Alpha of dead tank sprite.\n0 = Invisible, 255 = Fully Visible", CVAR_FLAGS, true, 0.0, true, 255.0); + g_hCvar_DeadScale = CreateConVar("l4d_tank_hp_sprite_dead_scale", "0.25", "Scale of dead tank sprite (increases both height and width).\nSome range values maintain the size the same.", CVAR_FLAGS, true, 0.0); + g_hCvar_DeadColor = CreateConVar("l4d_tank_hp_sprite_dead_color", "225 0 0", "Color of dead tank sprite.\nUse three values between 0-255 separated by spaces (\"<0-255> <0-255> <0-255>\").", CVAR_FLAGS); + g_hCvar_Team = CreateConVar("l4d_tank_hp_sprite_team", "3", "Which teams should the sprite be visible.\n0 = NONE, 1 = SURVIVOR, 2 = INFECTED, 4 = SPECTATOR, 8 = HOLDOUT.\nAdd numbers greater than 0 for multiple options.\nExample: \"3\", enables for SURVIVOR and INFECTED.", CVAR_FLAGS, true, 0.0, true, 15.0); + g_hCvar_CustomModel = CreateConVar("l4d_tank_hp_sprite_custom_model", "0", "Use a custom sprite for the alive model\nNote: This requires the client downloading the custom model (.vmt and .vtf) to work.\nSearch for FastDL for more info.\n0 = OFF, 1 = ON.", CVAR_FLAGS, true, 0.0, true, 1.0); + g_hCvar_CustomModelVMT = CreateConVar("l4d_tank_hp_sprite_custom_model_vmt", "materials/mart/mart_custombar.vmt", "Custom sprite VMT path."); + g_hCvar_CustomModelVTF = CreateConVar("l4d_tank_hp_sprite_custom_model_vtf", "materials/mart/mart_custombar.vtf", "Custom sprite VTF path."); + g_hCvar_AllSpecials = CreateConVar("l4d_tank_hp_sprite_all_specials", "1", "Should all specials have healthbar or only tanks\n0 = Tanks Only, 1 = All Specials", CVAR_FLAGS, true, 0.0, true, 1.0); + + g_hCvar_Enabled.AddChangeHook(Event_ConVarChanged); + g_hCvar_ZAxis.AddChangeHook(Event_ConVarChanged); + g_hCvar_FadeDistance.AddChangeHook(Event_ConVarChanged); + g_hCvar_Sight.AddChangeHook(Event_ConVarChanged); + g_hCvar_AttackDelay.AddChangeHook(Event_ConVarChanged); + g_hCvar_AliveShow.AddChangeHook(Event_ConVarChanged); + g_hCvar_AliveModel.AddChangeHook(Event_ConVarChanged); + g_hCvar_AliveAlpha.AddChangeHook(Event_ConVarChanged); + g_hCvar_AliveScale.AddChangeHook(Event_ConVarChanged); + g_hCvar_DeadShow.AddChangeHook(Event_ConVarChanged); + g_hCvar_DeadModel.AddChangeHook(Event_ConVarChanged); + g_hCvar_DeadAlpha.AddChangeHook(Event_ConVarChanged); + g_hCvar_DeadScale.AddChangeHook(Event_ConVarChanged); + g_hCvar_DeadColor.AddChangeHook(Event_ConVarChanged); + g_hCvar_Team.AddChangeHook(Event_ConVarChanged); + g_hCvar_CustomModel.AddChangeHook(Event_ConVarChanged); + g_hCvar_CustomModelVMT.AddChangeHook(Event_ConVarChanged); + g_hCvar_CustomModelVTF.AddChangeHook(Event_ConVarChanged); + + // Load plugin configs from .cfg + AutoExecConfig(true, CONFIG_FILENAME); + + // Admin Commands + RegAdminCmd("sm_print_cvars_l4d_tank_hp_sprite", CmdPrintCvars, ADMFLAG_ROOT, "Print the plugin related cvars and their respective values to the console."); + + CreateTimer(0.1, TimerKill, _, TIMER_REPEAT); + CreateTimer(0.1, TimerVisible, _, TIMER_REPEAT); + CreateTimer(0.1, TimerRender, _, TIMER_REPEAT); +} + +/****************************************************************************************************/ + +public void OnPluginEnd() +{ + int entity; + char targetname[19]; + + entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, CLASSNAME_ENV_SPRITE)) != INVALID_ENT_REFERENCE) + { + if (GetEntProp(entity, Prop_Data, "m_iHammerID") == -1) + { + GetEntPropString(entity, Prop_Data, "m_iName", targetname, sizeof(targetname)); + if (StrEqual(targetname, "l4d_tank_hp_sprite")) + AcceptEntityInput(entity, "Kill"); + } + } +} + +/****************************************************************************************************/ + +public void OnConfigsExecuted() +{ + GetCvars(); + + g_bConfigLoaded = true; + + LateLoad(); + + HookEvents(g_bCvar_Enabled); +} + +/****************************************************************************************************/ + +public void Event_ConVarChanged(Handle convar, const char[] sOldValue, const char[] sNewValue) +{ + GetCvars(); + + HookEvents(g_bCvar_Enabled); +} + +/****************************************************************************************************/ + +public void GetCvars() +{ + g_bCvar_Enabled = g_hCvar_Enabled.BoolValue; + g_fCvar_ZAxis = g_hCvar_ZAxis.FloatValue; + g_fVPos[2] = g_fCvar_ZAxis; + g_iCvar_FadeDistance = g_hCvar_FadeDistance.IntValue; + FormatEx(g_sCvar_FadeDistance, sizeof(g_sCvar_FadeDistance), "%i", g_iCvar_FadeDistance); + g_bCvar_Sight = g_hCvar_Sight.BoolValue; + g_fCvar_AttackDelay = g_hCvar_AttackDelay.FloatValue; + g_bCvar_AttackDelay = (g_fCvar_AttackDelay > 0.0); + g_bCvar_AliveShow = g_hCvar_AliveShow.BoolValue; + g_hCvar_AliveModel.GetString(g_sCvar_AliveModel, sizeof(g_sCvar_AliveModel)); + TrimString(g_sCvar_AliveModel); + g_iCvar_AliveAlpha = g_hCvar_AliveAlpha.IntValue; + FormatEx(g_sCvar_AliveAlpha, sizeof(g_sCvar_AliveAlpha), "%i", g_iCvar_AliveAlpha); + g_fCvar_AliveScale = g_hCvar_AliveScale.FloatValue; + FormatEx(g_sCvar_AliveScale, sizeof(g_sCvar_AliveScale), "%.2f", g_fCvar_AliveScale); + g_bCvar_DeadShow = g_hCvar_DeadShow.BoolValue; + g_hCvar_DeadModel.GetString(g_sCvar_DeadModel, sizeof(g_sCvar_DeadModel)); + TrimString(g_sCvar_DeadModel); + g_iCvar_DeadAlpha = g_hCvar_DeadAlpha.IntValue; + FormatEx(g_sCvar_DeadAlpha, sizeof(g_sCvar_DeadAlpha), "%i", g_iCvar_DeadAlpha); + g_fCvar_DeadScale = g_hCvar_DeadScale.FloatValue; + FormatEx(g_sCvar_DeadScale, sizeof(g_sCvar_DeadScale), "%.2f", g_fCvar_DeadScale); + g_hCvar_DeadColor.GetString(g_sCvar_DeadColor, sizeof(g_sCvar_DeadColor)); + TrimString(g_sCvar_DeadColor); + g_iCvar_Team = g_hCvar_Team.IntValue; + g_bCvar_CustomModel = g_hCvar_CustomModel.BoolValue; + g_hCvar_CustomModelVMT.GetString(g_sCvar_CustomModelVMT, sizeof(g_sCvar_CustomModelVMT)); + TrimString(g_sCvar_CustomModelVMT); + g_hCvar_CustomModelVTF.GetString(g_sCvar_CustomModelVTF, sizeof(g_sCvar_CustomModelVTF)); + TrimString(g_sCvar_CustomModelVTF); + + if (g_bCvar_AliveShow) + { + if (g_bCvar_CustomModel) + { + AddFileToDownloadsTable(g_sCvar_CustomModelVMT); + AddFileToDownloadsTable(g_sCvar_CustomModelVTF); + PrecacheModel(g_sCvar_CustomModelVMT, true); + } + else + { + PrecacheModel(g_sCvar_AliveModel, true); + } + } + + if (g_bCvar_DeadShow) + PrecacheModel(g_sCvar_DeadModel, true); +} + +/****************************************************************************************************/ + +public void LateLoad() +{ + for (int client = 1; client <= MaxClients; client++) + { + if (!IsPlayerTank(client)) + continue; + + TankSprite(client); + } +} + +/****************************************************************************************************/ + +public void OnClientDisconnect(int client) +{ + if (!g_bConfigLoaded) + return; + + gc_iTankSpriteRef[client] = INVALID_ENT_REFERENCE; + gc_iTankSpriteFrameRef[client] = INVALID_ENT_REFERENCE; + + for (int target = 1; target <= MaxClients; target++) + { + gc_bVisible[target][client] = false; + gc_fLastAttack[target][client] = 0.0; + } +} + +/****************************************************************************************************/ + +public void OnEntityDestroyed(int entity) +{ + if (!g_bConfigLoaded) + return; + + if (!IsValidEntityIndex(entity)) + return; + + ge_bInvalidTrace[entity] = false; + ge_iOwner[entity] = 0; +} + +/****************************************************************************************************/ + +public void OnEntityCreated(int entity, const char[] classname) +{ + if (!g_bConfigLoaded) + return; + + if (!IsValidEntityIndex(entity)) + return; + + switch (classname[0]) + { + case 't': + { + if (StrEqual(classname, CLASSNAME_TANK_ROCK)) + ge_bInvalidTrace[entity] = true; + } + } +} + +/****************************************************************************************************/ + +public void HookEvents(bool hook) +{ + if (hook && !g_bEventsHooked) + { + g_bEventsHooked = true; + + HookEvent("tank_spawn", Event_TankSpawn); + HookEvent("player_hurt", Event_PlayerHurt); + + return; + } + + if (!hook && g_bEventsHooked) + { + g_bEventsHooked = false; + + UnhookEvent("tank_spawn", Event_TankSpawn); + UnhookEvent("player_hurt", Event_PlayerHurt); + + return; + } +} + +/****************************************************************************************************/ + +public void Event_TankSpawn(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + + if (!IsValidClient(client)) + return; + + TankSprite(client); +} + +/****************************************************************************************************/ + +public void Event_PlayerHurt(Event event, const char[] name, bool dontBroadcast) +{ + if (!g_bCvar_AttackDelay) + return; + + int target = GetClientOfUserId(event.GetInt("userid")); + + if (!IsPlayerTank(target)) + return; + + int attacker = GetClientOfUserId(event.GetInt("attacker")); + + if (!IsValidClient(attacker)) + return; + + if (GetClientTeam(attacker) != TEAM_SURVIVOR) + return; + + gc_fLastAttack[target][attacker] = GetGameTime(); +} + +/****************************************************************************************************/ + +public Action TimerKill(Handle timer) +{ + if (!g_bConfigLoaded) + return Plugin_Continue; + + for (int target = 1; target <= MaxClients; target++) + { + if (gc_iTankSpriteRef[target] == INVALID_ENT_REFERENCE) + continue; + + if (g_bCvar_Enabled && IsPlayerTank(target)) + continue; + + int entity = EntRefToEntIndex(gc_iTankSpriteRef[target]); + + if (entity != INVALID_ENT_REFERENCE) + AcceptEntityInput(entity, "Kill"); + + gc_iTankSpriteRef[target] = INVALID_ENT_REFERENCE; + gc_iTankSpriteFrameRef[target] = INVALID_ENT_REFERENCE; + + for (int client = 1; client <= MaxClients; client++) + { + gc_bVisible[target][client] = false; + gc_fLastAttack[target][client] = 0.0; + } + } + + return Plugin_Continue; +} + +/****************************************************************************************************/ + +public Action TimerVisible(Handle timer) +{ + if (!g_bConfigLoaded) + return Plugin_Continue; + + if (!g_bCvar_Enabled) + return Plugin_Continue; + + for (int target = 1; target <= MaxClients; target++) + { + if (gc_iTankSpriteRef[target] == INVALID_ENT_REFERENCE) + continue; + + if (!IsClientInGame(target)) + continue; + + for (int client = 1; client <= MaxClients; client++) + { + gc_bVisible[target][client] = false; + + if (!IsClientInGame(client)) + continue; + + if (IsFakeClient(client)) + continue; + + if (!(GetTeamFlag(GetClientTeam(client)) & g_iCvar_Team)) + continue; + + if (g_bCvar_AttackDelay || g_bCvar_Sight) + { + if (GetClientTeam(client) == TEAM_SURVIVOR || GetClientTeam(client) == TEAM_HOLDOUT) + { + if (g_bCvar_AttackDelay && (GetGameTime() - gc_fLastAttack[target][client] > g_fCvar_AttackDelay)) + continue; + + if (g_bCvar_Sight && !IsVisibleTo(client, target)) + continue; + } + } + + gc_bVisible[target][client] = true; + } + } + + return Plugin_Continue; +} + +/****************************************************************************************************/ + +public Action TimerRender(Handle timer) +{ + if (!g_bConfigLoaded) + return Plugin_Continue; + + if (!g_bCvar_Enabled) + return Plugin_Continue; + + for (int target = 1; target <= MaxClients; target++) + { + if (!IsPlayerTank(target)) + continue; + + TankSprite(target); + } + + return Plugin_Continue; +} + +/****************************************************************************************************/ + +public void TankSprite(int client) +{ + int entity = INVALID_ENT_REFERENCE; + + if (gc_iTankSpriteRef[client] != INVALID_ENT_REFERENCE) + entity = EntRefToEntIndex(gc_iTankSpriteRef[client]); + + if (entity == INVALID_ENT_REFERENCE) + { + char targetname[22]; + FormatEx(targetname, sizeof(targetname), "%s-%i", "l4d_tank_hp_sprite", client); + + entity = CreateEntityByName(CLASSNAME_ENV_SPRITE); + ge_iOwner[entity] = client; + gc_iTankSpriteRef[client] = EntIndexToEntRef(entity); + DispatchKeyValue(entity, "targetname", targetname); + DispatchKeyValue(entity, "spawnflags", "1"); + DispatchKeyValue(entity, "fademindist", g_sCvar_FadeDistance); + SetEntProp(entity, Prop_Data, "m_iHammerID", -1); + SDKHook(entity, SDKHook_SetTransmit, OnSetTransmit); + } + + if (g_bCvar_CustomModel) + { + int entityFrame = INVALID_ENT_REFERENCE; + + if (gc_iTankSpriteFrameRef[client] != INVALID_ENT_REFERENCE) + entityFrame = EntRefToEntIndex(gc_iTankSpriteFrameRef[client]); + + if (entityFrame == INVALID_ENT_REFERENCE) + { + char targetname[22]; + FormatEx(targetname, sizeof(targetname), "%s-%i", "l4d_tank_hp_sprite", client); + + entityFrame = CreateEntityByName(CLASSNAME_ENV_TEXTURETOGGLE); + gc_iTankSpriteFrameRef[client] = EntIndexToEntRef(entityFrame); + DispatchKeyValue(entityFrame, "targetname", "l4d_tank_hp_sprite"); + DispatchKeyValue(entityFrame, "target", targetname); + + TeleportEntity(entityFrame, g_fVPos, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(entityFrame); + ActivateEntity(entityFrame); + + SetVariantString("!activator"); + AcceptEntityInput(entityFrame, "SetParent", entity); + } + } + + if (IsPlayerIncapacitated(client)) + { + if (g_bCvar_DeadShow) + { + DispatchKeyValue(entity, "model", g_sCvar_DeadModel); + DispatchKeyValue(entity, "rendercolor", g_sCvar_DeadColor); + DispatchKeyValue(entity, "renderamt", g_sCvar_DeadAlpha); // If renderamt goes before rendercolor, it doesn't render + DispatchKeyValue(entity, "scale", g_sCvar_DeadScale); + + TeleportEntity(entity, g_fVPos, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(entity); + ActivateEntity(entity); + + SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", client); + SetVariantString("!activator"); + AcceptEntityInput(entity, "SetParent", client); + AcceptEntityInput(entity, "ShowSprite"); + } + + return; + } + + if (!g_bCvar_AliveShow) + { + AcceptEntityInput(entity, "HideSprite"); + return; + } + + int maxHealth = GetEntProp(client, Prop_Data, "m_iMaxHealth"); + int currentHealth = GetClientHealth(client); + + float percentageHealth; + if (maxHealth > 0) + percentageHealth = (float(currentHealth) / float(maxHealth)); + + bool halfHealth = (percentageHealth <= 0.5); + + char sRenderColor[12]; + Format(sRenderColor, sizeof(sRenderColor), "%i %i 0", halfHealth ? 255 : RoundFloat(255.0 * ((1.0 - percentageHealth) * 2)), halfHealth ? RoundFloat(255.0 * (percentageHealth) * 2) : 255); + + DispatchKeyValue(entity, "model", g_bCvar_CustomModel ? g_sCvar_CustomModelVMT : g_sCvar_AliveModel); + DispatchKeyValue(entity, "rendercolor", sRenderColor); + DispatchKeyValue(entity, "renderamt", g_sCvar_AliveAlpha); // If renderamt goes before rendercolor, it doesn't render + DispatchKeyValue(entity, "scale", g_sCvar_AliveScale); + + TeleportEntity(entity, g_fVPos, NULL_VECTOR, NULL_VECTOR); + DispatchSpawn(entity); + ActivateEntity(entity); + + SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", client); + SetVariantString("!activator"); + AcceptEntityInput(entity, "SetParent", client); + AcceptEntityInput(entity, "ShowSprite"); + + if (!g_bCvar_CustomModel) + return; + + int entityFrame = EntRefToEntIndex(gc_iTankSpriteFrameRef[client]); + + if (entityFrame == INVALID_ENT_REFERENCE) + return; + + int frame = RoundFloat(percentageHealth * 100); + + char input[38]; + FormatEx(input, sizeof(input), "OnUser1 !self:SetTextureIndex:%i:0:1", frame); + SetVariantString(input); + AcceptEntityInput(entityFrame, "AddOutput"); + AcceptEntityInput(entityFrame, "FireUser1"); +} + +/****************************************************************************************************/ + +public Action OnSetTransmit(int entity, int client) +{ + int owner = ge_iOwner[entity]; + + if (owner == client) + return Plugin_Handled; + + if (gc_bVisible[owner][client]) + return Plugin_Continue; + + return Plugin_Handled; +} + +/****************************************************************************************************/ + +bool IsVisibleTo(int client, int target) +{ + float vClientPos[3]; + float vEntityPos[3]; + float vLookAt[3]; + float vAng[3]; + + GetClientEyePosition(client, vClientPos); + GetClientEyePosition(target, vEntityPos); + MakeVectorFromPoints(vClientPos, vEntityPos, vLookAt); + GetVectorAngles(vLookAt, vAng); + + Handle trace = TR_TraceRayFilterEx(vClientPos, vAng, MASK_PLAYERSOLID, RayType_Infinite, TraceFilter, target); + + bool isVisible; + + if (TR_DidHit(trace)) + { + isVisible = (TR_GetEntityIndex(trace) == target); + + if (!isVisible) + { + vEntityPos[2] -= 62.0; // results the same as GetClientAbsOrigin + + delete trace; + trace = TR_TraceHullFilterEx(vClientPos, vEntityPos, g_fVPlayerMins, g_fVPlayerMaxs, MASK_PLAYERSOLID, TraceFilter, target); + + if (TR_DidHit(trace)) + isVisible = (TR_GetEntityIndex(trace) == target); + } + } + + delete trace; + + return isVisible; +} + +/****************************************************************************************************/ + +public bool TraceFilter(int entity, int contentsMask, int client) +{ + if (entity == client) + return true; + + if (IsValidClientIndex(entity)) + return false; + + return ge_bInvalidTrace[entity] ? false : true; +} + +/****************************************************************************************************/ + +public Action CmdPrintCvars(int client, int args) +{ + PrintToConsole(client, ""); + PrintToConsole(client, "======================================================================"); + PrintToConsole(client, ""); + PrintToConsole(client, "----------------- Plugin Cvars (l4d_tank_hp_sprite) ------------------"); + PrintToConsole(client, ""); + PrintToConsole(client, "l4d_tank_hp_sprite_version : %s", PLUGIN_VERSION); + PrintToConsole(client, "l4d_tank_hp_sprite_enable : %b (%s)", g_bCvar_Enabled, g_bCvar_Enabled ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_z_axis : %.2f", g_fCvar_ZAxis); + PrintToConsole(client, "l4d_tank_hp_sprite_fade_distance : %i", g_iCvar_FadeDistance); + PrintToConsole(client, "l4d_tank_hp_sprite_sight : %b (%s)", g_bCvar_Sight, g_bCvar_Sight ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_attack_delay : %.2f (%s)", g_fCvar_AttackDelay, g_bCvar_AttackDelay ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_alive_show : %b (%s)", g_bCvar_AliveShow, g_bCvar_AliveShow ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_alive_model : \"%s\"", g_sCvar_AliveModel); + PrintToConsole(client, "l4d_tank_hp_sprite_alive_alpha : %i", g_iCvar_AliveAlpha); + PrintToConsole(client, "l4d_tank_hp_sprite_alive_scale : %.2f", g_fCvar_AliveScale); + PrintToConsole(client, "l4d_tank_hp_sprite_dead_show : %b (%s)", g_bCvar_DeadShow, g_bCvar_DeadShow ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_dead_model : \"%s\"", g_sCvar_DeadModel); + PrintToConsole(client, "l4d_tank_hp_sprite_dead_alpha : %i", g_iCvar_DeadAlpha); + PrintToConsole(client, "l4d_tank_hp_sprite_dead_scale : %.2f", g_fCvar_DeadScale); + PrintToConsole(client, "l4d_tank_hp_sprite_dead_color : \"%s\"", g_sCvar_DeadColor); + PrintToConsole(client, "l4d_tank_hp_sprite_team : %i", g_iCvar_Team); + PrintToConsole(client, "l4d_tank_hp_sprite_custom_model : %b (%s)", g_bCvar_CustomModel, g_bCvar_CustomModel ? "true" : "false"); + PrintToConsole(client, "l4d_tank_hp_sprite_custom_model_vmt : \"%s\"", g_sCvar_CustomModelVMT); + PrintToConsole(client, "l4d_tank_hp_sprite_custom_model_vtf : \"%s\"", g_sCvar_CustomModelVTF); + PrintToConsole(client, ""); + PrintToConsole(client, "======================================================================"); + PrintToConsole(client, ""); + + return Plugin_Handled; +} + +// ==================================================================================================== +// Helpers +// ==================================================================================================== +/** + * Validates if is a valid client index. + * + * @param client Client index. + * @return True if client index is valid, false otherwise. + */ +bool IsValidClientIndex(int client) +{ + return (1 <= client <= MaxClients); +} + +/****************************************************************************************************/ + +/** + * Validates if is a valid client. + * + * @param client Client index. + * @return True if client index is valid and client is in game, false otherwise. + */ +bool IsValidClient(int client) +{ + return (IsValidClientIndex(client) && IsClientInGame(client)); +} + +/****************************************************************************************************/ + +/** + * Validates if is a valid entity index (between MaxClients+1 and 2048). + * + * @param entity Entity index. + * @return True if entity index is valid, false otherwise. + */ +bool IsValidEntityIndex(int entity) +{ + return (MaxClients+1 <= entity <= GetMaxEntities()); +} + +/****************************************************************************************************/ + +/** + * Gets the client L4D1/L4D2 zombie class id. + * + * @param client Client index. + * @return L4D1 1=SMOKER, 2=BOOMER, 3=HUNTER, 4=WITCH, 5=TANK, 6=NOT INFECTED + * @return L4D2 1=SMOKER, 2=BOOMER, 3=HUNTER, 4=SPITTER, 5=JOCKEY, 6=CHARGER, 7=WITCH, 8=TANK, 9=NOT INFECTED + */ +int GetZombieClass(int client) +{ + return (GetEntProp(client, Prop_Send, "m_zombieClass")); +} + +/****************************************************************************************************/ + +/** + * Returns is a player is in ghost state. + * + * @param client Client index. + * @return True if client is in ghost state, false otherwise. + */ +bool IsPlayerGhost(int client) +{ + return (GetEntProp(client, Prop_Send, "m_isGhost") == 1); +} + +/****************************************************************************************************/ + +/** + * Validates if the client is incapacitated. + * + * @param client Client index. + * @return True if the client is incapacitated, false otherwise. + */ +bool IsPlayerIncapacitated(int client) +{ + return (GetEntProp(client, Prop_Send, "m_isIncapacitated") == 1); +} + +/****************************************************************************************************/ + +/** + * Returns if the client is a valid tank. + * + * @param client Client index. + * @return True if client is a tank, false otherwise. + */ +bool IsPlayerTank(int client) +{ + bool isValid = IsValidClient(client) && GetClientTeam(client) == TEAM_INFECTED && IsPlayerAlive(client) && !IsPlayerGhost(client); + if(!g_hCvar_AllSpecials.BoolValue && GetZombieClass(client) != g_iTankClass) + return false; + else + return isValid; +} + +/****************************************************************************************************/ + +/** + * Returns the team flag from a team. + * + * @param team Team index. + * @return Team flag. + */ +int GetTeamFlag(int team) +{ + switch (team) + { + case TEAM_SURVIVOR: + return FLAG_TEAM_SURVIVOR; + case TEAM_INFECTED: + return FLAG_TEAM_INFECTED; + case TEAM_SPECTATOR: + return FLAG_TEAM_SPECTATOR; + case TEAM_HOLDOUT: + return FLAG_TEAM_HOLDOUT; + default: + return FLAG_TEAM_NONE; + } +} \ No newline at end of file diff --git a/scripting/l4dunreservelobby.sp b/scripting/l4dunreservelobby.sp new file mode 100644 index 0000000..bd58ad8 --- /dev/null +++ b/scripting/l4dunreservelobby.sp @@ -0,0 +1,149 @@ +#include +#include +#include + +#define UNRESERVE_VERSION "1.1.1" + +#define UNRESERVE_DEBUG 0 +#define UNRESERVE_DEBUG_LOG 0 + +#define L4D_MAXCLIENTS MaxClients +#define L4D_MAXCLIENTS_PLUS1 (L4D_MAXCLIENTS + 1) + +#define L4D_MAXHUMANS_LOBBY_VERSUS 8 +#define L4D_MAXHUMANS_LOBBY_OTHER 4 + +ConVar cvarGameMode; +ConVar cvarUnreserve; + +public Plugin myinfo = +{ + name = "L4D1/2 Remove Lobby Reservation", + author = "Downtown1", + description = "Removes lobby reservation when server is full", + version = UNRESERVE_VERSION, + url = "http://forums.alliedmods.net/showthread.php?t=87759" +} + + +public OnPluginStart() +{ + LoadTranslations("common.phrases"); + + RegAdminCmd("sm_unreserve", Command_Unreserve, ADMFLAG_BAN, "sm_unreserve - manually force removes the lobby reservation"); + + cvarUnreserve = CreateConVar("l4d_unreserve_full", "1", "Automatically unreserve server after a full lobby joins", FCVAR_SPONLY|FCVAR_NOTIFY); + CreateConVar("l4d_unreserve_version", UNRESERVE_VERSION, "Version of the Lobby Unreserve plugin.", FCVAR_SPONLY|FCVAR_NOTIFY); + + HookEvent("game_init", Event_GameStart); + + + cvarGameMode = FindConVar("mp_gamemode"); +} + +void Event_GameStart(Event event, const char[] name, bool dontBroadcast) { + CreateTimer(20.0, Timer_CheckPlayers); +} + +Action Timer_CheckPlayers(Handle h) { + if(AreAllPlayersConnecting()) { + PrintToServer("4 Players connecting, unreserving"); + L4D_LobbyUnreserve(); + } + return Plugin_Continue; +} + +bool AreAllPlayersConnecting() { + int count = 0; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i)) { + if(!IsClientInGame(i)) return false; + count++; + } + } + return count >= 4; +} + +bool IsServerLobbyFull() +{ + int humans = GetHumanCount(); + + DebugPrintToAll("IsServerLobbyFull : humans = %d", humans); + + char sGameMode[32]; + cvarGameMode.GetString(sGameMode, sizeof(sGameMode)); + if(StrEqual(sGameMode, "versus") || StrEqual(sGameMode, "scavenge")) + { + return humans >= L4D_MAXHUMANS_LOBBY_VERSUS; + } + return humans >= L4D_MAXHUMANS_LOBBY_OTHER; +} + +public OnClientPutInServer(int client) +{ + DebugPrintToAll("Client put in server %N", client); + + if(GetConVarBool(cvarUnreserve) && /*L4D_LobbyIsReserved() &&*/ IsServerLobbyFull()) + { + //PrintToChatAll("[SM] A full lobby has connected, automatically unreserving the server."); + L4D_LobbyUnreserve(); + } +} + +Action Command_Unreserve(int client, int args) +{ + /*if(!L4D_LobbyIsReserved()) + { + ReplyToCommand(client, "[SM] Server is already unreserved."); + }*/ + + L4D_LobbyUnreserve(); + PrintToChatAll("[SM] Lobby reservation has been removed."); + + return Plugin_Handled; +} + + +//client is in-game and not a bot +stock bool IsClientInGameHuman(int client) +{ + return IsClientInGame(client) && !IsFakeClient(client); +} + +stock int GetHumanCount() +{ + int humans = 0; + + int i; + for(i = 1; i < L4D_MAXCLIENTS_PLUS1; i++) + { + if(IsClientInGameHuman(i)) + { + humans++ + } + } + + return humans; +} + +void DebugPrintToAll(const char[] format, any...) +{ + #if UNRESERVE_DEBUG || UNRESERVE_DEBUG_LOG + char buffer[192]; + + VFormat(buffer, sizeof(buffer), format, 2); + + #if UNRESERVE_DEBUG + PrintToChatAll("[UNRESERVE] %s", buffer); + PrintToConsole(0, "[UNRESERVE] %s", buffer); + #endif + + LogMessage("%s", buffer); + #else + //suppress "format" never used warning + if(format[0]) + return; + else + return; + #endif +} \ No newline at end of file diff --git a/scripting/sceneprocessor.sp b/scripting/sceneprocessor.sp new file mode 100644 index 0000000..dc2c2d1 --- /dev/null +++ b/scripting/sceneprocessor.sp @@ -0,0 +1,855 @@ +#define PLUGIN_VERSION "1.33.2" + +#pragma semicolon 1 +#pragma newdecls required + +#include +#include +#include + +#include + +int iSkippedFrames; +char sVocalizeScene[MAXPLAYERS+1][MAX_VOCALIZE_LENGTH]; +bool bSceneHasInitiator[MAXPLAYERS+1], bScenesUnprocessed, bUnvocalizedCommands, bJailbreakVocalize, bIsL4D; + +float fStartTimeStamp, fVocalizePreDelay[MAXPLAYERS+1], fVocalizePitch[MAXPLAYERS+1]; +Handle hSceneStageForward, hVocalizeCommandForward; + +ArrayList alVocalize; +ArrayStack asScene; + +enum struct SceneData +{ + SceneStages ssDataBit; + bool bInFakePostSpawn; + float fTimeStampData; + int iActorData; + int iInitiatorData; + char sFileData[MAX_SCENEFILE_LENGTH]; + char sVocalizeData[MAX_VOCALIZE_LENGTH]; + float fPreDelayData; + float fPitchData; +} + +SceneData nSceneData[2048]; +int iScenePlaying[MAXPLAYERS+1], iVocalizeTick[MAXPLAYERS+1], iVocalizeInitiator[MAXPLAYERS+1]; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + EngineVersion evGame = GetEngineVersion(); + if (evGame == Engine_Left4Dead) + { + bIsL4D = true; + } + else if (evGame != Engine_Left4Dead2) + { + strcopy(error, err_max, "[SP] Plugin Supports L4D And L4D2 Only!"); + return APLRes_Failure; + } + + CreateNative("GetSceneStage", SP_GetSceneStage); + CreateNative("GetSceneStartTimeStamp", SP_GetSceneStartTimeStamp); + CreateNative("GetActorFromScene", SP_GetSceneActor); + CreateNative("GetSceneFromActor", SP_GetActorScene); + CreateNative("GetSceneInitiator", SP_GetSceneInitiator); + CreateNative("GetSceneFile", SP_GetSceneFile); + CreateNative("GetSceneVocalize", SP_GetSceneVocalize); + CreateNative("GetScenePreDelay", SP_GetScenePreDelay); + CreateNative("SetScenePreDelay", SP_SetScenePreDelay); + CreateNative("GetScenePitch", SP_GetScenePitch); + CreateNative("SetScenePitch", SP_SetScenePitch); + CreateNative("CancelScene", SP_CancelScene); + CreateNative("PerformScene", SP_PerformScene); + CreateNative("PerformSceneEx", SP_PerformSceneEx); + + RegPluginLibrary("sceneprocessor"); + return APLRes_Success; +} + +public any SP_GetSceneStage(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return SceneStage_Unknown; + } + + int scene = GetNativeCell(1); + if (scene < 1 || scene > 2048 || !IsValidEntity(scene)) + { + return SceneStage_Unknown; + } + + return nSceneData[scene].ssDataBit; +} + +public any SP_GetSceneStartTimeStamp(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return 0.0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0.0; + } + + return nSceneData[scene].fTimeStampData; +} + +public int SP_GetActorScene(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return INVALID_ENT_REFERENCE; + } + + int iActor = GetNativeCell(1); + if (iActor < 1 || iActor > MaxClients || !IsClientInGame(iActor) || GetClientTeam(iActor) != 2 || !IsPlayerAlive(iActor)) + { + return INVALID_ENT_REFERENCE; + } + + return iScenePlaying[iActor]; +} + +public int SP_GetSceneActor(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return 0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0; + } + + return nSceneData[scene].iActorData; +} + +public int SP_GetSceneInitiator(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return 0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0; + } + + return nSceneData[scene].iInitiatorData; +} + +public int SP_GetSceneFile(Handle plugin, int numParams) +{ + if (numParams != 3) + { + return 0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0; + } + + int len = GetNativeCell(3); + + int bytesWritten; + SetNativeString(2, nSceneData[scene].sFileData, len, _, bytesWritten); + return bytesWritten; +} + +public int SP_GetSceneVocalize(Handle plugin, int numParams) +{ + if (numParams != 3) + { + return 0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0; + } + + int len = GetNativeCell(3); + + int bytesWritten; + SetNativeString(2, nSceneData[scene].sVocalizeData, len, _, bytesWritten); + return bytesWritten; +} + +public any SP_GetScenePreDelay(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return 0.0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0.0; + } + + return nSceneData[scene].fPreDelayData; +} + +public int SP_SetScenePreDelay(Handle plugin, int numParams) +{ + if (numParams != 2) + { + return; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return; + } + + float fPreDelay = GetNativeCell(2); + + SetEntPropFloat(scene, Prop_Data, "m_flPreDelay", fPreDelay); + nSceneData[scene].fPreDelayData = fPreDelay; +} + +public any SP_GetScenePitch(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return 0.0; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return 0.0; + } + + return nSceneData[scene].fPitchData; +} + +public int SP_SetScenePitch(Handle plugin, int numParams) +{ + if (numParams != 2) + { + return; + } + + int scene = GetNativeCell(1); + if (!IsValidScene(scene)) + { + return; + } + + float fPitch = GetNativeCell(2); + + SetEntPropFloat(scene, Prop_Data, "m_fPitch", fPitch); + nSceneData[scene].fPitchData = fPitch; +} + +public int SP_CancelScene(Handle plugin, int numParams) +{ + if (numParams == 0) + { + return; + } + + int scene = GetNativeCell(1); + if (scene < 1 || scene > 2048 || !IsValidEntity(scene)) + { + return; + } + + SceneStages ssBit = nSceneData[scene].ssDataBit; + if (ssBit == SceneStage_Unknown) + { + return; + } + else if (ssBit == SceneStage_Started || (ssBit == SceneStage_SpawnedPost && nSceneData[scene].bInFakePostSpawn)) + { + AcceptEntityInput(scene, "Cancel"); + } + else if (ssBit != SceneStage_Cancelled && ssBit != SceneStage_Completion && ssBit != SceneStage_Killed) + { + AcceptEntityInput(scene, "Kill"); + } +} + +public int SP_PerformScene(Handle plugin, int numParams) +{ + if (numParams < 2) + { + return; + } + + int client = GetNativeCell(1); + + if (client < 1 || client > MaxClients || !IsClientInGame(client) || GetClientTeam(client) != 2 || !IsPlayerAlive(client)) + { + return; + } + + static char sVocalize[MAX_VOCALIZE_LENGTH], sFile[MAX_SCENEFILE_LENGTH]; + float fPreDelay = DEFAULT_SCENE_PREDELAY, fPitch = DEFAULT_SCENE_PITCH; + int iInitiator = SCENE_INITIATOR_PLUGIN; + + if (GetNativeString(2, sVocalize, MAX_VOCALIZE_LENGTH) != SP_ERROR_NONE) + { + ThrowNativeError(SP_ERROR_NATIVE, "Unknown Vocalize Parameter!"); + return; + } + + if (numParams >= 3) + { + if (GetNativeString(3, sFile, MAX_SCENEFILE_LENGTH) != SP_ERROR_NONE) + { + ThrowNativeError(SP_ERROR_NATIVE, "Unknown File Parameter!"); + return; + } + } + + if (numParams >= 4) + { + fPreDelay = GetNativeCell(4); + } + + if (numParams >= 5) + { + fPitch = GetNativeCell(5); + } + + if (numParams >= 6) + { + iInitiator = GetNativeCell(6); + } + + Scene_Perform(client, sVocalize, sFile, fPreDelay, fPitch, iInitiator); +} + +public int SP_PerformSceneEx(Handle plugin, int numParams) +{ + if (numParams < 2) + { + return; + } + + int client = GetNativeCell(1); + if (client < 1 || client > MaxClients || !IsClientInGame(client) || GetClientTeam(client) != 2 || !IsPlayerAlive(client)) + { + return; + } + + static char sVocalize[MAX_VOCALIZE_LENGTH], sFile[MAX_SCENEFILE_LENGTH]; + float fPreDelay = DEFAULT_SCENE_PREDELAY, fPitch = DEFAULT_SCENE_PITCH; + int iInitiator = SCENE_INITIATOR_PLUGIN; + + if (GetNativeString(2, sVocalize, MAX_VOCALIZE_LENGTH) != SP_ERROR_NONE) + { + ThrowNativeError(SP_ERROR_NATIVE, "Unknown Vocalize Parameter!"); + return; + } + + if (numParams >= 3) + { + if (GetNativeString(3, sFile, MAX_SCENEFILE_LENGTH) != SP_ERROR_NONE) + { + ThrowNativeError(SP_ERROR_NATIVE, "Unknown File Parameter!"); + return; + } + } + + if (numParams >= 4) + { + fPreDelay = GetNativeCell(4); + } + + if (numParams >= 5) + { + fPitch = GetNativeCell(5); + } + + if (numParams >= 6) + { + iInitiator = GetNativeCell(6); + } + + Scene_Perform(client, sVocalize, sFile, fPreDelay, fPitch, iInitiator, true); +} + +public Plugin myinfo = +{ + name = "Scene Processor", + author = "Buster \"Mr. Zero\" Nielsen (Fork by cravenge & Dragokas)", + description = "Provides Forwards and Natives For Scenes' Manipulation.", + version = PLUGIN_VERSION, + url = "https://forums.alliedmods.net/showthread.php?t=241585" +}; + +public void OnPluginStart() +{ + hSceneStageForward = CreateGlobalForward("OnSceneStageChanged", ET_Ignore, Param_Cell, Param_Cell); + hVocalizeCommandForward = CreateGlobalForward("OnVocalizeCommand", ET_Hook, Param_Cell, Param_String, Param_Cell); + + CreateConVar("sceneprocessor_version", PLUGIN_VERSION, "Scene Processor Version", FCVAR_SPONLY|FCVAR_NOTIFY|FCVAR_DONTRECORD); + if (!bIsL4D) + { + ConVar spJailbreakVocalize = CreateConVar("sceneprocessor_jailbreak_vocalize", "1", "Enable/Disable Jailbreak Vocalizations", FCVAR_SPONLY|FCVAR_NOTIFY); + spJailbreakVocalize.AddChangeHook(OnSPCVarChanged); + bJailbreakVocalize = spJailbreakVocalize.BoolValue; + } + + AddCommandListener(OnVocalizeCmd, "vocalize"); + + asScene = new ArrayStack(); + alVocalize = new ArrayList(MAX_VOCALIZE_LENGTH); + + for (int i = 1; i < 2049; i++) + { + if (IsValidEntity(i) && IsValidEdict(i)) + { + SceneData_SetStage(i, SceneStage_Unknown); + } + } + + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i)) + { + ResetClientVocalizeData(i); + } + } +} + +public void OnSPCVarChanged(ConVar cvar, const char[] sOldValue, const char[] sNewValue) +{ + bJailbreakVocalize = cvar.BoolValue; +} + +public Action OnVocalizeCmd(int client, const char[] command, int args) +{ + if (client == 0 || args == 0) + { + return Plugin_Continue; + } + + if (!IsClientInGame(client)) + { + return Plugin_Handled; + } + + static char sVocalize[128]; + GetCmdArg(1, sVocalize, sizeof(sVocalize)); + + if (!bIsL4D && args != 2) + { + if (bJailbreakVocalize) + { + JailbreakVocalize(client, sVocalize); + } + return Plugin_Handled; + } + + int iTick = GetGameTickCount(); + + if (!bSceneHasInitiator[client] || (iVocalizeTick[client] > 0 && iVocalizeTick[client] != iTick)) + { + iVocalizeInitiator[client] = client; + + if (!bIsL4D && args > 1 && StrEqual(sVocalize, "smartlook", false)) + { + static char sTime[32]; + GetCmdArg(2, sTime, sizeof(sTime)); + if (StrEqual(sTime, "auto", false)) + { + iVocalizeInitiator[client] = SCENE_INITIATOR_WORLD; + } + } + } + + strcopy(sVocalizeScene[client], MAX_VOCALIZE_LENGTH, sVocalize); + iVocalizeTick[client] = iTick; + + Action aResult = Plugin_Continue; + + Call_StartForward(hVocalizeCommandForward); + Call_PushCell(client); + Call_PushString(sVocalize); + Call_PushCell(iVocalizeInitiator[client]); + Call_Finish(aResult); + + return (aResult == Plugin_Stop) ? Plugin_Handled : Plugin_Continue; +} + +public void OnPluginEnd() +{ + RemoveCommandListener(OnVocalizeCmd, "vocalize"); +} + +public void OnMapStart() +{ + iSkippedFrames = 0; + fStartTimeStamp = GetGameTime(); +} + +public void OnEntityCreated(int entity, const char[] classname) +{ + if (entity < 1 || entity > 2048) + { + return; + } + + if (StrEqual(classname, "instanced_scripted_scene")) + { + SDKHook(entity, SDKHook_SpawnPost, OnSpawnPost); + SceneData_SetStage(entity, SceneStage_Created); + } +} + +public void OnSpawnPost(int entity) +{ + int iActor = GetEntPropEnt(entity, Prop_Data, "m_hOwner"); + nSceneData[entity].iActorData = iActor; + + static char sFile[MAX_SCENEFILE_LENGTH]; + GetEntPropString(entity, Prop_Data, "m_iszSceneFile", sFile, MAX_SCENEFILE_LENGTH); + + strcopy(nSceneData[entity].sFileData, MAX_SCENEFILE_LENGTH, sFile); + nSceneData[entity].fPitchData = GetEntPropFloat(entity, Prop_Data, "m_fPitch"); + + if (iActor > 0 && iActor <= MaxClients && IsClientInGame(iActor)) + { + if (iVocalizeTick[iActor] == GetGameTickCount()) + { + strcopy(nSceneData[entity].sVocalizeData, MAX_VOCALIZE_LENGTH, sVocalizeScene[iActor]); + + nSceneData[entity].iInitiatorData = iVocalizeInitiator[iActor]; + nSceneData[entity].fPreDelayData = fVocalizePreDelay[iActor]; + nSceneData[entity].fPitchData = fVocalizePitch[iActor]; + } + ResetClientVocalizeData(iActor); + } + + SetEntPropFloat(entity, Prop_Data, "m_fPitch", nSceneData[entity].fPitchData); + SetEntPropFloat(entity, Prop_Data, "m_flPreDelay", nSceneData[entity].fPreDelayData); + + asScene.Push(entity); + bScenesUnprocessed = true; + + HookSingleEntityOutput(entity, "OnStart", OnSceneStart_EntOutput); + HookSingleEntityOutput(entity, "OnCanceled", OnSceneCanceled_EntOutput); + + SceneData_SetStage(entity, SceneStage_Spawned); +} + +public void OnSceneStart_EntOutput(const char[] output, int caller, int activator, float delay) +{ + if (caller < 1 || caller > 2048 || !IsValidEntity(caller)) + { + return; + } + + static char sFile[MAX_SCENEFILE_LENGTH]; + strcopy(sFile, MAX_SCENEFILE_LENGTH, nSceneData[caller].sFileData); + if (!sFile[0]) + { + return; + } + + nSceneData[caller].fTimeStampData = GetEngineTime(); + + if (nSceneData[caller].ssDataBit == SceneStage_Spawned) + { + nSceneData[caller].bInFakePostSpawn = true; + SceneData_SetStage(caller, SceneStage_SpawnedPost); + } + + if (nSceneData[caller].ssDataBit == SceneStage_SpawnedPost) + { + int iActor = nSceneData[caller].iActorData; + if (iActor > 0 && iActor <= MaxClients && IsClientInGame(iActor)) + { + iScenePlaying[iActor] = caller; + } + SceneData_SetStage(caller, SceneStage_Started); + } +} + +public void OnSceneCanceled_EntOutput(const char[] output, int caller, int activator, float delay) +{ + if (caller < 1 || caller > 2048 || !IsValidEntity(caller)) + { + return; + } + + for (int i = 1; i <= MaxClients; i++) + { + if (iScenePlaying[i] == caller) + { + iScenePlaying[i] = INVALID_ENT_REFERENCE; + break; + } + } + + SceneData_SetStage(caller, SceneStage_Cancelled); +} + +public void OnEntityDestroyed(int entity) +{ + if (entity < 1 || entity > 2048 || !IsValidEdict(entity)) + { + return; + } + + static char sEntityClass[64]; + GetEdictClassname(entity, sEntityClass, sizeof(sEntityClass)); + if (!StrEqual(sEntityClass, "instanced_scripted_scene")) + { + return; + } + + SDKUnhook(entity, SDKHook_SpawnPost, OnSpawnPost); + + SceneStages ssBit = nSceneData[entity].ssDataBit; + if (ssBit != SceneStage_Unknown) + { + if (ssBit == SceneStage_Started) + { + SceneData_SetStage(entity, SceneStage_Completion); + } + SceneData_SetStage(entity, SceneStage_Killed); + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i) || iScenePlaying[i] != entity) + { + continue; + } + + iScenePlaying[i] = INVALID_ENT_REFERENCE; + break; + } + } + + SceneData_SetStage(entity, SceneStage_Unknown); +} + +public void OnClientDisconnect(int client) +{ + if (client == 0) + { + return; + } + + iScenePlaying[client] = INVALID_ENT_REFERENCE; +} + +public void OnGameFrame() +{ + iSkippedFrames += 1; + if (iSkippedFrames < 3) + { + return; + } + + iSkippedFrames = 1; + if (bScenesUnprocessed) + { + bScenesUnprocessed = false; + + int dScene; + while (!asScene.Empty) + { + asScene.Pop(dScene); + if (dScene < 1 || dScene > 2048 || !IsValidEntity(dScene)) + { + continue; + } + + if (nSceneData[dScene].ssDataBit != SceneStage_Spawned) + { + continue; + } + + nSceneData[dScene].fPreDelayData = GetEntPropFloat(dScene, Prop_Data, "m_flPreDelay"); + nSceneData[dScene].bInFakePostSpawn = false; + + SceneData_SetStage(dScene, SceneStage_SpawnedPost); + } + } + + if (bUnvocalizedCommands) + { + int iArraySize = alVocalize.Length, + iCurrentTick = GetGameTickCount(); + + static char sVocalize[MAX_VOCALIZE_LENGTH]; + float fPreDelay, fPitch; + int client, dInitiator, dTick; + + for (int i = 0; i < iArraySize; i += 6) + { + dTick = alVocalize.Get(i + 5); + if (iCurrentTick != dTick) + { + continue; + } + + client = alVocalize.Get(i + 0); + alVocalize.GetString(i + 1, sVocalize, MAX_VOCALIZE_LENGTH); + fPreDelay = view_as(alVocalize.Get(i + 2)); + fPitch = view_as(alVocalize.Get(i + 3)); + dInitiator = alVocalize.Get(i + 4); + + Scene_Perform(client, sVocalize, _, fPreDelay, fPitch, dInitiator, true); + + for (int j = 0; j < 6; j++) + { + alVocalize.Erase(i); + iArraySize -= 1; + } + } + if (iArraySize < 1) + { + alVocalize.Clear(); + bUnvocalizedCommands = false; + } + } +} + +public void OnMapEnd() +{ + iSkippedFrames = 0; + + bScenesUnprocessed = false; + bUnvocalizedCommands = false; + + while (!asScene.Empty) + { + PopStack(asScene); + } + alVocalize.Clear(); + + for (int i = 1; i < 2049; i++) + { + if (IsValidEntity(i) && IsValidEdict(i)) + { + SceneData_SetStage(i, SceneStage_Unknown); + } + } + + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i)) + { + iScenePlaying[i] = INVALID_ENT_REFERENCE; + } + } +} + +void ResetClientVocalizeData(int client) +{ + iVocalizeTick[client] = 0; + sVocalizeScene[client] = "\0"; + bSceneHasInitiator[client] = false; + iVocalizeInitiator[client] = SCENE_INITIATOR_WORLD; + fVocalizePreDelay[client] = DEFAULT_SCENE_PREDELAY; + fVocalizePitch[client] = DEFAULT_SCENE_PITCH; +} + +void SceneData_SetStage(int scene, SceneStages stage) +{ + nSceneData[scene].ssDataBit = stage; + + if (stage != SceneStage_Unknown) + { + Call_StartForward(hSceneStageForward); + Call_PushCell(scene); + Call_PushCell(stage); + Call_Finish(); + } + else + { + nSceneData[scene].bInFakePostSpawn = false; + nSceneData[scene].fTimeStampData = 0.0; + nSceneData[scene].iActorData = 0; + nSceneData[scene].iInitiatorData = 0; + strcopy(nSceneData[scene].sFileData, MAX_SCENEFILE_LENGTH, "\0"); + strcopy(nSceneData[scene].sVocalizeData, MAX_VOCALIZE_LENGTH, "\0"); + nSceneData[scene].fPreDelayData = DEFAULT_SCENE_PREDELAY; + nSceneData[scene].fPitchData = DEFAULT_SCENE_PITCH; + } +} + +void Scene_Perform(int client, const char[] sVocalizeParam, const char[] sFileParam = "", float fScenePreDelay = DEFAULT_SCENE_PREDELAY, float fScenePitch = DEFAULT_SCENE_PITCH, int iSceneInitiator = SCENE_INITIATOR_PLUGIN, bool bVocalizeNow = false) +{ + if (sFileParam[0] && FileExists(sFileParam, true)) + { + int iScene = CreateEntityByName("instanced_scripted_scene"); + DispatchKeyValue(iScene, "SceneFile", sFileParam); + + SetEntPropEnt(iScene, Prop_Data, "m_hOwner", client); + nSceneData[iScene].iActorData = client; + SetEntPropFloat(iScene, Prop_Data, "m_flPreDelay", fScenePreDelay); + nSceneData[iScene].fPreDelayData = fScenePreDelay; + SetEntPropFloat(iScene, Prop_Data, "m_fPitch", fScenePitch); + nSceneData[iScene].fPitchData = fScenePitch; + + nSceneData[iScene].iInitiatorData = iSceneInitiator; + strcopy(nSceneData[iScene].sVocalizeData, MAX_VOCALIZE_LENGTH, sVocalizeParam); + + DispatchSpawn(iScene); + ActivateEntity(iScene); + + AcceptEntityInput(iScene, "Start", client, client); + } + else if (sVocalizeParam[0]) + { + if (bVocalizeNow) + { + iVocalizeInitiator[client] = iSceneInitiator; + bSceneHasInitiator[client] = true; + fVocalizePreDelay[client] = fScenePreDelay; + fVocalizePitch[client] = fScenePitch; + + if (bIsL4D) + { + FakeClientCommandEx(client, "vocalize %s", sVocalizeParam); + } + else + { + JailbreakVocalize(client, sVocalizeParam); + } + } + else + { + alVocalize.Push(client); + alVocalize.PushString(sVocalizeParam); + alVocalize.Push(fScenePreDelay); + alVocalize.Push(fScenePitch); + alVocalize.Push(iSceneInitiator); + alVocalize.Push(GetGameTickCount() + 10 - 1); + + bUnvocalizedCommands = true; + } + } +} + +void JailbreakVocalize(int client, const char[] sVocalize) +{ + char sBuffer[2][32]; + FloatToString((GetGameTime() - fStartTimeStamp) + 2.0, sBuffer[0], 32); + ExplodeString(sBuffer[0], ".", sBuffer, 2, 32); + + Format(sBuffer[1], 2, "%s\0", sBuffer[1][0]); + FakeClientCommandEx(client, "vocalize %s #%s%s", sVocalize, sBuffer[0], sBuffer[1]); +} diff --git a/scripting/sm_namespamblock.sp b/scripting/sm_namespamblock.sp new file mode 100644 index 0000000..b9e7721 --- /dev/null +++ b/scripting/sm_namespamblock.sp @@ -0,0 +1,107 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" + +#include +#include +//#include + +#define MIN_TIME_BETWEEN_NAME_CHANGES 10000 // In seconds +#define MAX_NAME_COUNT 3 // How many changes max within a MIN_TIME_BETWEEN_NAME_CHANGES + +public Plugin myinfo = +{ + name = "Name change Block", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +public void OnPluginStart() { + HookEvent("player_info", Event_PlayerInfo); + RegAdminCmd("status2", Cmd_Status2, ADMFLAG_GENERIC); + RegAdminCmd("sm_status2", Cmd_Status2, ADMFLAG_GENERIC); +} + +char firstName[64][MAXPLAYERS+1]; +int joinTime[MAXPLAYERS+1]; + +public Action Cmd_Status2(int client, int args) { + ArrayList players = new ArrayList(); + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i) && GetUserAdmin(i) == INVALID_ADMIN_ID) { + players.Push(i); + } + } + players.SortCustom(Sort_Players); + char buffer[64], steamid[32]; + ReplyToCommand(client, "Index\tUserid\tName\tSteamID"); + for(int i = 0; i < players.Length; i++) { + int player = players.Get(i); + GetClientAuthId(player, AuthId_Steam2, steamid, sizeof(steamid)); + GetClientName(player, buffer, sizeof(buffer)); + if(StrEqual(buffer, firstName[player])) + ReplyToCommand(client, "%d.\t#%d\t%s\t%s", player, GetClientUserId(player), buffer, steamid); + else + ReplyToCommand(client, "%d.\t#%d\t%s\t%s (formely %s)", player, GetClientUserId(player), buffer, steamid, firstName[player]); + } + ReplySource src = GetCmdReplySource(); + if(src == SM_REPLY_TO_CONSOLE) + ReplyToCommand(client, "You can ban players by using their userid or steamid with #. \"sm_ban #52 0\" or \"sm_ban #STEAM_1:1:5325325 0\""); + else + ReplyToCommand(client, "You can ban players by using their userid or steamid with #. \"/ban #52 0\" or \"/ban #STEAM_1:1:5325325 0\""); + return Plugin_Handled; +} + +public int Sort_Players(int index1, int index2, ArrayList array, Handle hndl) { + return joinTime[index2] - joinTime[index1]; +} + +static int lastNameChange[MAXPLAYERS+1]; +static int nameChangeCount[MAXPLAYERS+1]; + +public void Event_PlayerInfo(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client && !IsFakeClient(client) && GetUserAdmin(client) == INVALID_ADMIN_ID) { + ++nameChangeCount[client]; + int time = GetTime(); + int diff = time - lastNameChange[client]; + if(diff < MIN_TIME_BETWEEN_NAME_CHANGES && nameChangeCount[client] > MAX_NAME_COUNT) { + char buffer[64]; + Format(buffer, sizeof(buffer), "Excessive name changing (%d in %d seconds)", nameChangeCount[client], diff); + BanClient(client, 20, BANFLAG_AUTO, "Excessive name changing", buffer); + GetClientAuthId(client, AuthId_Steam2, buffer, sizeof(buffer)); + PrintChatToAdmins("%N (steamid %s) hit excessive name change and has been banned temporarily", client, buffer); + } + lastNameChange[client] = time; + } +} + +stock void PrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToChat(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} + + +public void OnClientConnected(int client) { + lastNameChange[client] = 0; + nameChangeCount[client] = 0; + firstName[client][0] = '\0'; + if(!IsFakeClient(client)) { + joinTime[client] = GetTime(); + GetClientName(client, firstName[client], 64 ); + } +} diff --git a/scripting/sm_player_notes.sp b/scripting/sm_player_notes.sp new file mode 100644 index 0000000..4e3084b --- /dev/null +++ b/scripting/sm_player_notes.sp @@ -0,0 +1,628 @@ +#pragma semicolon 1 +#pragma newdecls required + +//#define DEBUG + +#define PLUGIN_VERSION "1.0" +#define MAX_PLAYER_HISTORY 25 +#define MAX_NOTES_TO_SHOW 4 +#define DATABASE_CONFIG_NAME "stats" + +#include +#include +#include +// Addons: +#tryinclude +#tryinclude + +public Plugin myinfo = +{ + name = "Player Notes", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "https://github.com/Jackzmc/sourcemod-plugins" +}; + +static Database DB; +static char query[1024]; +static char reason[256]; +static int WaitingForNotePlayer; +static char menuNoteTarget[32]; +static char menuNoteTargetName[32]; + +enum struct PlayerData { + char id[32]; + char name[32]; +} + +static ArrayList lastPlayers; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + CreateNative("AddPlayerNoteIdentity", Native_AddNoteIdentity); + return APLRes_Success; +} + +public void OnPluginStart() { + if(!SQL_CheckConfig(DATABASE_CONFIG_NAME)) { + SetFailState("No database entry for %s; no database to connect to.", DATABASE_CONFIG_NAME); + } + if(!ConnectDB()) { + SetFailState("Failed to connect to database."); + } + + LoadTranslations("common.phrases"); + + lastPlayers = new ArrayList(sizeof(PlayerData)); + + HookEvent("player_disconnect", Event_PlayerDisconnect); + HookEvent("player_first_spawn", Event_FirstSpawn); + + RegConsoleCmd("sm_rep", Command_RepPlayer, "+rep or -rep a player"); + RegAdminCmd("sm_note", Command_AddNote, ADMFLAG_KICK, "Add a note to a player"); + RegAdminCmd("sm_notes", Command_ListNotes, ADMFLAG_KICK, "List notes for a player"); + RegAdminCmd("sm_notedisconnected", Command_AddNoteDisconnected, ADMFLAG_KICK, "Add a note to any disconnected players"); + + // PrintToServer("Parse Test #1"); + // ParseActions(0, "!fta:Slow_Speed:16"); + // PrintToServer(""); + + // PrintToServer("Parse Test #2"); + // ParseActions(0, "SPACE !testSPACE:val1:val2"); + // PrintToServer(""); + + // PrintToServer("Parse Test #3"); + // ParseActions(0, "donotfire"); + // PrintToServer(""); +} + +void ShowRepMenu(int client, int targetUserid) { + Menu menu = new Menu(RepFinalHandler); + menu.SetTitle("Choose a rating"); + char id[16]; + Format(id, sizeof(id), "%d|1", targetUserid); + menu.AddItem(id, "+Rep"); + Format(id, sizeof(id), "%d|-1", targetUserid); + menu.AddItem(id, "-Rep"); + menu.Display(client, 0); +} + +public int RepPlayerHandler(Menu menu, MenuAction action, int param1, int param2) { + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) { + static char info[8]; + menu.GetItem(param2, info, sizeof(info)); + int targetUserid = StringToInt(info); + int target = GetClientOfUserId(targetUserid); + + if(target == 0) { + ReplyToCommand(param1, "Could not acquire player"); + return 0; + } + + ShowRepMenu(param1, targetUserid); + } else if (action == MenuAction_End) { + delete menu; + } + return 0; +} + +public int RepFinalHandler(Menu menu, MenuAction action, int param1, int param2) { + /* If an option was selected, tell the client about the item. */ + if (action == MenuAction_Select) { + char info[16]; + menu.GetItem(param2, info, sizeof(info)); + char str[2][8]; + ExplodeString(info, "|", str, 2, 8, false); + int targetUserid = StringToInt(str[0]); + int target = GetClientOfUserId(targetUserid); + int rep = StringToInt(str[1]); + + if(target == 0) { + ReplyToCommand(param1, "Could not acquire player"); + return 0; + } + + ApplyRep(param1, target, rep); + } else if (action == MenuAction_End) { + delete menu; + } + return 0; +} + +public Action Command_RepPlayer(int client, int args) { + if(client == 0) { + ReplyToCommand(client, "You must be a player to use this command."); + return Plugin_Handled; + } + if(args == 0) { + Menu menu = new Menu(RepPlayerHandler); + menu.SetTitle("Choose a player to rep"); + char id[8], display[64]; + // int clientTeam = GetClientTeam(client); + for(int i = 1; i <= MaxClients; i++) { + if(i != client && IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i)) { + Format(id, sizeof(id), "%d", GetClientUserId(i)); + Format(display, sizeof(display), "%N", i); + menu.AddItem(id, display); + } + } + menu.Display(client, 0); + return Plugin_Handled; + } else if(args > 0) { + char arg1[32]; + GetCmdArg(1, arg1, sizeof(arg1)); + char target_name[MAX_TARGET_LENGTH]; + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + arg1, + client, + target_list, + 1, + COMMAND_FILTER_ALIVE, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0) + { + /* This function replies to the admin with a failure message */ + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + if (args == 1) { + ShowRepMenu(client, GetClientUserId(target_list[0])); + } else { + char arg2[2]; + GetCmdArg(2, arg2, sizeof(arg2)); + int rep; + if(arg2[0] == 'y' || arg2[0] == '+' || arg2[0] == 'p') { + rep = 1; + } else if(arg2[0] == 'n' || arg2[0] == '-' || arg2[0] == 's') { + rep = -1; + } else { + ReplyToCommand(client, "Invalid rep value: Use (y/+/p) for +rep or (n/-/s) for -rep"); + return Plugin_Handled; + } + ApplyRep(client, target_list[0], rep); + } + } + return Plugin_Handled; +} + +void ApplyRep(int client, int target, int rep) { + char[] msg = "+rep"; + if(rep == -1) msg[0] = '-'; + + LogAction(client, target, "\"%L\" %srep \"%L\"", client, msg, target); + if(rep > 0) + CShowActivity(client, "{green}+rep %N", target); + else + CShowActivity(client, "{yellow}-rep %N", target); + + char activatorId[32], targetId[32]; + GetClientAuthId(client, AuthId_Steam2, activatorId, sizeof(activatorId)); + GetClientAuthId(target, AuthId_Steam2, targetId, sizeof(targetId)); + AddNoteIdentity(activatorId, targetId, msg); +} + +public Action Command_AddNoteDisconnected(int client, int args) { + if(lastPlayers.Length == 0) { + ReplyToCommand(client, "No disconnected players recorded."); + return Plugin_Handled; + } + Menu menu = new Menu(Menu_Disconnected); + menu.SetTitle("Add Note For Disconnected"); + for(int i = lastPlayers.Length - 1; i >= 0; i--) { + PlayerData data; + lastPlayers.GetArray(i, data, sizeof(data)); + menu.AddItem(data.id, data.name); + } + menu.Display(client, 0); + return Plugin_Handled; +} + +public int Menu_Disconnected(Menu menu, MenuAction action, int client, int item) { + if (action == MenuAction_Select) { + int style; + menu.GetItem(item, menuNoteTarget, sizeof(menuNoteTarget), style, menuNoteTargetName, sizeof(menuNoteTargetName)); + CPrintToChat(client, "Enter a note in the chat for {yellow}%s {olive}(%s){default}: (or 'cancel' to cancel)", menuNoteTargetName, menuNoteTarget); + WaitingForNotePlayer = client; + } else if (action == MenuAction_End) + delete menu; + return 0; +} + +public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) { + if(client > 0 && WaitingForNotePlayer == client) { + WaitingForNotePlayer = 0; + if(StrEqual(sArgs, "cancel", false)) { + PrintToChat(client, "Note cancelled."); + } else { + int size = strlen(sArgs) + 1; + char[] sArgsTrimmed = new char[size]; + strcopy(sArgsTrimmed, size, sArgs); + TrimString(sArgsTrimmed); + char buffer[32]; + GetClientAuthId(client, AuthId_Steam2, buffer, sizeof(buffer)); + DB.Format(query, sizeof(query), "INSERT INTO `notes` (steamid, markedBy, content) VALUES ('%s', '%s', '%s')", menuNoteTarget, buffer, sArgsTrimmed); + DB.Query(DB_AddNote, query); + LogAction(client, -1, "\"%L\" added note for \"%s\" (%s): \"%s\"", client, menuNoteTargetName, menuNoteTarget, sArgsTrimmed); + Format(buffer, sizeof(buffer), "%N: ", client); + CShowActivity2(client, buffer, "added a note for {green}%s: {default}\"%s\"", menuNoteTargetName, sArgsTrimmed); + } + return Plugin_Stop; + } + return Plugin_Continue; +} + +public Action Command_AddNote(int client, int args) { + if(args < 2) { + ReplyToCommand(client, "Syntax: sm_note \"your message here\" or if they left, use sm_notedisconnected"); + } else { + char target_name[MAX_TARGET_LENGTH]; + GetCmdArg(1, target_name, sizeof(target_name)); + GetCmdArg(2, reason, sizeof(reason)); + TrimString(reason); + if(args > 2) { + // Correct commands that don't wrap message in quotes + char buffer[64]; + for(int i = 3; i <= args; i++) { + GetCmdArg(i, buffer, sizeof(buffer)); + Format(reason, sizeof(reason), "%s %s", reason, buffer); + } + } + + if(reason[0] == '\0') { + ReplyToCommand(client, "Can't create an empty note"); + return Plugin_Handled; + } + + int target_list[1], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + target_name, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + if(target_count == COMMAND_TARGET_NONE) { + ReplyToCommand(client, "Could not find any online user. If user has disconnected, use sm_notedisconnected"); + } else { + ReplyToTargetError(client, target_count); + } + return Plugin_Handled; + } + if(args == 1) { + ReplyToCommand(client, "Enter the note for %N in the chat: (type 'cancel' to cancel)", target_list[0]); + WaitingForNotePlayer = client; + return Plugin_Handled; + } + char auth[32]; + GetClientAuthId(target_list[0], AuthId_Steam2, auth, sizeof(auth)); + char authMarker[32]; + if(client > 0) + GetClientAuthId(client, AuthId_Steam2, authMarker, sizeof(authMarker)); + DB.Format(query, sizeof(query), "INSERT INTO `notes` (steamid, markedBy, content) VALUES ('%s', '%s', '%s')", auth, authMarker, reason); + DB.Query(DB_AddNote, query); + LogAction(client, target_list[0], "\"%L\" added note for \"%L\": \"%s\"", client, target_list[0], reason); + CShowActivity(client, "added a note for {green}%N: {default}\"%s\"", target_list[0], reason); + } + return Plugin_Handled; +} + +public Action Command_ListNotes(int client, int args) { + if(args < 1) { + ReplyToCommand(client, "Syntax: sm_notes "); + } else { + char target_name[MAX_TARGET_LENGTH]; + GetCmdArg(1, target_name, sizeof(target_name)); + GetCmdArg(2, reason, sizeof(reason)); + + int target_list[MAXPLAYERS], target_count; + bool tn_is_ml; + if ((target_count = ProcessTargetString( + target_name, + client, + target_list, + 1, + COMMAND_FILTER_NO_MULTI | COMMAND_FILTER_NO_IMMUNITY, + target_name, + sizeof(target_name), + tn_is_ml)) <= 0 + ) { + ReplyToTargetError(client, target_count); + return Plugin_Handled; + } + char auth[32]; + GetClientAuthId(target_list[0], AuthId_Steam2, auth, sizeof(auth)); + + DB.Format(query, sizeof(query), "SELECT notes.content, stats_users.last_alias FROM `notes` JOIN stats_users ON markedBy = stats_users.steamid WHERE notes.`steamid` = '%s' ORDER BY id DESC", auth); + ReplyToCommand(client, "Fetching notes..."); + DataPack pack = new DataPack(); + pack.WriteCell(GetClientUserId(client)); + pack.WriteCell(GetClientUserId(target_list[0])); + pack.WriteString(auth); + DB.Query(DB_ListNotesForPlayer, query, pack); + } + return Plugin_Handled; +} + +bool ConnectDB() { + char error[255]; + DB = SQL_Connect(DATABASE_CONFIG_NAME, true, error, sizeof(error)); + if (DB== null) { + LogError("Database error %s", error); + delete DB; + return false; + } else { + PrintToServer("Connected to database %s", DATABASE_CONFIG_NAME); + SQL_LockDatabase(DB); + SQL_FastQuery(DB, "SET NAMES \"UTF8mb4\""); + SQL_UnlockDatabase(DB); + DB.SetCharset("utf8mb4"); + return true; + } +} + +public void Event_FirstSpawn(Event event, const char[] name, bool dontBroadcast) { + int client = GetClientOfUserId(event.GetInt("userid")); + if(client > 0 && client <= MaxClients && !IsFakeClient(client)) { + static char auth[32]; + GetClientAuthId(client, AuthId_Steam2, auth, sizeof(auth)); + DB.Format(query, sizeof(query), "SELECT notes.content, stats_users.last_alias, markedBy FROM `notes` JOIN stats_users ON markedBy = stats_users.steamid WHERE notes.`steamid` = '%s' ORDER BY id DESC", auth); + DB.Query(DB_FindNotes, query, GetClientUserId(client)); + } +} + +public void Event_PlayerDisconnect(Event event, const char[] name, bool dontBroadcast) { + if(!event.GetBool("bot")) { + PlayerData data; + event.GetString("networkid", data.id, sizeof(data.id)); + if(!StrEqual(data.id, "BOT")) { + if(!IsPlayerInHistory(data.id)) { + event.GetString("name", data.name, sizeof(data.name)); + lastPlayers.PushArray(data); + if(lastPlayers.Length > MAX_PLAYER_HISTORY) { + lastPlayers.Erase(0); + } + } + } + } +} + +bool IsPlayerInHistory(const char[] id) { + static PlayerData data; + for(int i = 0; i < lastPlayers.Length; i++) { + lastPlayers.GetArray(i, data, sizeof(data)); + if(StrEqual(data.id, id)) + return true; + } + return false; +} + +public void DB_FindNotes(Database db, DBResultSet results, const char[] error, any data) { + if(db == null || results == null) { + LogError("DB_FindNotes returned error: %s", error); + return; + } + //initialize variables + int client = GetClientOfUserId(data); + if(client > 0 && results.RowCount > 0) { + static char noteCreator[32]; + CPrintChatToAdmins("{yellow}> Notes for %N", client); + int actions = 0; + int repP = 0, repN = 0; + int count = 0; + while(results.FetchRow()) { + count++; + DBResult result; + results.FetchString(0, reason, sizeof(reason)); + results.FetchString(1, noteCreator, sizeof(noteCreator), result); + if(result == DBVal_Null) { + // No name for admin, get the raw id: + results.FetchString(2, noteCreator, sizeof(noteCreator), result); + } + TrimString(reason); + if(ParseActions(data, reason)) { + actions++; + } else if(StrEqual(reason, "+rep")) { + repP++; + } else if(StrEqual(reason, "-rep")) { + repN++; + } else if(count < MAX_NOTES_TO_SHOW) { + CPrintChatToAdmins(" {olive}%s: {default}%s", noteCreator, reason); + } + } + if(count >= MAX_NOTES_TO_SHOW) { + CPrintChatToAdmins(" ... and {olive}%d more", count - MAX_NOTES_TO_SHOW); + } + + if(actions > 0) { + CPrintChatToAdmins(" > {olive}%d Auto Actions Applied", actions); + } + if(repP > 0 || repN > 0) { + CPrintChatToAdmins(" > {olive}%d +rep\t{yellow}%d-rep", repP, repN); + } + } +} + +#define ACTION_DESTINATOR '@' +#define ACTION_SEPERATOR "." +bool ParseActions(int userid, const char[] input) { + if(input[0] != ACTION_DESTINATOR) return false; + + char piece[64], key[32], value[16]; + // int prevIndex, index; + // Incase there is no space, have piece be filled in as input + strcopy(piece, sizeof(piece), input); + // Loop through all spaces + // do { + // prevIndex += index; + // If piece contains !flag, parse !flag:value + int keyIndex = StrContains(piece, ACTION_SEPERATOR); + if(keyIndex > -1) { + strcopy(key, sizeof(key), piece[keyIndex + 1]); + piece[keyIndex] = '\0'; + } else { + // Ignore empty actions + if(piece[1] == '\0') return false; + key[0] = '\0'; + value[0] = '\0'; + } + + int valueIndex = StrContains(key, ACTION_SEPERATOR); + if(valueIndex > -1) { + strcopy(value, sizeof(value), key[valueIndex + 1]); + key[valueIndex] = '\0'; + } else { + value[0] = '\0'; + } + + ApplyAction(userid, piece[1], key, value); + // } while((index = SplitString(input[prevIndex], " ", piece, sizeof(piece))) != -1); + + return true; +} + +bool ApplyAction(int targetUserId, const char[] action, const char[] key, const char[] value) { + // If action is 'fta*' or 'ftas' + int target = GetClientOfUserId(targetUserId); + if(target == 0) return false; + LogAction(-1, target, "activating automatic action on \"%L\": @%s.%s.%s", target, action, key, value); + if(StrContains(action, "fta") > -1) { + #if defined _ftt_included_ + // Replace under scores with spaces + char newKey[32]; + strcopy(newKey, sizeof(newKey), key); + ReplaceString(newKey, sizeof(newKey), "_", " ", true); + int flags = StringToInt(value); + + + // ApplyTroll(int victim, const char[] name, TrollModifier modifier = TrollMod_Invalid, int flags, int activator, bool silent = false); + ApplyTroll(target, newKey, TrollMod_Invalid, flags, 0, true); + #else + PrintToServer("[PlayerNotes] Warn: Action \"%s\" for %N has missing plugin: Feed The Trolls", action, target); + return false; + #endif + } else if(strncmp(action, "ignore", 6) == 0) { + #if defined _tkstopper_included_ + if(StrEqual(key, "rff")) { + SetImmunity(target, TKImmune_ReverseFriendlyFire, true); + } else if(StrEqual(key, "tk")) { + SetImmunity(target, TKImmune_Teamkill, true); + } else { + PrintToServer("[PlayerNotes] Warn: Unknown ignore type \"%s\" for TKStopper", key, target); + } + #else + PrintToServer("[PlayerNotes] Warn: Action \"%s\" for %N has missing plugin: TKStopper", action, target); + return false; + #endif + } else if(strncmp(action, "slap", 4) == 0) { + float delay = StringToFloat(key); + CreateTimer(delay, Timer_SlapPlayer, targetUserId); + } else { + PrintToServer("[PlayerNotes] Warn: Action (\"%s\") for %N is not valid", action, target); + return false; + } + + return true; +} + +Action Timer_SlapPlayer(Handle h, int userid) { + int client = GetClientOfUserId(userid); + if(client > 0 && IsClientInGame(client)) { + SlapPlayer(client, 0, true); + } + return Plugin_Handled; +} + +public void DB_ListNotesForPlayer(Database db, DBResultSet results, const char[] error, DataPack pack) { + if(db == null || results == null) { + LogError("DB_ListNotesForPlayer returned error: %s", error); + return; + } + //initialize variables + static char auth[32]; + pack.Reset(); + int client = GetClientOfUserId(pack.ReadCell()); + int target = GetClientOfUserId(pack.ReadCell()); + pack.ReadString(auth, sizeof(auth)); + delete pack; + if(client > 0) { + if(target > 0) { + GetClientName(target, auth, sizeof(auth)); + } + if(results.RowCount > 0) { + CPrintToChat(client, "{green}> Notes for %s:", auth); + char noteCreator[32]; + while(results.FetchRow()) { + results.FetchString(0, reason, sizeof(reason)); + results.FetchString(1, noteCreator, sizeof(noteCreator)); + CPrintToChat(client, " {olive}%s: {default}%s", noteCreator, reason); + } + + } else { + PrintToChat(client, "No notes found for %s", auth); + } + } +} + +public void DB_AddNote(Database db, DBResultSet results, const char[] error, any data) { + if(db == null || results == null) { + LogError("DB_AddNote returned error: %s", error); + return; + } +} + +stock void PrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + PrintToChat(i, "%s", buffer); + } + } + } + PrintToServer("%s", buffer); +} + +stock void CPrintChatToAdmins(const char[] format, any ...) { + char buffer[254]; + VFormat(buffer, sizeof(buffer), format, 2); + for(int i = 1; i < MaxClients; i++) { + if(IsClientConnected(i) && IsClientInGame(i)) { + AdminId admin = GetUserAdmin(i); + if(admin != INVALID_ADMIN_ID) { + CPrintToChat(i, "%s", buffer); + } + } + } + CPrintToServer("%s", buffer); +} + +any Native_AddNoteIdentity(Handle plugin, int numParams) { + char noteCreator[32]; + char noteTarget[32]; + int length; + GetNativeStringLength(3, length); + char[] message = new char[length + 1]; + GetNativeString(1, noteCreator, sizeof(noteCreator)); + GetNativeString(2, noteTarget, sizeof(noteTarget)); + GetNativeString(3, message, length); + AddNoteIdentity(noteCreator, noteTarget, message); + return 0; +} + +void AddNoteIdentity(const char noteCreator[32], const char noteTarget[32], const char[] message) { + // messaege length + steamids (32 + 32 + null term) + // char[] query = new char[strlen(message) + 65]; + DB.Format(query, sizeof(query), "INSERT INTO `notes` (steamid, markedBy, content) VALUES ('%s', '%s', '%s')", noteTarget, noteCreator, message); + DB.Query(DB_AddNote, query); +} \ No newline at end of file diff --git a/scripting/sm_player_recorder.sp b/scripting/sm_player_recorder.sp new file mode 100644 index 0000000..b961cf9 --- /dev/null +++ b/scripting/sm_player_recorder.sp @@ -0,0 +1,136 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_AUTHOR "Jackz" +#define PLUGIN_VERSION "1.00" + +#define DATABASE_NAME "player-recorder" +#define RECORD_INTERVAL 60.0 + +#include +#include + +#pragma newdecls required + +public Plugin myinfo = { + name = "SRCDS Player Count Recorder", + author = PLUGIN_AUTHOR, + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +static Database g_db; +static char playerID[32]; + +enum struct PlayerData { + int timestamp; + int playerCount; +} + +static ArrayList g_playerData; +static int iLastCount; +static bool active; + +public void OnPluginStart() { + if(!SQL_CheckConfig(DATABASE_NAME)) { + SetFailState("No database entry for '" ... DATABASE_NAME ... "'; no database to connect to."); + } else if(!ConnectDB()) { + SetFailState("Failed to connect to database."); + } + + g_playerData = new ArrayList(sizeof(PlayerData)); + + + ConVar hPlayerCountID = CreateConVar("sm_playercount_id", "", "The ID to use for player count recording. Will not record if not set", FCVAR_NONE); + hPlayerCountID.GetString(playerID, sizeof(playerID)); + hPlayerCountID.AddChangeHook(Change_ID); + + if(strlen(playerID) > 0) { + Init(); + } +} + +void Init() { + HookEvent("player_first_spawn", Event_Connection, EventHookMode_PostNoCopy); + HookEvent("player_disconnect", Event_Connection, EventHookMode_PostNoCopy); + + CreateTimer(RECORD_INTERVAL, Timer_PushCounts, _, TIMER_REPEAT); + active = true; + PlayerData data; + data.timestamp = GetTime(); + data.playerCount = GetPlayerCount(); + g_playerData.PushArray(data); + + +} + +public void Change_ID(ConVar convar, const char[] oldValue, const char[] newValue) { + convar.GetString(playerID, sizeof(playerID)); + if(!active && strlen(playerID) > 0) { + Init(); + } +} + +bool ConnectDB() { + char error[255]; + g_db = SQL_Connect(DATABASE_NAME, true, error, sizeof(error)); + if (g_db == null) { + LogError("Database error %s", error); + delete g_db; + return false; + } else { + PrintToServer("[SPR] Connected to database \"" ... DATABASE_NAME ... "\""); + SQL_LockDatabase(g_db); + SQL_FastQuery(g_db, "SET NAMES \"UTF8mb4\""); + SQL_UnlockDatabase(g_db); + g_db.SetCharset("utf8mb4"); + + return true; + } +} + +public void Event_Connection(Event event, const char[] name, bool dontBroadcast) { + int count = GetPlayerCount(); + if(count != iLastCount) { + PlayerData data; + data.timestamp = GetTime(); + data.playerCount = count; + g_playerData.PushArray(data); + iLastCount = count; + } +} + +public Action Timer_PushCounts(Handle h) { + Transaction transact = new Transaction(); + static char query[255]; + static PlayerData data; + int length = g_playerData.Length; + for(int i = 0; i < length; i++) { + g_playerData.GetArray(i, data, sizeof(data)); + g_db.Format(query, sizeof(query), "INSERT INTO player_count (server_name, timestamp, count) VALUES ('%s', %d, %d)", + playerID, + data.timestamp, + data.playerCount + ); + transact.AddQuery(query); + } + g_playerData.Resize(g_playerData.Length - length); + g_db.Execute(transact, _, SQL_TransactionFailed, length, DBPrio_Low); + return Plugin_Continue; +} + +public void SQL_TransactionFailed(Database db, any data, int numQueries, const char[] error, int failIndex, any[] queryData) { + PrintToServer("[PlayerRecorder] Push failure: %s at query %d/%d", error, failIndex, numQueries); +} + +int GetPlayerCount() { + int count; + for(int i = 1; i <= MaxClients; i++) { + if(IsClientConnected(i) && !IsFakeClient(i)) { + count++; + } + } + return count; +} \ No newline at end of file diff --git a/scripting/spray_control.sp b/scripting/spray_control.sp new file mode 100644 index 0000000..509068e --- /dev/null +++ b/scripting/spray_control.sp @@ -0,0 +1,194 @@ +#pragma semicolon 1 + +#define DEBUG + +#define PLUGIN_VERSION "0.00" + +#define DB_NAME "sprayfiltercontrol" +#define DB_TABLE "spray_results" //not used + +// The minimum value for detection, number is related to value of RESULT_TEXT +#define ADULT_THRES 2 +#define RACY_THRES 2 + +#include +#include +#include + +#pragma newdecls required + +public Plugin myinfo = { + name = "Spay Filter Control", + author = "jackzmc", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +static Database g_db; +static char apikey[64]; +/* TODO: +1. Plugin start, fetch API key from keyvalue +2. On client connect, check database for spray result +3. Run system2 if no result +*/ +char RESULT_TEXT[6][] = { + "UNKNOWN", + "VERY UNLIKELY", + "UNLIKELY", + "POSSIBLE", + "LIKELY", + "VERY LIKELY" +}; + +enum Result { + UNKNOWN = -1, + VERY_UNLIKELY = 0, + UNLIKELY, + POSSIBLE, + LIKELY, + VERY_LIKELY +} + +enum struct SprayResult { + Result adult; + Result racy; +} + +public void OnPluginStart() { + if(!SQL_CheckConfig(DB_NAME)) { + SetFailState("No database entry for " ... DB_NAME ... "; no database to connect to."); + } + if(!ConnectDB()) { + SetFailState("Failed to connect to database."); + } + + KeyValues kv = new KeyValues("Config"); + kv.ImportFromFile("spraycontrol.cfg"); + + if (!kv.JumpToKey("apikey")) { + delete kv; + SetFailState("No 'apikey' provided in spraycontrol.cfg"); + } + + kv.GetString("apikey", apikey, sizeof(apikey)); + + RegAdminCmd("sm_checkspray", Command_CheckSpray, ADMFLAG_GENERIC, "Gets the spray results of a user"); +} + +bool ConnectDB() { + char error[255]; + g_db = SQL_Connect(DB_NAME, true, error, sizeof(error)); + if (g_db == null) { + LogError("[SFC] Database error %s", error); + delete g_db; + return false; + } else { + SQL_LockDatabase(g_db); + SQL_FastQuery(g_db, "SET NAMES \"UTF8mb4\""); + SQL_UnlockDatabase(g_db); + g_db.SetCharset("utf8mb4"); + return true; + } +} + +// Events + +public void OnClientAuthorized(int client, const char[] auth) { + if(!StrEqual(auth, "BOT", true)) { + char filename[64], query[128]; + if(!GetPlayerDecalFile(client, filename, sizeof(filename))) { + return; //They don't have a spray + } + Format(query, sizeof(query), "SELECT adult,racy FROM spray_results WHERE steamid = '%s' AND sprayid = '%s'", auth, filename); + g_db.Query(DB_OnConnectCheck, query, GetClientUserId(client)); + } +} + +public void DB_OnConnectCheck(Database db, DBResultSet results, const char[] error, int user) { + int client = GetClientOfUserId(user); + if(db == INVALID_HANDLE || results == null) { + LogError("DB_OnConnectCheck returned error: %s", error); + }else{ + if(results.RowCount > 0 && client) { + int adult = results.FetchInt(0) + 1; + int racy = results.FetchInt(1) + 1; + + CheckUser(client, adult, racy); + } else { + char filename[64]; + if(!GetPlayerDecalFile(client, filename, sizeof(filename))) { + return; //They don't have a spray + } + System2_ExecuteFormattedThreaded(ExecuteCallback, GetClientUserId(client), "test-spray %s %s", filename, apikey); + } + } +} + +public void ExecuteCallback(bool success, const char[] command, System2ExecuteOutput output, int user) { + int client = GetClientOfUserId(user); + if(client <= 0) return; //Client disconnected, void result + if (!success || output.ExitStatus != 0) { + PrintToServer("[SFC] Could not get the spray result for %N", client); + } else { + char outputString[128]; + output.GetOutput(outputString, sizeof(outputString)); + + char results[2][64]; + char bit[3][16]; + ExplodeString(outputString, "\n", results, 2, 64); + + int adult = -1; + int racy = -1; + + ExplodeString(results[0], "=", bit, 3, 16); + adult = StringToInt(bit[2]); + ExplodeString(results[1], "=", bit, 3, 16); + racy = StringToInt(bit[2]); + + PrintToServer("[SFC] %N Spray Results | adult=%s racy=%s", RESULT_TEXT[adult], RESULT_TEXT[racy]); + + CheckUser(client, adult, racy); + } +} + +public Action Command_CheckSpray(int client, int args) { + if(args < 1) + ReplyToCommand(client, "Usage: sm_checkspray "); + else { + char arg1[64]; + GetCmdArg(1, arg1, sizeof(arg1)); + int target = FindTarget(client, arg1, true, false); + if(target > 0) { + char filename[64]; + if(!GetPlayerDecalFile(client, filename, sizeof(filename))) { + ReplyToCommand(client, "%N does not have a spray", target); + return Plugin_Handled; + } + System2_ExecuteFormattedThreaded(ExecuteCallback, GetClientUserId(client), "test-spray %s %s", filename, apikey); + } else { + ReplyToCommand(client, "Could not find target."); + } + } + return Plugin_Handled; +} + +void CheckUser(int client, int adult, int racy) { + if(adult > 3 || (adult > ADULT_THRES && racy > RACY_THRES)) { + PrintToAdmins("%N 's spray has a questionable spray. Adult=%s Racy=%s", + client, + RESULT_TEXT[adult], + RESULT_TEXT[racy] + ); + } +} + +stock void PrintToAdmins(const char[] format, any ...) { + char message[100]; + VFormat(message, sizeof(message), format, 2); + for (int x = 1; x <= MaxClients; x++){ + if (IsClientConnected(x) && IsClientInGame(x) && GetUserAdmin(x) != INVALID_ADMIN_ID) { + PrintToChat(x, message); + } + } +} \ No newline at end of file