text
stringlengths
2
104M
meta
dict
## Compose sample application ### Lucee standalone application This is just the most basic demonstration, and while using the "latest" tag is an option, it's not the best. See other examples that show pointing to a specific tag (for a specific update of a specific Lucee version). Project structure: ``` . β”œβ”€β”€ docker-compose.yml β”œβ”€β”€ app └── test.cfm └── dumpserver.cfm ``` [_docker-compose.yml_](docker-compose.yml) ``` services: lucee: image: lucee/lucee:latest ports: - "8888:8888" ``` ## Deploy with docker-compose ``` $ docker-compose up -d - Network lucee-latest_default Created 0.0s - Container lucee-latest-lucee-1 Started 0.3s ``` ## Expected result Listing containers must show one container running and the port mapping as below (note that the version reported may differ for you, in using the "latest" tag): ``` $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dfc208f9368c lucee/lucee:latest "catalina.sh run" 37 seconds ago Up 36 seconds 8080/tcp, 0.0.0.0:8888->8888/tcp lucee-latest-lucee-1 ``` ## Running requests After the application starts, navigate to `http://localhost:8888` in your web browser to run available files placed into Lucee's webroot by default. ### Default files included with the container Unless you mount an app into the container (see the next section), the Lucee image defaults to providing a few files in that location: index.cfm (a welcome page), debug.cfm (dumping various scopes), an Application.cfc, and a favicon.ico. If you run the URL in the previous section, then you would see the welcome page (at index.cfm) by default. To see the debug page, you could run `http://localhost:8888/debug.cfm` in your web browser to see the test page, or run via curl: ``` $ curl http://localhost:8888/debug.cfm ``` ### Mounting an app into the container Optionally, you can copy files into the container webroot (/var/www). The can be done by adding a volume mount of a host folder into that containe folder. Those are then what become available as the contents for the root site of the container. For example, included with this compose file is an app folder, with some test files. The following volumes directive (under the lucee service) would mount those files into the container: volumes: - ./app:/var/www You could then run `http://localhost:8888/test.cfm` in your web browser to see the test page, or run via curl: ``` $ curl http://localhost:8888/test.cfm Which will show: Hello World! at 03-Jul-2022 21:35:44 ``` Or to see a dump of the server scope within the container, navigate to `http://localhost:8888/dumpserver.cfm` in your web browser or run: ``` $ curl http://localhost:8888/dumpserver.cfm ``` To be clear, if you mount or copy in your own files to the /var/www folder, the test.cfm and dumpserver.cfm files won't be available, and instead your own files will be. ## Accessing the Lucee Admin The Lucee admin (server and web)are available within the lucee/lucee container via the paths lucee/admin/server.cfm and lucee/admin/web.cfm, respectively. To access the Lucee Server admin, navigate to `http://localhost:8888/lucee/admin/server.cfm` in your web browser or run: ``` $ curl http://localhost:8888/lucee/admin/server.cfm ``` Or use the same form for the lucee/admin/web.cfm. ### Setting Lucee Admin password (none defined by default) As with Lucee itself, for the sake of security, there is no password defined for the Lucee admin(s) by default. With traditional Lucee deployment, you would create a file called password.txt and place that in the deployment's /lucee-server/context/password.txt file. With containers, we can instead place that file inside the container either via a dockerfile using COPY or via a compose file bind-mounting that file into the container. This compose files shows the latter: lucee: image: lucee/lucee:latest ports: - "8888:8888" volumes: - type: bind source: ./lucee-admin-password/password.txt target: /opt/lucee/server/lucee-server/context/password.txt Note that this can't be implemented as a "shorthand" bind like the other one above (for /var/www). Doing that in this case would would cause docker to create a two-way mount, where all files in the container in that /opt/lucee/server/lucee-server/context folder would be copied also into your host under that lucee-admin-password folder, which is definitely NOT what we want in this simple case of wanting to copy this one file INTO the container. ## Setting java options To set java options within the container (such as to control the heap size, garbage collection args, etc), you can use the environment variable called LUCEE_JAVA_OPTS (the name is case-sensitive). Here is an example of doing that. Note that as of Lucee 5.3.9.141, this value defaults to: -Xms64m -Xmx512m. If you specify one but not the other, the value will depend on the JVM. For instance, with the Java 11.0.15 that comes with that Lucee image version, setting the Xmx only will by default set the Xms to the same value. lucee: image: lucee/lucee:latest ports: - "8888:8888" environment: - LUCEE_JAVA_OPTS=-Xmx1024m ## Stop and remove the containers ``` $ docker-compose down ```
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfscript> name="World" writeoutput("Hello #name#! at #datetimeformat(now())#"); </cfscript>
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
version: "3" services: coldfusion: image: adobecoldfusion/coldfusion2021:latest ports: - "8500:8500" environment: - acceptEULA=YES - password=123 volumes: - ./app:/app
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
## Compose sample application ### ColdFusion standalone application This is just the most basic demonstration, and while using the "latest" tag is an option, it's not the best. See other examples that show pointing to a specific tag (for a specific update of a specific CF version). Project structure: ``` . β”œβ”€β”€ docker-compose.yml β”œβ”€β”€ app └── test.cfm └── dumpserver.cfm ``` [_docker-compose.yml_](docker-compose.yml) ``` services: coldfusion: image: adobecoldfusion/coldfusion2021:latest ports: - "8500:8500" environment: - acceptEULA=YES - password=123 volumes: - ./app:/app ``` ## Deploy with docker-compose ``` $ docker-compose up -d - Network cf-latest_default Created 0.8s - Container cf-latest-coldfusion-1 Created 0.2s Attaching to cf-latest-coldfusion-1 cf-latest-coldfusion-1 | Updating webroot to /app cf-latest-coldfusion-1 | Configuring virtual directories cf-latest-coldfusion-1 | Updating password cf-latest-coldfusion-1 | Skipping language updation cf-latest-coldfusion-1 | Serial Key: Not Provided cf-latest-coldfusion-1 | Previous Serial Key: Not Provided cf-latest-coldfusion-1 | Starting ColdFusion ... ``` ## Expected result Listing containers must show one container running and the port mapping as below (note that the version reported may differ for you, in using the "latest" tag): ``` $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d935f819f622 adobecoldfusion/coldfusion2021:latest "sh /opt/startup/sta…" About a minute ago Up About a minute (healthy) 8118/tcp, 45564/tcp, 0.0.0.0:8500->8500/tcp cf-latest_coldfusion_1 ``` After the application starts, navigate to `http://localhost:8500` in your web browser to see available files in CF's default webroot (added to by the /app volume mapping) Or run `http://localhost:8500/test.cfm` in your web browser to see the test page in the mapped /app folder, or run via curl: ``` $ curl http://localhost:8500/test.cfm Which will show: Hello World! at 03-Oct-2021 02:35:44 ``` Run this to see a dump of the server.coldfusion struct within the container: navigate to `http://localhost:8500/dumpserver.cfm` in your web browser or run: ``` $ curl http://localhost:8500/dumpserver.cfm ``` Stop and remove the containers ``` $ docker-compose down ```
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfscript> name="World" writeoutput("Hello #name#! at #datetimeformat(now())#"); </cfscript>
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
version: "3" services: addons: image: adobecoldfusion/coldfusionaddons2021 environment: - acceptEULA=YES ports: - "8993:8993" coldfusion: image: adobecoldfusion/coldfusion2021 ports: - "8500:8500" environment: - acceptEULA=YES - password=123 # following needed for either solr or pdfg - configureExternalAddons=true - addonsHost=addons - addonsPort=8993 - installModules=htmltopdf,search # importModules can be used instead to point to a file in container holding cfpm export # following needed for pdfg - addonsPDFServiceName=addons depends_on: - addons volumes: - ./app:/app
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
## Compose sample application ### ColdFusion with addons service (supporting Solr and PDFg/cfhtmltopdf integration) Complete Readme text to be developed
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfscript> name="World" writeoutput("Hello #name#! at #datetimeformat(now())#"); </cfscript>
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfhtmltopdf name="test"> test </cfhtmltopdf> <cfheader name="Content-Disposition" value="attachment; filename=cfhtmltopdf-test.pdf"> <cfcontent reset="yes" type="application/pdf" variable="#test#">
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<!--- this is a rather silly example, in that it indexes the standard linix /var/log folder. I'm using that as something simply to rely upon to confirm that indexing any folder (and dumping the contents of a search of that index) can be demonstrated to have worked. ---> <cfindex action="update" collection="test" type="path" key="/var/log/" extensions=".log"> <cfsearch collection="test" name="get"> <cfdump var="#get#">
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfcollection action="list" name="get"> <cfdump var="#get#">
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfcollection action="create" collection="test" path=""> <cfcollection action="list" name="get"> <cfdump var="#get#">
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
version: "3" services: coldfusion: image: adobecoldfusion/coldfusion2021:2021.0.4 ports: - "8500:8500" environment: - acceptEULA=YES - password=123 volumes: - ./app:/app
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
## Compose sample application ### ColdFusion standalone application Project structure: ``` . β”œβ”€β”€ docker-compose.yml β”œβ”€β”€ app └── test.cfm └── dumpserver.cfm ``` [_docker-compose.yml_](docker-compose.yml) ``` services: coldfusion: image: adobecoldfusion/coldfusion2021:2021.0.4 ports: - "8500:8500" environment: - acceptEULA=YES - password=123 volumes: - ./app:/app ``` ## Deploy with docker-compose ``` $ docker-compose up -d - Network cf-latest_default Created 0.8s - Container cf-latest-coldfusion-1 Created 0.2s Attaching to cf-latest-coldfusion-1 cf-2021-update-specified-coldfusion-1 | Updating webroot to /app cf-2021-update-specified-coldfusion-1 | Configuring virtual directories cf-2021-update-specified-coldfusion-1 | Updating password cf-2021-update-specified-coldfusion-1 | Serial Key: Not Provided cf-2021-update-specified-coldfusion-1 | Previous Serial Key: Not Provided cf-2021-update-specified-coldfusion-1 | Starting ColdFusion ... ``` ## Expected result Listing containers must show one container running and the port mapping as below (note that the version reported may differ for you, in using the "latest" tag): ``` $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a7df2d9ffc26 adobecoldfusion/coldfusion2021:2021.0.2 "sh /opt/startup/sta…" 6 minutes ago Up 6 minutes (healthy) 8118/tcp, 45564/tcp, 0.0.0.0:8500->8500/tcp cf-2021-coldfusion-1 ``` After the application starts, navigate to `http://localhost:8500` in your web browser to see available files in CF's default webroot (added to by the /app volume mapping) Or run `http://localhost:8500/test.cfm` in your web browser to see the test page in the mapped /app folder, or run via curl: ``` $ curl http://localhost:8500/test.cfm Which will show: Hello World! at 03-Oct-2021 02:25:44 ``` Run this to see a dump of the server.coldfusion struct within the container: navigate to `http://localhost:8500/dumpserver.cfm` in your web browser or run: ``` $ curl http://localhost:8500/dumpserver.cfm ``` Stop and remove the containers ``` $ docker-compose down ```
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
<cfscript> name="World" writeoutput("Hello #name#! at #datetimeformat(now())#"); </cfscript>
{ "repo_name": "carehart/awesome-cf-compose", "stars": "27", "repo_language": "ColdFusion", "file_name": "test.cfm", "mime_type": "text/plain" }
CC0 1.0 Universal Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see <http://creativecommons.org/publicdomain/zero/1.0/>
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - CircularJSON * By Hudell - www.hudell.com * OrangeCircularJSON.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Fixes Circular References on JSON serialization <OrangeCircularJSON> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * This plugin uses the CircularJSON module by WebRelection: * https://github.com/WebReflection/circular-json * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeCircularJSON = Hudell.OrangeCircularJSON || {}; (function($) { var oldJsonExStringify = JsonEx.stringify; var oldJsonExParse = JsonEx.parse; //CircularJSON, by WebReflection (https://github.com/WebReflection/circular-json) // Modified to include the functionality of JsonEx._encode and JsonEx._decode, from MV's lib. /*! Copyright (C) 2013 by WebReflection Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var CircularJSON = (function(JSON, RegExp){ var // should be a not so common char // possibly one JSON does not encode // possibly one encodeURIComponent does not encode // right now this char is '~' but this might change in the future specialChar = '~', safeSpecialChar = '\\x' + ( '0' + specialChar.charCodeAt(0).toString(16) ).slice(-2), escapedSafeSpecialChar = '\\' + safeSpecialChar, specialCharRG = new RegExp(safeSpecialChar, 'g'), safeSpecialCharRG = new RegExp(escapedSafeSpecialChar, 'g'), safeStartWithSpecialCharRG = new RegExp('(?:^|([^\\\\]))' + escapedSafeSpecialChar), indexOf = [].indexOf || function(v){ for(var i=this.length;i--&&this[i]!==v;); return i; }, $String = String // there's no way to drop warnings in JSHint // about new String ... well, I need that here! // faked, and happy linter! ; function generateReplacer(value, replacer, resolve) { var path = [], all = [value], seen = [value], mapp = [resolve ? specialChar : '[Circular]'], last = value, lvl = 1, i ; return function(key, value) { // the replacer has rights to decide // if a new object should be returned // or if there's some key to drop // let's call it here rather than "too late" if (replacer) value = replacer.call(this, key, value); var type = Object.prototype.toString.call(value); if (type === '[object Object]' || type === '[object Array]') { var constructorName = JsonEx._getConstructorName(value); if (constructorName !== 'Object' && constructorName !== 'Array') { value['@'] = constructorName; } } // did you know ? Safari passes keys as integers for arrays // which means if (key) when key === 0 won't pass the check if (key !== '') { if (last !== this) { i = lvl - indexOf.call(all, this) - 1; lvl -= i; all.splice(lvl, all.length); path.splice(lvl - 1, path.length); last = this; } // console.log(lvl, key, path); if (typeof value === 'object' && value) { // if object isn't referring to parent object, add to the // object path stack. Otherwise it is already there. if (indexOf.call(all, value) < 0) { all.push(last = value); } lvl = all.length; i = indexOf.call(seen, value); if (i < 0) { i = seen.push(value) - 1; if (resolve) { // key cannot contain specialChar but could be not a string path.push(('' + key).replace(specialCharRG, safeSpecialChar)); mapp[i] = specialChar + path.join(specialChar); } else { mapp[i] = mapp[0]; } } else { value = mapp[i]; } } else { if (typeof value === 'string' && resolve) { // ensure no special char involved on deserialization // in this case only first char is important // no need to replace all value (better performance) value = value .replace(safeSpecialChar, escapedSafeSpecialChar) .replace(specialChar, safeSpecialChar); } } } return value; }; } function retrieveFromPath(current, keys) { for(var i = 0, length = keys.length; i < length; current = current[ // keys should be normalized back here keys[i++].replace(safeSpecialCharRG, specialChar) ]); return current; } function generateReviver(reviver) { return function(key, value) { var isString = typeof value === 'string'; if (isString && value.charAt(0) === specialChar) { return new $String(value.slice(1)); } if (key === '') value = regenerate(value, value, {}); // again, only one needed, do not use the RegExp for this replacement // only keys need the RegExp if (isString) value = value .replace(safeStartWithSpecialCharRG, '$1' + specialChar) .replace(escapedSafeSpecialChar, safeSpecialChar); return reviver ? reviver.call(this, key, value) : value; }; } function regenerateArray(root, current, retrieve) { for (var i = 0, length = current.length; i < length; i++) { current[i] = regenerate(root, current[i], retrieve); } return current; } function regenerateObject(root, current, retrieve) { for (var key in current) { if (current.hasOwnProperty(key)) { current[key] = regenerate(root, current[key], retrieve); } } var type = Object.prototype.toString.call(current); if (type === '[object Object]' || type === '[object Array]') { if (current['@']) { var constructor = window[current['@']]; if (constructor) { current = JsonEx._resetPrototype(current, constructor.prototype); } } } return current; } function regenerate(root, current, retrieve) { return current instanceof Array ? // fast Array reconstruction regenerateArray(root, current, retrieve) : ( current instanceof $String ? ( // root is an empty string current.length ? ( retrieve.hasOwnProperty(current) ? retrieve[current] : retrieve[current] = retrieveFromPath( root, current.split(specialChar) ) ) : root ) : ( current instanceof Object ? // dedicated Object parser regenerateObject(root, current, retrieve) : // value as it is current ) ) ; } function stringifyRecursion(value, replacer, space, doNotResolve) { return JSON.stringify(value, generateReplacer(value, replacer, !doNotResolve), space); } function parseRecursion(text, reviver) { return JSON.parse(text, generateReviver(reviver)); } return { stringify: stringifyRecursion, parse: parseRecursion }; }(JSON, RegExp)); JsonEx.stringify = function(object) { return CircularJSON.stringify(object); }; JsonEx.parse = function(json) { return CircularJSON.parse(json); }; $.oldJsonExParse = oldJsonExParse; $.oldJsonExStringify = oldJsonExStringify; $.CircularJSON = CircularJSON; })(Hudell.OrangeCircularJSON); OrangeCircularJSON = Hudell.OrangeCircularJSON; Imported.OrangeCircularJSON = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - SteamCloud * By Hudell - www.hudell.com * OrangeSteamCloud.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Steam Cloud Integration <OrangeSteamCloud> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website to learn how to use this plugin: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeSteamCloud = Hudell.OrangeSteamCloud || {}; (function($) { "use strict"; if (!Utils.isNwjs()) return; if (Imported.OrangeGreenworks === undefined || isNaN(Imported.OrangeGreenworks) || Imported.OrangeGreenworks < 1.1) { console.error('OrangeGreenworks not found.'); return; } if (!OrangeGreenworks.initialized) { console.error('OrangeGreenworks not initialized'); return; } var g = OrangeGreenworks.greenworks; if (!g) { console.error('Unable to find OrangeGreenworks internal component.'); return; } $.syncAllSaves = function() { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; g.readTextFromFile('globalInfo', function(json){ var localJson; try { localJson = StorageManager.load(0); } catch (e) { console.error(e); localJson = ''; } if (json == localJson) return; var globalInfo; var localGlobalInfo; try { globalInfo = JSON.parse(json); } catch(e) { globalInfo = {}; } try { localGlobalInfo = JSON.parse(localJson); } catch(e) { localGlobalInfo = {}; } for (var i = 1; i <= DataManager.maxSavefiles(); i++) { var remoteData = globalInfo[i]; var localData = localGlobalInfo[i]; if (!remoteData) continue; if (!!localData) { if (localData.timestamp >= remoteData.timestamp) continue; } $.downloadFile(i, remoteData); } }, function(msg){ console.log('Global Info download failed. Error message:', msg); }); }; $.saveFile = function(fileName, fileContent) { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; g.saveTextToFile(fileName, fileContent, function(){ console.log('Save file uploaded successfully', arguments); }, function(){ console.error('Failed to upload save file:', arguments); }); }; $.updateLocalGlobalInfo = function(savefileId, header) { var globalInfo = DataManager.loadGlobalInfo() || []; globalInfo[savefileId] = header; $.saveLocally(0, JSON.stringify(globalInfo)); }; $.saveLocally = function(savefileId, json) { if (StorageManager.isLocalMode()) { StorageManager.saveToLocalFile(savefileId, json); } else { StorageManager.saveToWebStorage(savefileId, json); } }; $.downloadFile = function(savefileId, header) { if (!g.isSteamRunning()) return; if (!g.isCloudEnabled()) return; if (!g.isCloudEnabledForUser()) return; if (savefileId > 0) { g.readTextFromFile('save_' + savefileId, function(fileContent){ try { //Make sure the data is parse-able before saving it. var data = JSON.parse(fileContent); $.saveLocally(savefileId, fileContent); $.updateLocalGlobalInfo(savefileId, header); } catch(e) { console.error('Failed to save downloaded file ' + savefileId, e); } }, function(msg){ console.error('Failed to download save file ' + savefileId, msg); }); } else { if (savefileId == -1) { //jshint ignore:line g.readTextFromFile('config', function(fileContent){ $.saveLocally(-1, fileContent); ConfigManager.load(); }, function(msg){ console.error('Failed to download config from cloud.', msg); }); } } }; $._oldDataManager_makeSavefileInfo = DataManager.makeSavefileInfo; DataManager.makeSavefileInfo = function() { var info = $._oldDataManager_makeSavefileInfo.call(this); info.timestamp = new Date().getTime(); return info; }; $._oldStorageManager_save = StorageManager.save; StorageManager.save = function(savefileId, json) { $._oldStorageManager_save.call(this, savefileId, json); if (savefileId == 0) { //jshint ignore:line $.saveFile('globalInfo', json); } else if (savefileId == -1) { $.saveFile('config', json); } else { $.saveFile('save_' + savefileId, json); } }; $._oldDataManager_saveGlobalInfo = DataManager.saveGlobalInfo; DataManager.saveGlobalInfo = function(info) { info.timestamp = new Date().getTime(); $._oldDataManager_saveGlobalInfo.call(this, info); }; $.downloadFile(-1); $.syncAllSaves(); })(Hudell.OrangeSteamCloud); OrangeSteamCloud = Hudell.OrangeSteamCloud; Imported.OrangeSteamCloud = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Disable Mouse Movement * By Hudell - www.hudell.com * OrangeDisableMouseMovement.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will disable the player movement with the use of the mouse * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/disable-mouse-movement * *=============================================================================*/ Game_Temp.prototype.setDestination = function(x, y) {}; var Imported = Imported || {}; Imported["OrangeDisableMouseMovement"] = true;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Simple Mouse Data * By Hudell - www.hudell.com * OrangeMouseData.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Will give you access to mouse's X, Y, TileX, TileY and Down Status for both left and right buttons <OrangeMouseData> * * @author Hudell * * @param variableMouseX * @desc The number of the variable where the Mouse X will be stored * @default 0 * * @param variableMouseY * @desc The number of the variable where the Mouse Y will be stored * @default 0 * * @param variableMouseTileX * @desc The number of the variable where the Mouse Tile X will be stored * @default 0 * * @param variableMouseTileY * @desc The number of the variable where the Mouse TIle Y will be stored * @default 0 * * @param switchLeftButtonDown * @desc The number of the switch that will be turned on when the mouse left button is clicked * @default 0 * * @param switchRightButtonDown * @desc The number of the switch that will be turned on when the mouse right button is clicked * @default 0 * * @param switchMiddleButtonDown * @desc The number of the switch that will be turned on when the mouse middle button is clicked * @default 0 */ var Imported = Imported || {}; var OrangeMouseData = OrangeMouseData || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin){ return plugin.description.indexOf('<OrangeMouseData>') >= 0; }); if (parameters.length === 0) { throw new Error("Couldn't find OrangeMouseData parameters."); } $.Parameters = parameters[0].parameters; $.Param = $.Param || {}; $.Param.variableMouseX = Number($.Parameters['variableMouseX'] || 0); $.Param.variableMouseY = Number($.Parameters['variableMouseY'] || 0); $.Param.variableMouseTileX = Number($.Parameters['variableMouseTileX'] || 0); $.Param.variableMouseTileY = Number($.Parameters['variableMouseTileY'] || 0); $.Param.switchLeftButtonDown = Number($.Parameters['switchLeftButtonDown'] || 0); $.Param.switchRightButtonDown = Number($.Parameters['switchRightButtonDown'] || 0); $.Param.switchMiddleButtonDown = Number($.Parameters['switchMiddleButtonDown'] || 0); $.getSwitchId = function(mouseButton) { switch(mouseButton) { case 0 : return $.Param.switchLeftButtonDown; case 1 : return $.Param.switchMiddleButtonDown; case 2 : return $.Param.switchRightButtonDown; default : return 0; } }; $._onMouseUp = function(event) { if ($gameSwitches === null || $gameSwitches === undefined) return; var switchId = $.getSwitchId(event.button); if (switchId > 0) { $gameSwitches.setValue(switchId, false); } }; $._onMouseDown = function(event) { if ($gameSwitches === null || $gameSwitches === undefined) return; var switchId = $.getSwitchId(event.button); if (switchId > 0) { $gameSwitches.setValue(switchId, true); } }; $._onMouseMove = function(event) { if ($gameVariables === null || $gameSwitches === undefined) return; var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); var tileX = x; var tileY = y; if ($gameMap !== undefined && $gameMap !== null && $dataMap !== undefined && $dataMap !== null) { tileX = $gameMap.canvasToMapX(x); tileY = $gameMap.canvasToMapY(y); } if ($.Param.variableMouseX > 0) $gameVariables.setValue($.Param.variableMouseX, x); if ($.Param.variableMouseY > 0) $gameVariables.setValue($.Param.variableMouseY, y); if ($.Param.variableMouseTileX > 0) $gameVariables.setValue($.Param.variableMouseTileX, tileX); if ($.Param.variableMouseTileY > 0) $gameVariables.setValue($.Param.variableMouseTileY, tileY); }; document.addEventListener('mousedown', $._onMouseDown.bind($)); document.addEventListener('mouseup', $._onMouseUp.bind($)); document.addEventListener('mousemove', $._onMouseMove.bind($)); })(OrangeMouseData); Imported["OrangeMouseData"] = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Screenshot Saver * By Hudell - www.hudell.com * OrangeScreenshotSaver.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will automatically save screenshots in a "Screenshots" folder inside the game * * @author Hudell */ var Imported = Imported || {}; var OrangeScreenshotSaver = OrangeScreenshotSaver || {}; (function($) { "use strict"; $.generateFileName = function(){ var date = new Date(); return '' + date.getFullYear() + '_' + (date.getMonth() + 1) + '_' + date.getDate() + '_' + date.getHours() + '_' + date.getMinutes() + '_' + date.getSeconds() + '_' + date.getMilliseconds() + '_' + Math.floor(Math.random() * 5000) + '.png'; }; $.saveScreenshot = function(){ if (!Utils.isNwjs()) return; var fs = require('fs'); var path = './Screenshots'; try { fs.mkdir(path, function(){ var fileName = path + '/' + $.generateFileName(); var snap = SceneManager.snap(); var urlData = snap._canvas.toDataURL(); var base64Data = urlData.replace(/^data:image\/png;base64,/, ""); fs.writeFile(fileName, base64Data, 'base64', function(error){ if (error !== undefined && error !== null) { console.error('An error occured while saving the screenshot', error); } }); }); } catch(error) { if (error !== undefined && error !== null) { console.error('An error occured while saving the screenshot:', error); } } }; var oldInput_onKeyUp = Input._onKeyUp; Input._onKeyUp = function(event) { oldInput_onKeyUp.call(this, event); if (event.keyCode == 44) { $.saveScreenshot(); } }; })(OrangeScreenshotSaver); Imported["OrangeScreenshotSaver"] = true;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Notetag to Switch * By Hudell - www.hudell.com * OrangeNoteTagToSwitch.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to automatically turn on a switch everytime a notetag is found on a map - OrangeNoteTagToSwitch * @author Hudell * * @param switchId * @desc The number of the switch to activate when the notetag is found * @default 0 * * @param notetag * @desc The name of the notetag to look for on the maps notes * @default 0 * * @param noteList * @desc Configure several notes with a single plugin using this param * @default * * @help * Add the <notetag> on the notes of the maps that you want to tag. * * This plugin can be added multiple times to the same project * (just make a copy of the file and add it) * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeNoteTagToSwitch"] === undefined) { (function() { "use strict"; var getProp = undefined; if (Imported["MVCommons"] !== undefined) { getProp = MVC.getProp; } else { getProp = function (meta, propName){ if (meta === undefined) return undefined; if (meta[propName] !== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; } var paramList = []; function updateParamList(){ for (var i = 0; i < $plugins.length; i++) { if ($plugins[i].description.indexOf('OrangeNoteTagToSwitch') >= 0) { var switchId = Number($plugins[i].parameters['switchId'] || 0); var notetagName = $plugins[i].parameters['notetag'] || ''; if (switchId > 0 && notetagName.trim().length > 0) { paramList.push({ switchId : switchId, notetagName : notetagName }); } var list = $plugins[i].parameters['noteList']; if (list !== undefined) { var re = /<([^<>:]+):([^>]*)>/g; while(true) { var match = re.exec(list); if (match) { notetagName = match[1]; switchId = Number(match[2] || 0); if (switchId > 0 && notetagName.trim().length > 0) { paramList.push({ switchId : switchId, notetagName : notetagName }); } } else { break; } } } } } } updateParamList(); if (paramList.length > 0) { var updateSwitchList = function() { if (SceneManager._scene instanceof Scene_Map) { for (var i = 0; i < paramList.length; i++) { var value = undefined; if ($gameMap._interpreter.isRunning() && $gameMap._interpreter._eventId > 0) { var eventData = $dataMap.events[$gameMap._interpreter._eventId]; if (eventData) { value = getProp(eventData.meta, paramList[i].notetagName); } } if (value === undefined) { value = getProp($dataMap.meta, paramList[i].notetagName) === true; } $gameSwitches.setValue(paramList[i].switchId, value); } } }; var oldGameInterpreter_setup = Game_Interpreter.prototype.setup; Game_Interpreter.prototype.setup = function(list, eventId) { oldGameInterpreter_setup.call(this, list, eventId); updateSwitchList(); }; var oldGameInterpreter_terminate = Game_Interpreter.prototype.terminate; Game_Interpreter.prototype.terminate = function(list, eventId) { oldGameInterpreter_terminate.call(this, list, eventId); updateSwitchList(); }; var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { var shouldUpdateSwitchList = this.isTransferring(); oldGamePlayer_performTransfer.call(this); if (shouldUpdateSwitchList) { updateSwitchList(); } }; } })(); Imported["OrangeNoteTagToSwitch"] = 1.2; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Overlay * By Hudell - www.hudell.com * OrangeOverlay.js * Version: 1.1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc v1.1.2 - Adds overlay images to the map <OrangeOverlay> * @author Hudell * * @param Organized Folders * @desc Use different folders for each type of parallax * @default false * * @param Parallax Layer Filename * @desc * @default par * * @param Ground Layer Filename * @desc * @default ground * * @param Light Layer Filename * @desc * @default light * * @param Shadow Layer Filename * @desc * @default shadow * * @param Light Opacity * @desc * @default 185 * * @param Quick Start * @desc * @default true * * @param Bush Region ID * @desc * @default 7 * * @param Fog Switch ID * @desc * @default 1 * * @param Light Switch ID * @desc * @default 2 * * @param Parallax Switch ID * @desc * @default 3 * * @param Shadow Switch ID * @desc * @default 4 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * Instructions * ============================================================================ * * You can use this plugin to add overlay images to your maps * You can keep the images either on the img/parallaxes folder * Or (if you set the Organized Folders param to true) on separate folders like this: * * img/overlays/grounds * img/overlays/pars * img/overlays/shadows * img/overlays/lights * img/overlays/fogs * * All image filenames must end with the number of the map that they are used on * * Map notetags: * * <all> : Display all overlays * <ground> : Display ground overlay * <par> : Display parallax overlay * <light> : Display light overlay * <shadow> : Display shadow overlay * <fogName:filename> : Display the specified fog image * <fogOpacity:number> : Change the opacity level of the fog image (0 to 255) * <fogBlend:number> : Changes the blend type of the fog image * <fogDuration:number> : Changes the duration of the opacity transition * <xMove:number> : Changes the horizontal speed of the fog * <yMove:number> : Changes the vertical speed of the fog * * You can use variables numbers on the notetags by adding a $ symbol before the value * * ============================================================================ * Plugin Commands * ============================================================================ * ---------------------------------------------------------------------------- * Overlay layertype filename * ---------------------------------------------------------------------------- * Possible layer types: ground, light, shadow, par * * ---------------------------------------------------------------------------- * Overlay fog filename opacity xMove yMove blendmode duration * ---------------------------------------------------------------------------- * Changes the fog params to the ones specified in this command. * Blendmode and duration are optional * Examples: * Overlay fog fog1 100 10 0 0 20 * This will display the file fo1 with opacity 100 and move horizontally 10px * at a time, with a transition of 20 frames * * ---------------------------------------------------------------------------- * Overlay fadeout duration * ---------------------------------------------------------------------------- * Do a fadeout effect on the current fog * * ---------------------------------------------------------------------------- * Overlay addfog filename ID Opacity xMove yMove BlendType Z * ---------------------------------------------------------------------------- * Adds an extra fog layer. BlendType and Z values are optional * * ---------------------------------------------------------------------------- * Overlay removefog ID * ---------------------------------------------------------------------------- * Removes an extra fog that was added with the addfog command * * ============================================================================ * Changelog * ============================================================================ * Version 1.1.2: * Fixed several small issues with the opacity *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeOverlay = Hudell.OrangeOverlay || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeOverlay>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeOverlay parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.Param.organizedFolders = $.Parameters["Organized Folders"] == 'true'; $.Param.parallaxLayerFileName = $.Parameters["Parallax Layer Filename"] || 'par'; $.Param.groundLayerFileName = $.Parameters["Ground Layer Filename"] || 'ground'; $.Param.lightLayerFileName = $.Parameters["Light Layer Filename"] || 'light'; $.Param.shadowLayerFileName = $.Parameters["Shadow Layer Filename"] || 'shadow'; $.Param.lightOpacity = Number($.Parameters["Light Opacity"] || 185); $.Param.quickStart = $.Parameters["Quick Start"] != 'false'; $.Param.bushRegionId = Number($.Parameters["Bush Region ID"] || 7); $.Param.fogSwitchId = Number($.Parameters["Fog Switch ID"] || 1); $.Param.lightSwitchId = Number($.Parameters["Light Switch ID"] || 2); $.Param.parallaxSwitchId = Number($.Parameters["Parallax Switch ID"] || 3); $.Param.shadowSwitchId = Number($.Parameters["Shadow Switch ID"] || 4); $.clearParams = function() { $.fogFileNameCommand = ''; $.fogOpacityCommand = 0; $.fogMoveXCommand = 0; $.fogMoveYCommand = 0; $.fodBlendCommand = 0; $.fogDurationCommand = 0; $.overlayFadeOut = false; $.fogFadeOut = 1; $.fogFileName = ''; $.fogOpacity = 255; $.fogMoveX = 0; $.fogMoveY = 0; $.fogBlendMode = 0; $.fogDuration = 1; $.updateFog = false; $.updateLight = false; $.lightName = ''; $.updateShadow = false; $.shadowName = ''; $.updateParallax = false; $.parallaxName = ''; $.updateGround = false; $.groundName = ''; $.newFogToCreate = false; $.newFogName = ''; $.newFogId = ''; $.newFogOpacity = 0; $.newFogZ = 22; $.newFogBlend = 0; $.newFogXMove = 0; $.newFogYMove = 0; $.fogToRemove = 0; $.defOpacity = 0; $.defDuration = 1; $.defTransition = 0; $.fogNewX = 0; $.fogNewY = 0; }; $.clearParams(); var oldDataManager_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { oldDataManager_setupNewGame.call(this); if ($.Param.quickStart) { if ($.Param.fogSwitchId > 0) { $gameSwitches.setValue($.Param.fogSwitchId, true); } if ($.Param.lightSwitchId > 0) { $gameSwitches.setValue($.Param.lightSwitchId, true); } if ($.Param.parallaxSwitchId > 0) { $gameSwitches.setValue($.Param.parallaxSwitchId, true); } if ($.Param.shadowSwitchId > 0) { $gameSwitches.setValue($.Param.shadowSwitchId, true); } } }; var oldSpritesetMap_createLowerLayer = Spriteset_Map.prototype.createLowerLayer; Spriteset_Map.prototype.createLowerLayer = function() { $.clearParams(); this._fogList = []; oldSpritesetMap_createLowerLayer.call(this); }; Spriteset_Map.prototype.loadBitmap = function(folderName, fileName) { if ($.Param.organizedFolders) { return ImageManager.loadBitmap('img/overlays/' + folderName + '/', fileName); } return ImageManager.loadParallax(fileName); }; Spriteset_Map.prototype.createLayer = function(folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity) { if (!$dataMap) return null; if (!$dataMap.meta) return null; if (!$dataMap.meta[tagName] && !$dataMap.meta.all) { return null; } if (maxOpacity === undefined) maxOpacity = 255; var layer = new Sprite(); layer.bitmap = this.loadBitmap(folderName, fileNamePrefix + $gameMap._mapId); layer.z = zValue; this._tilemap.addChild(layer); if (switchId > 0) { layer.opacity = $gameSwitches.value(switchId) ? maxOpacity : 0; } return layer; }; Spriteset_Map.prototype.createGroundLayer = function() { this._groundLayer = this.createLayer('grounds', $.Param.groundLayerFileName, 'ground', 1, 0); }; Spriteset_Map.prototype.createParallaxLayer = function() { this._parallaxLayer = this.createLayer('pars', $.Param.parallaxLayerFileName, 'par', 20, $.Param.parallaxSwitchId); }; Spriteset_Map.prototype.createShadowLayer = function() { this._shadowLayer = this.createLayer('shadows', $.Param.shadowLayerFileName, 'shadow', 21, $.Param.shadowSwitchId); }; Spriteset_Map.prototype.getOverlayVariable = function(variableName) { if (!$dataMap) return false; if (!$dataMap.meta) return false; if ($dataMap.meta[variableName] === undefined) return false; var value = $dataMap.meta[variableName].trim(); if (value[0] == '$') { value = value.slice(1); var variableId = parseInt(value, 10); if (!isNaN(variableId) && variableId > 0) { return $gameVariables.value(variableId); } } return value; }; Spriteset_Map.prototype.createFogItem = function(id, fileName, xMove, yMove, opacity, blend, z) { if (!this._fogList[id]) { var data = {}; data.bitmap = this.loadBitmap('fogs', fileName); if (!data.bitmap) return; data.sprite = new TilingSprite(); data.sprite.bitmap = data.bitmap; data.sprite.width = Graphics.width; data.sprite.height = Graphics.height; data.sprite.opacity = opacity; data.sprite.blendMode = blend; data.sprite.z = z; data.newX = 0; data.newY = 0; data.xMove = xMove; data.yMove = yMove; this._fogList[id] = data; this._tilemap.addChild(data.sprite); } $.newFogToCreate = false; }; Spriteset_Map.prototype.createFogLayer = function() { $.fogFileName = this.getOverlayVariable('fogName'); $.fogOpacity = parseInt(this.getOverlayVariable('fogOpacity'), 10) || 255; $.fogMoveX = parseFloat(this.getOverlayVariable('xMove'), 10) || 0; $.fogMoveY = parseFloat(this.getOverlayVariable('yMove'), 10) || 0; $.fogBlendMode = parseInt(this.getOverlayVariable('fogBlend'), 10) || 0; $.fogDuration = parseInt(this.getOverlayVariable('fogDuration'), 10) || 1; if (!$.fogFileName && !$.fogFileNameCommand) return; var fileName = $.fogFileName; if (!!$.fogFileNameCommand && $.fogFileNameCommand !== '') { fileName = $.fogFileNameCommand; } var bitmap = this.loadBitmap('fogs', fileName); if (!bitmap) return; var layer = new TilingSprite(); layer.bitmap = bitmap; layer.width = Graphics.width; layer.height = Graphics.height; layer.blendMode = $.fogBlendMode; layer.opacity = 0; layer.origin.x = $gameMap.displayX() * $gameMap.tileWidth(); layer.origin.y = $gameMap.displayY() * $gameMap.tileHeight(); layer.z = 22; $.fogNewX = 0; $.fogNewY = 0; this._tilemap.addChild(layer); this._fogLayer = layer; $.updateFog = false; }; Spriteset_Map.prototype.createLightLayer = function() { this._lightLayer = this.createLayer('lights', $.Param.lightLayerFileName, 'light', 23, $.Param.lightSwitchId, $.Param.lightOpacity); if (!!this._lightLayer) { this._lightLayer.blendMode = 1; } }; var oldSpritesetMap_createCharacters = Spriteset_Map.prototype.createCharacters; Spriteset_Map.prototype.createCharacters = function() { this.createGroundLayer(); oldSpritesetMap_createCharacters.call(this); this.createParallaxLayer(); this.createShadowLayer(); this.createFogLayer(); this.createLightLayer(); }; Spriteset_Map.prototype.updateLayer = function(layerName, update, folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity, opacityChange) { if (maxOpacity === undefined) maxOpacity = 255; if (opacityChange === undefined) opacityChange = 10; var layer = this[layerName]; if (!layer) { layer = this.createLayer(folderName, fileNamePrefix, tagName, zValue, switchId, maxOpacity); update = false; } if (!!layer) { layer.x = $gameMap.displayX() * (0 - $gameMap.tileWidth()); layer.y = $gameMap.displayY() * (0 - $gameMap.tileHeight()); if (switchId > 0) { if ($gameSwitches.value(switchId)) { if (layer.opacity < maxOpacity) { layer.opacity += opacityChange; } if (layer.opacity > maxOpacity) { layer.opacity = maxOpacity; } } else { if (layer.opacity > 0) { layer.opacity -= opacityChange; } if (layer.opacity < 0) { layer.opacity = 0; } } } if (update) { layer.bitmap = this.loadBitmap(folderName, fileNamePrefix + $gameMap._mapId); } this[layerName] = layer; } }; Spriteset_Map.prototype.updateGroundLayer = function() { this.updateLayer('_groundLayer', $.updateGround, 'grounds', $.Param.groundLayerFileName, 'ground', 1, 0); $.updateGround = false; }; Spriteset_Map.prototype.updateParallaxLayer = function() { this.updateLayer('_parallaxLayer', $.updateParallax, 'pars', $.Param.parallaxLayerFileName, 'par', 20, $.Param.parallaxSwitchId); $.updateParallax = false; }; Spriteset_Map.prototype.updateShadowLayer = function() { this.updateLayer('_shadowLayer', $.updateShadow, 'shadows', $.Param.shadowLayerFileName, 'shadow', 21, $.Param.shadowSwitchId); $.updateShadow = false; }; Spriteset_Map.prototype.updateFogItem = function(id) { var data = this._fogList[id]; if (!data) return; data.newX += data.xMove; data.newY += data.yMove; data.sprite.origin.x = $gameMap.displayX() * $gameMap.tileWidth() - data.newX; data.sprite.origin.y = $gameMap.displayY() * $gameMap.tileHeight() - data.newY; }; Spriteset_Map.prototype.removeFogItem = function(id) { if (!this._fogList[id]) return; delete this._fogList[id]; }; Spriteset_Map.prototype.updateFogLayer = function() { if (!this._fogLayer) { this.createFogLayer(); if (!this._fogLayer) { return; } } var newOpacity; this._fogLayer.blendMode = $.fodBlendCommand === 0 ? 0 : 1; if ($.fogMoveXCommand !== 0) { $.fogNewX += $.fogMoveXCommand; } else { $.fogNewX += $.fogMoveX; } if ($.fogMoveYCommand !== 0) { $.fogNewY += $.fogMoveYCommand; } else { $.fogNewY += $.fogMoveY; } this._fogLayer.origin.x = $gameMap.displayX() * $gameMap.tileWidth() - $.fogNewX; this._fogLayer.origin.y = $gameMap.displayY() * $gameMap.tileHeight() - $.fogNewY; if ($.Param.fogSwitchId > 0 && $gameSwitches.value($.Param.fogSwitchId)) { if ($.fogOpacityCommand !== 0) { $.defOpacity = $.fogOpacityCommand; } else { $.defOpacity = $.fogOpacity; } if ($.fogDurationCommand !== 0) { $.defDuration = $.fogDurationCommand; } else { $.defDuration = $.fogDuration; } $.defTransition = $.defOpacity / $.defDuration; } else if (this._fogLayer.opacity > 0) { newOpacity = this._fogLayer.opacity - 10; if (newOpacity < 0) newOpacity = 0; this._fogLayer.opacity = newOpacity; } if ($.overlayFadeOut) { $.defTransition = $.defOpacity / $.fogFadeOut; if (this._fogLayer.opacity > 0) { newOpacity = this._fogLayer.opacity - $.defTransition; if (newOpacity < 0) newOpacity = 0; this._fogLayer.opacity = newOpacity; } else { $.overlayFadeOut = false; $.fogOpacityCommand = 0; $.defOpacity = 0; if ($.Param.fogSwitchId > 0) { $gameSwitches.setValue($.Param.fogSwitchId, false); } } } else if (this._fogLayer.opacity < $.defOpacity) { newOpacity = this._fogLayer.opacity + $.defTransition; if (newOpacity > $.defOpacity) newOpacity = $.defOpacity; this._fogLayer.opacity = newOpacity; } if ($.updateFog && !!$.fogFileNameCommand && $.fogFileNameCommand !== '') { this._fogLayer.bitmap = this.loadBitmap('fogs', $.fogFileNameCommand); $.updateFog = false; } }; Spriteset_Map.prototype.updateLightLayer = function() { this.updateLayer('_lightLayer', $.updateLight, 'lights', $.Param.lightLayerFileName, 'light', 23, $.Param.lightSwitchId, $.Param.lightOpacity, 1); $.updateLight = false; }; var oldSpritesetMap_updateTilemap = Spriteset_Map.prototype.updateTilemap; Spriteset_Map.prototype.updateTilemap = function() { this.updateGroundLayer(); this.updateParallaxLayer(); this.updateShadowLayer(); this.updateFogLayer(); this.updateLightLayer(); oldSpritesetMap_updateTilemap.call(this); var len = this._fogList.length; if (len > 0) { for (var i = 0; i < len; i++) { if (!!this._fogList[i]) { this.updateFogItem(i); } } } if ($.newFogToCreate) { this.createFogItem($.newFogId, $.newFogName, $.newFogXMove, $.newFogYMove, $.newFogOpacity, $.newFogBlend, $.newFogZ); $.newFogToCreate = false; } if ($.fogToRemove > 0) { this.removeFogItem($.fogToRemove); $.fogToRemove = 0; } }; Game_Interpreter.prototype.overlayPluginCommand = function(args) { if (args.length < 2) return; switch(args[0].toLowerCase()) { case 'fog' : if (args.length < 5) return; if (!!args[1] && !!args[2] && !!args[3] && !!args[4]) { $.updateFog = true; $.fogFileNameCommand = args[1]; $.fogOpacityCommand = parseInt(args[2], 10); $.fogMoveXCommand = parseFloat(args[3], 10); $.fogMoveYCommand = parseFloat(args[4], 10); if (args.length > 5 && !!args[5]) { $.fodBlendCommand = parseInt(args[5], 10); } if (args.length > 6 && !!args[6]) { $.fogDurationCommand = parseInt(args[6], 10); } } break; case 'fadeout' : if (!!args[1]) { $.overlayFadeOut = true; $.fogFadeOut = parseInt(args[1], 10); } break; case 'light' : if (!!args[1]) { $.updateLight = true; $.lightName = args[1]; } break; case 'shadow' : if (!!args[1]) { $.updateShadow = true; $.shadowName = args[1]; } break; case 'par' : if (!!args[1]) { $.updateParallax = true; $.parallaxName = args[1]; } break; case 'ground' : if (!!args[1]) { $.updateGround = true; $.groundName = args[1]; } break; case 'addfog' : if (args.length < 6) return; if (!args[1]) return; $.newFogToCreate = true; $.newFogName = args[1]; $.newFogId = parseInt(args[2], 10); $.newFogOpacity = parseInt(args[3], 10); $.newFogXMove = parseFloat(args[4], 10); $.newFogYMove = parseFloat(args[5], 10); if (args.length > 6) { $.newFogBlend = parseInt(args[6], 10); } else { $.newFogBlend = 0; } if (args.length > 7) { $.newFogZ = parseInt(args[7], 10); } else { $.newFogZ = 22; } break; case 'removefog' : $.fogToRemove = parseInt(args[1], 10); break; default : console.log('unknown command: ', args[0]); break; } }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function (command, args) { if (command.toLowerCase() == 'overlay') { this.overlayPluginCommand(args); return; } oldGameInterpreter_pluginCommand.apply(this, arguments); }; if ($.Param.bushRegionId > 0) { var oldIsBush = Game_Map.prototype.isBush; Game_Map.prototype.isBush = function(x, y) { if (oldIsBush.call(this, x, y) === true) return true; if (this.isValid(x, y)) { return $gameMap.regionId(x, y) == $.Param.bushRegionId; } return false; }; } if (!!Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION == "1.2.0") { TilingSprite.prototype.generateTilingTexture = function(arg) { PIXI.TilingSprite.prototype.generateTilingTexture.call(this, arg); // Purge from Pixi's Cache if (Graphics.isWebGL()) { if (!!this.tilingTexture && this.tilingTexture.canvasBuffer) { PIXI.Texture.removeTextureFromCache(this.tilingTexture.canvasBuffer.canvas._pixiId); } } }; } var oldSpriteCharacter_startBallon = Sprite_Character.prototype.startBalloon; Sprite_Character.prototype.startBalloon = function() { oldSpriteCharacter_startBallon.call(this); if (!!this._balloonSprite) { this._balloonSprite.z = 30; } }; var oldSpriteAnimation_initMembers = Sprite_Animation.prototype.initMembers; Sprite_Animation.prototype.initMembers = function() { oldSpriteAnimation_initMembers.apply(this, arguments); this.z = 30; }; })(Hudell.OrangeOverlay); OrangeOverlay = Hudell.OrangeOverlay; Imported.OrangeOverlay = 1.1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Region Collisions * By Hudell - www.hudell.com * OrangeRegionCollisions.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allows the usage of regions to overwrite the passability configuration of tiles * @author Hudell * * @param BlockRegionId * @desc The ID of the region that should be used to block passage on a tile * @default 0 * * @param UnblockRegionId * @desc The ID of the region that should be used to unblock passage on a tile * @default 0 * * @param BlockPlayerRegionId * @desc The ID of the region that should be used to block passage of the player on a tile * @default 0 * * @param UnblockPlayerRegionId * @desc The ID of the region that should be used to unblock passage of the player on a tile * @default 0 * * @param BlockEventRegionId * @desc The ID of the region that should be used to block passage of events on a tile * @default 0 * * @param UnblockEventRegionId * @desc The ID of the region that should be used to unblock passage of events on a tile * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://download.hudell.com/OrangeRegionCollisions.js * *=============================================================================*/ var Imported = Imported || {}; var OrangeRegionCollisions = OrangeRegionCollisions || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeRegionCollisions'); $.Param = $.Param || {}; $.Param.BlockRegionId = Number($.Parameters.BlockRegionId || 0); $.Param.UnblockRegionId = Number($.Parameters.UnblockRegionId || 0); $.Param.BlockPlayerRegionId = Number($.Parameters.BlockPlayerRegionId || 0); $.Param.UnblockPlayerRegionId = Number($.Parameters.UnblockPlayerRegionId || 0); $.Param.BlockEventRegionId = Number($.Parameters.BlockEventRegionId || 0); $.Param.UnblockEventRegionId = Number($.Parameters.UnblockEventRegionId || 0); var oldGame_Map_checkPassage = Game_Map.prototype.checkPassage; Game_Map.prototype.checkPassage = function(x, y, bit) { if ($.Param.BlockRegionId > 0 || $.Param.UnblockRegionId > 0) { var regionId = this.regionId(x, y); if (regionId > 0) { if ($.Param.BlockRegionId > 0 && regionId == $.Param.BlockRegionId) { return false; } if ($.Param.UnblockRegionId > 0 && regionId == $.Param.UnblockRegionId) { return true; } } } return oldGame_Map_checkPassage.call(this, x, y, bit); }; var oldGameEvent_isMapPassable = Game_Event.prototype.isMapPassable; Game_Event.prototype.isMapPassable = function(x, y, d) { if ($.Param.BlockEventRegionId > 0 || $.Param.UnblockRegionId > 0) { var new_x = $gameMap.roundXWithDirection(x, d); var new_y = $gameMap.roundYWithDirection(y, d); var regionId = $gameMap.regionId(new_x, new_y); if (regionId > 0) { if ($.Param.BlockEventRegionId > 0 && regionId == $.Param.BlockEventRegionId) { return false; } if ($.Param.UnblockRegionId > 0 && regionId == $.Param.UnblockRegionId) { return true; } } } return oldGameEvent_isMapPassable.call(this, x, y, d); }; var oldGamePlayer_isMapPassable = Game_Player.prototype.isMapPassable; if (Imported.SuperOrangeMovement !== undefined || Imported.SuperOrangeMovementEx !== undefined) { var insignificantValue = 0.000001; $.runForAllPositions = function(x, y, callback) { var first_x = (x + this.hitboxXSize).floor(); var last_x = (x + this.hitboxXSize + this.hitboxWidthSize - insignificantValue).floor(); var first_y = (y + this.hitboxYSize).floor(); var last_y = (y + this.hitboxYSize + this.hitboxHeightSize - insignificantValue).floor(); for (var new_x = first_x; new_x <= last_x; new_x++) { for (var new_y = first_y; new_y <= last_y; new_y++) { var result = callback.call(this, new_x, new_y); if (result === true) return true; if (result === false) return false; } } return null; }; $.checkPlayerRegionCollision = function(x, y) { var regionId = $gameMap.regionId(x, y); if (regionId > 0) { if ($.Param.BlockPlayerRegionId > 0 && regionId == $.Param.BlockPlayerRegionId) { return false; } if ($.Param.UnblockRegionId > 0 && regionId == $.Param.UnblockRegionId) { return true; } } return null; }; Game_Player.prototype.isMapPassable = function(x, y, d) { if ($.Param.BlockPlayerRegionId > 0 || $.Param.UnblockRegionId > 0) { var new_x = $gameMap.roundFractionXWithDirection(x, d); var new_y = $gameMap.roundFractionYWithDirection(y, d); var result = $.runForAllPositions.call(this, new_x, new_y, $.checkPlayerRegionCollision); if (result === true) return true; if (result === false) return false; } return oldGamePlayer_isMapPassable.call(this, x, y, d); }; } else { Game_Player.prototype.isMapPassable = function(x, y, d) { if ($.Param.BlockPlayerRegionId > 0 || $.Param.UnblockRegionId > 0) { var new_x = $gameMap.roundXWithDirection(x, d); var new_y = $gameMap.roundYWithDirection(y, d); var regionId = $gameMap.regionId(new_x, new_y); if (regionId > 0) { if ($.Param.BlockPlayerRegionId > 0 && regionId == $.Param.BlockPlayerRegionId) { return false; } if ($.Param.UnblockRegionId > 0 && regionId == $.Param.UnblockRegionId) { return true; } } } return oldGamePlayer_isMapPassable.call(this, x, y, d); }; } })(OrangeRegionCollisions); Imported.OrangeRegionCollisions = 1.2;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Event Hitboxes * By Hudell - www.hudell.com * OrangeEventHitboxes.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allows the configuration of custom hitboxes for events * @author Hudell * @help * ============================================================================ * Instructions * ============================================================================ * This plugin REQUIRES MVCommons: http://link.hudell.com/mvcommons * * There are 4 tags that can be used to configure the event hitboxes: * <hitboxX:0> * <hitboxY:0> * <hitboxWidth:1> * <hitboxHeight:1> * * The hitboxX and hitboxY tags are used to relocate the top left position of * the hitbox. The default value is 0 * The hitboxWidth and hitboxHeight tags are used to resize the hitbox. The * default value is 1. * * All values are on tiles. If you change hitboxX to -1: * <hitboxX:-1> * then the hitbox will start one tile to left of where it would usually start * * Those tags can be added to the event notes. If you want a different * size for a specific page, you can add those tags on a comment on that page * and the plugin will understand that it should use that configuration * for that specific page. * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/event-hitboxes * */ var Imported = Imported || {}; if (Imported.MVCommons === undefined) { var MVC = MVC || {}; (function($){ $.defaultGetter = function(name) { return function () { return this['_' + name]; }; }; $.defaultSetter = function(name) { return function (value) { var prop = '_' + name; if ((!this[prop]) || this[prop] !== value) { this[prop] = value; if (this._refresh) { this._refresh(); } } }; }; $.accessor = function(value, name /* , setter, getter */) { Object.defineProperty(value, name, { get: arguments.length > 3 ? arguments[3] : $.defaultGetter(name), set: arguments.length > 2 ? arguments[2] : $.defaultSetter(name), configurable: true });}; $.reader = function(obj, name /*, getter */) { Object.defineProperty(obj, name, { get: arguments.length > 2 ? arguments[2] : defaultGetter(name), configurable: true }); }; $.getProp = function(meta, propName){ if (meta === undefined) return undefined; if (meta[propName] !== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; $.extractEventMeta = function(event) { var the_event = event; if (the_event instanceof Game_Event) { the_event = event.event(); } var pages = the_event.pages; if (pages === undefined) return; var re = /<([^<>:]+)(:?)([^>]*)>/g; for (var i = 0; i < pages.length; i++) { var page = pages[i]; page.meta = page.meta || {}; for (var j = 0; j < page.list.length; j++) { var command = page.list[j]; if (command.code !== 108 && command.code !== 408) continue; for (;;) { var match = re.exec(command.parameters[0]); if (match) { if (match[2] === ':') { page.meta[match[1]] = match[3]; } else { page.meta[match[1]] = true; } } else { break; } } } } }; })(MVC); Number.prototype.fix = function() { return parseFloat(this.toPrecision(12)); }; Number.prototype.floor = function() { return Math.floor(this.fix()); }; } var OrangeEventHitboxes = OrangeEventHitboxes || {}; (function($) { "use strict"; // Creates an accessor for the hitboxX property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 0. MVC.accessor(Game_Event.prototype, 'hitboxX', function(value) { this._hitboxX = value; this._canClearHitboxX = false; }, function() { if (this._hitboxX === undefined) { var size = this.findNoteTagValue('hitboxX'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxX = size; } else { this._hitboxX = 0; } this._canClearHitboxX = true; } return this._hitboxX; }); // Creates an accessor for the hitboxY property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 0. MVC.accessor(Game_Event.prototype, 'hitboxY', function(value) { this._hitboxY = value; this._canClearHitboxY = false; }, function() { if (this._hitboxY === undefined) { var size = this.findNoteTagValue('hitboxY'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxY = size; } else { this._hitboxY = 0; } this._canClearHitboxY = true; } return this._hitboxY; }); // Creates an accessor for the hitboxWidth property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 1. MVC.accessor(Game_Event.prototype, 'hitboxWidth', function(value) { this._hitboxWidth = value; this._canClearHitboxWidth = false; }, function() { if (this._hitboxWidth === undefined) { var size = this.findNoteTagValue('hitboxWidth'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxWidth = size; } else { this._hitboxWidth = 1; } this._canClearHitboxWidth = true; } return this._hitboxWidth; }); // Creates an accessor for the hitboxHeight property, // It's value is read from the notetags and then cached. It can also be changed // manually. Default is 1. MVC.accessor(Game_Event.prototype, 'hitboxHeight', function(value) { this._hitboxHeight = value; this._canClearHitboxHeight = false; }, function() { if (this._hitboxHeight === undefined) { var size = this.findNoteTagValue('hitboxHeight'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxHeight = size; } else { this._hitboxHeight = 1; } this._canClearHitboxHeight = true; } return this._hitboxHeight; }); // Quick reader for the left position of the hitbox MVC.reader(Game_Event.prototype, 'left', function() { return (this._x + this.hitboxX).fix(); }); // Quick reader for the top position of the hitbox MVC.reader(Game_Event.prototype, 'top', function() { return (this._y + this.hitboxY).fix(); }); // Quick reader for the right position of the hitbox MVC.reader(Game_Event.prototype, 'right', function() { return (this.left + this.hitboxWidth).fix(); }); // Quick reader for the bottom position of the hitbox MVC.reader(Game_Event.prototype, 'bottom', function() { return (this.top + this.hitboxHeight).fix(); }); // Adds a method that searches for a notetag value on all comments of the page Game_Event.prototype.findNoteTagValue = function(notetag) { var page = this.page(); if (page === undefined) return false; if (page.meta === undefined) { MVC.extractEventMeta(this); } var result; if (page.meta !== undefined) { result = MVC.getProp(page.meta, notetag); } if (result === undefined) { return MVC.getProp(this.event().meta, notetag); } else { return result; } }; // Adds a method that checks if the event is using the default hitbox, // in which case some methods don't need to be changed. Game_Event.prototype.isUsingDefaultHitbox = function() { return (this.hitboxX === 0 && this.hitboxY === 0 && this.hitboxWidth === 1 && this.hitboxHeight === 1); }; // Alias the method pos of the Game_Event class to check if the event // is on a specified position. If the event hitbox wasn't changed, the old // method is run instead. var oldGameEvent_pos = Game_Event.prototype.pos; Game_Event.prototype.pos = function(x, y) { if (this.isUsingDefaultHitbox()) { return oldGameEvent_pos.call(this, x, y); } else { return (x >= this.left && x < this.right && y >= this.top && y < this.bottom); } }; // Alias the setupPage method from the Game_Event class to clear the // hitbox cache (because the event can use a different cache for each page) var oldGameEvent_setupPage = Game_Event.prototype.setupPage; Game_Event.prototype.setupPage = function() { oldGameEvent_setupPage.call(this); if (this._canClearHitboxX === true) this._hitboxX = undefined; if (this._canClearHitboxY === true) this._hitboxY = undefined; if (this._canClearHitboxHeight === true) this._hitboxHeight = undefined; if (this._canClearHitboxWidth === true) this._hitboxWidth = undefined; }; })(OrangeEventHitboxes); Imported.OrangeEventHitboxes = 1.1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - DisableRefresh * By Hudell - www.hudell.com * OrangeDisableRefresh.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Disables F5 Refresh <OrangeDisableRefresh> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeDisableRefresh = Hudell.OrangeDisableRefresh || {}; (function($) { $.oldSceneManager_onKeyDown = SceneManager.onKeyDown; SceneManager.onKeyDown = function(event) { if (event.keyCode == 116) return; $.oldSceneManager_onKeyDown.call(this, event); }; })(Hudell.OrangeDisableRefresh); OrangeDisableRefresh = Hudell.OrangeDisableRefresh; Imported.OrangeDisableRefresh = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - RegionNames * By Hudell - www.hudell.com * OrangeRegionNames.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Displays the name of the region the player is currently walking on <OrangeRegionNames> * @author Hudell * * @param 1 * @desc The name of the region 1 * @default * * @param 2 * @desc The name of the region 2 * @default * * @param 3 * @desc The name of the region 3 * @default * * @param 4 * @desc The name of the region 4 * @default * * @param 5 * @desc The name of the region 5 * @default * * @param 6 * @desc The name of the region 6 * @default * * @param 7 * @desc The name of the region 7 * @default * * @param 8 * @desc The name of the region 8 * @default * * @param 9 * @desc The name of the region 9 * @default * * @param 10 * @desc The name of the region 10 * @default * * @param 11 * @desc The name of the region 11 * @default * * @param 12 * @desc The name of the region 12 * @default * * @param 13 * @desc The name of the region 13 * @default * * @param 14 * @desc The name of the region 14 * @default * * @param 15 * @desc The name of the region 15 * @default * * @param 16 * @desc The name of the region 16 * @default * * @param 17 * @desc The name of the region 17 * @default * * @param 18 * @desc The name of the region 18 * @default * * @param 19 * @desc The name of the region 19 * @default * * @param 20 * @desc The name of the region 20 * @default * * @param 21 * @desc The name of the region 21 * @default * * @param 22 * @desc The name of the region 22 * @default * * @param 23 * @desc The name of the region 23 * @default * * @param 24 * @desc The name of the region 24 * @default * * @param 25 * @desc The name of the region 25 * @default * * @param 26 * @desc The name of the region 26 * @default * * @param 27 * @desc The name of the region 27 * @default * * @param 28 * @desc The name of the region 28 * @default * * @param 29 * @desc The name of the region 29 * @default * * @param 30 * @desc The name of the region 30 * @default * * @param 31 * @desc The name of the region 31 * @default * * @param 32 * @desc The name of the region 32 * @default * * @param 33 * @desc The name of the region 33 * @default * * @param 34 * @desc The name of the region 34 * @default * * @param 35 * @desc The name of the region 35 * @default * * @param 36 * @desc The name of the region 36 * @default * * @param 37 * @desc The name of the region 37 * @default * * @param 38 * @desc The name of the region 38 * @default * * @param 39 * @desc The name of the region 39 * @default * * @param 40 * @desc The name of the region 40 * @default * * @param 41 * @desc The name of the region 41 * @default * * @param 42 * @desc The name of the region 42 * @default * * @param 43 * @desc The name of the region 43 * @default * * @param 44 * @desc The name of the region 44 * @default * * @param 45 * @desc The name of the region 45 * @default * * @param 46 * @desc The name of the region 46 * @default * * @param 47 * @desc The name of the region 47 * @default * * @param 48 * @desc The name of the region 48 * @default * * @param 49 * @desc The name of the region 49 * @default * * @param 50 * @desc The name of the region 50 * @default * * @param 51 * @desc The name of the region 51 * @default * * @param 52 * @desc The name of the region 52 * @default * * @param 53 * @desc The name of the region 53 * @default * * @param 54 * @desc The name of the region 54 * @default * * @param 55 * @desc The name of the region 55 * @default * * @param 56 * @desc The name of the region 56 * @default * * @param 57 * @desc The name of the region 57 * @default * * @param 58 * @desc The name of the region 58 * @default * * @param 59 * @desc The name of the region 59 * @default * * @param 60 * @desc The name of the region 60 * @default * * @param 61 * @desc The name of the region 61 * @default * * @param 62 * @desc The name of the region 62 * @default * * @param 63 * @desc The name of the region 63 * @default * * @param 64 * @desc The name of the region 64 * @default * * @param 65 * @desc The name of the region 65 * @default * * @param 66 * @desc The name of the region 66 * @default * * @param 67 * @desc The name of the region 67 * @default * * @param 68 * @desc The name of the region 68 * @default * * @param 69 * @desc The name of the region 69 * @default * * @param 70 * @desc The name of the region 70 * @default * * @param 71 * @desc The name of the region 71 * @default * * @param 72 * @desc The name of the region 72 * @default * * @param 73 * @desc The name of the region 73 * @default * * @param 74 * @desc The name of the region 74 * @default * * @param 75 * @desc The name of the region 75 * @default * * @param 76 * @desc The name of the region 76 * @default * * @param 77 * @desc The name of the region 77 * @default * * @param 78 * @desc The name of the region 78 * @default * * @param 79 * @desc The name of the region 79 * @default * * @param 80 * @desc The name of the region 80 * @default * * @param 81 * @desc The name of the region 81 * @default * * @param 82 * @desc The name of the region 82 * @default * * @param 83 * @desc The name of the region 83 * @default * * @param 84 * @desc The name of the region 84 * @default * * @param 85 * @desc The name of the region 85 * @default * * @param 86 * @desc The name of the region 86 * @default * * @param 87 * @desc The name of the region 87 * @default * * @param 88 * @desc The name of the region 88 * @default * * @param 89 * @desc The name of the region 89 * @default * * @param 90 * @desc The name of the region 90 * @default * * @param 91 * @desc The name of the region 91 * @default * * @param 92 * @desc The name of the region 92 * @default * * @param 93 * @desc The name of the region 93 * @default * * @param 94 * @desc The name of the region 94 * @default * * @param 95 * @desc The name of the region 95 * @default * * @param 96 * @desc The name of the region 96 * @default * * @param 97 * @desc The name of the region 97 * @default * * @param 98 * @desc The name of the region 98 * @default * * @param 99 * @desc The name of the region 99 * @default * * @param 00 * @desc The name of the region 00 * @default * * @param 101 * @desc The name of the region 101 * @default * * @param 102 * @desc The name of the region 102 * @default * * @param 103 * @desc The name of the region 103 * @default * * @param 104 * @desc The name of the region 104 * @default * * @param 105 * @desc The name of the region 105 * @default * * @param 106 * @desc The name of the region 106 * @default * * @param 107 * @desc The name of the region 107 * @default * * @param 108 * @desc The name of the region 108 * @default * * @param 109 * @desc The name of the region 109 * @default * * @param 110 * @desc The name of the region 110 * @default * * @param 111 * @desc The name of the region 111 * @default * * @param 112 * @desc The name of the region 112 * @default * * @param 113 * @desc The name of the region 113 * @default * * @param 114 * @desc The name of the region 114 * @default * * @param 115 * @desc The name of the region 115 * @default * * @param 116 * @desc The name of the region 116 * @default * * @param 117 * @desc The name of the region 117 * @default * * @param 118 * @desc The name of the region 118 * @default * * @param 119 * @desc The name of the region 119 * @default * * @param 120 * @desc The name of the region 120 * @default * * @param 121 * @desc The name of the region 121 * @default * * @param 122 * @desc The name of the region 122 * @default * * @param 123 * @desc The name of the region 123 * @default * * @param 124 * @desc The name of the region 124 * @default * * @param 125 * @desc The name of the region 125 * @default * * @param 126 * @desc The name of the region 126 * @default * * @param 127 * @desc The name of the region 127 * @default * * @param 128 * @desc The name of the region 128 * @default * * @param 129 * @desc The name of the region 129 * @default * * @param 130 * @desc The name of the region 130 * @default * * @param 131 * @desc The name of the region 131 * @default * * @param 132 * @desc The name of the region 132 * @default * * @param 133 * @desc The name of the region 133 * @default * * @param 134 * @desc The name of the region 134 * @default * * @param 135 * @desc The name of the region 135 * @default * * @param 136 * @desc The name of the region 136 * @default * * @param 137 * @desc The name of the region 137 * @default * * @param 138 * @desc The name of the region 138 * @default * * @param 139 * @desc The name of the region 139 * @default * * @param 140 * @desc The name of the region 140 * @default * * @param 141 * @desc The name of the region 141 * @default * * @param 142 * @desc The name of the region 142 * @default * * @param 143 * @desc The name of the region 143 * @default * * @param 144 * @desc The name of the region 144 * @default * * @param 145 * @desc The name of the region 145 * @default * * @param 146 * @desc The name of the region 146 * @default * * @param 147 * @desc The name of the region 147 * @default * * @param 148 * @desc The name of the region 148 * @default * * @param 149 * @desc The name of the region 149 * @default * * @param 150 * @desc The name of the region 150 * @default * * @param 151 * @desc The name of the region 151 * @default * * @param 152 * @desc The name of the region 152 * @default * * @param 153 * @desc The name of the region 153 * @default * * @param 154 * @desc The name of the region 154 * @default * * @param 155 * @desc The name of the region 155 * @default * * @param 156 * @desc The name of the region 156 * @default * * @param 157 * @desc The name of the region 157 * @default * * @param 158 * @desc The name of the region 158 * @default * * @param 159 * @desc The name of the region 159 * @default * * @param 160 * @desc The name of the region 160 * @default * * @param 161 * @desc The name of the region 161 * @default * * @param 162 * @desc The name of the region 162 * @default * * @param 163 * @desc The name of the region 163 * @default * * @param 164 * @desc The name of the region 164 * @default * * @param 165 * @desc The name of the region 165 * @default * * @param 166 * @desc The name of the region 166 * @default * * @param 167 * @desc The name of the region 167 * @default * * @param 168 * @desc The name of the region 168 * @default * * @param 169 * @desc The name of the region 169 * @default * * @param 170 * @desc The name of the region 170 * @default * * @param 171 * @desc The name of the region 171 * @default * * @param 172 * @desc The name of the region 172 * @default * * @param 173 * @desc The name of the region 173 * @default * * @param 174 * @desc The name of the region 174 * @default * * @param 175 * @desc The name of the region 175 * @default * * @param 176 * @desc The name of the region 176 * @default * * @param 177 * @desc The name of the region 177 * @default * * @param 178 * @desc The name of the region 178 * @default * * @param 179 * @desc The name of the region 179 * @default * * @param 180 * @desc The name of the region 180 * @default * * @param 181 * @desc The name of the region 181 * @default * * @param 182 * @desc The name of the region 182 * @default * * @param 183 * @desc The name of the region 183 * @default * * @param 184 * @desc The name of the region 184 * @default * * @param 185 * @desc The name of the region 185 * @default * * @param 186 * @desc The name of the region 186 * @default * * @param 187 * @desc The name of the region 187 * @default * * @param 188 * @desc The name of the region 188 * @default * * @param 189 * @desc The name of the region 189 * @default * * @param 190 * @desc The name of the region 190 * @default * * @param 191 * @desc The name of the region 191 * @default * * @param 192 * @desc The name of the region 192 * @default * * @param 193 * @desc The name of the region 193 * @default * * @param 194 * @desc The name of the region 194 * @default * * @param 195 * @desc The name of the region 195 * @default * * @param 196 * @desc The name of the region 196 * @default * * @param 197 * @desc The name of the region 197 * @default * * @param 198 * @desc The name of the region 198 * @default * * @param 199 * @desc The name of the region 199 * @default * * @param 200 * @desc The name of the region 200 * @default * * @param 201 * @desc The name of the region 201 * @default * * @param 202 * @desc The name of the region 202 * @default * * @param 203 * @desc The name of the region 203 * @default * * @param 204 * @desc The name of the region 204 * @default * * @param 205 * @desc The name of the region 205 * @default * * @param 206 * @desc The name of the region 206 * @default * * @param 207 * @desc The name of the region 207 * @default * * @param 208 * @desc The name of the region 208 * @default * * @param 209 * @desc The name of the region 209 * @default * * @param 210 * @desc The name of the region 210 * @default * * @param 211 * @desc The name of the region 211 * @default * * @param 212 * @desc The name of the region 212 * @default * * @param 213 * @desc The name of the region 213 * @default * * @param 214 * @desc The name of the region 214 * @default * * @param 215 * @desc The name of the region 215 * @default * * @param 216 * @desc The name of the region 216 * @default * * @param 217 * @desc The name of the region 217 * @default * * @param 218 * @desc The name of the region 218 * @default * * @param 219 * @desc The name of the region 219 * @default * * @param 220 * @desc The name of the region 220 * @default * * @param 221 * @desc The name of the region 221 * @default * * @param 222 * @desc The name of the region 222 * @default * * @param 223 * @desc The name of the region 223 * @default * * @param 224 * @desc The name of the region 224 * @default * * @param 225 * @desc The name of the region 225 * @default * * @param 226 * @desc The name of the region 226 * @default * * @param 227 * @desc The name of the region 227 * @default * * @param 228 * @desc The name of the region 228 * @default * * @param 229 * @desc The name of the region 229 * @default * * @param 230 * @desc The name of the region 230 * @default * * @param 231 * @desc The name of the region 231 * @default * * @param 232 * @desc The name of the region 232 * @default * * @param 233 * @desc The name of the region 233 * @default * * @param 234 * @desc The name of the region 234 * @default * * @param 235 * @desc The name of the region 235 * @default * * @param 236 * @desc The name of the region 236 * @default * * @param 237 * @desc The name of the region 237 * @default * * @param 238 * @desc The name of the region 238 * @default * * @param 239 * @desc The name of the region 239 * @default * * @param 240 * @desc The name of the region 240 * @default * * @param 241 * @desc The name of the region 241 * @default * * @param 242 * @desc The name of the region 242 * @default * * @param 243 * @desc The name of the region 243 * @default * * @param 244 * @desc The name of the region 244 * @default * * @param 245 * @desc The name of the region 245 * @default * * @param 246 * @desc The name of the region 246 * @default * * @param 247 * @desc The name of the region 247 * @default * * @param 248 * @desc The name of the region 248 * @default * * @param 249 * @desc The name of the region 249 * @default * * @param 250 * @desc The name of the region 250 * @default * * @param 251 * @desc The name of the region 251 * @default * * @param 252 * @desc The name of the region 252 * @default * * @param 253 * @desc The name of the region 253 * @default * * @param 254 * @desc The name of the region 254 * @default * * @param 255 * @desc The name of the region 255 * @default * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeRegionNames = Hudell.OrangeRegionNames || {}; function Window_RegionName() { this.initialize.apply(this, arguments); } Window_RegionName.prototype = Object.create(Window_MapName.prototype); Window_RegionName.prototype.constructor = Window_RegionName; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeRegionNames>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeRegionNames parameters."); } $.Parameters = parameters[0].parameters; $.RegionNames = {}; for (var i = 1; i <= 255; i++) { $.RegionNames[i] = $.Parameters[i] || ""; } $.getRegionName = function(regionId) { return ($.RegionNames[regionId] || "").trim(); }; Window_RegionName.prototype.refresh = function() { this.contents.clear(); var regionId = this._currentRegionId || 0; // var regionId = $gameMap.regionId($gamePlayer._x, $gamePlayer._y); if (regionId > 0) { var regionName = $.getRegionName(regionId); if (regionName) { var width = this.contentsWidth(); this.drawBackground(0, 0, width, this.lineHeight()); this.drawText(regionName, 0, 0, width, 'center'); } } }; Window_RegionName.prototype.update = function() { var regionId = $gameMap.regionId($gamePlayer._x, $gamePlayer._y); if (regionId !== this._currentRegionId) { this._currentRegionId = regionId; this.open(); } else { Window_MapName.prototype.update.call(this); } }; Scene_Map.prototype.createRegionNameWindow = function(){ this._regionNameWindow = new Window_RegionName(); this.addChild(this._regionNameWindow); }; $.oldSceneMap_createMapNameWindow = Scene_Map.prototype.createMapNameWindow; Scene_Map.prototype.createMapNameWindow = function() { $.oldSceneMap_createMapNameWindow.call(this); this.createRegionNameWindow.call(this); }; $.oldSceneMap_updateTransferPlayer = Scene_Map.prototype.updateTransferPlayer; Scene_Map.prototype.updateTransferPlayer = function() { if ($gamePlayer.isTransferring()) { this._regionNameWindow.close(); } $.oldSceneMap_updateTransferPlayer.call(this); this._regionNameWindow.update(); }; $.oldSceneMap_callMenu = Scene_Map.prototype.callMenu; Scene_Map.prototype.callMenu = function() { $.oldSceneMap_callMenu.call(this); this._regionNameWindow.hide(); }; $.oldSceneMap_launchBattle = Scene_Map.prototype.launchBattle; Scene_Map.prototype.launchBattle = function() { $.oldSceneMap_launchBattle.call(this); this._regionNameWindow.hide(); }; $.oldSceneMap_stop = Scene_Map.prototype.stop; Scene_Map.prototype.stop = function() { this._regionNameWindow.close(); $.oldSceneMap_stop.call(this); }; })(Hudell.OrangeRegionNames); OrangeRegionNames = Hudell.OrangeRegionNames; Imported["OrangeRegionNames"] = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Anti Lag * By Hudell - www.hudell.com * OrangeAntiLag.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Improves part of RM code to reduce lag * @author Hudell */ var Imported = Imported || {}; var OrangeAntiLag = OrangeAntiLag || {}; (function($) { "use strict"; // Replaces the original refreshTileEvents to filter the _events array directly Game_Map.prototype.refreshTileEvents = function() { this.tileEvents = this._events.filter(function(event) { return !!event && event.isTile(); }); }; // Replaces the original eventsXy to filter the _events array directly Game_Map.prototype.eventsXy = function(x, y) { return this._events.filter(function(event) { return !!event && event.pos(x, y); }); }; // Replaces the original eventsXyNt to filter the _events array directly Game_Map.prototype.eventsXyNt = function(x, y) { return this._events.filter(function(event) { return !!event && event.posNt(x, y); }); }; // Make Tilemap class sort sprites only when needed Game_Temp.prototype.canSortTileMapChildren = function() { return !!this._zOrderChanged; }; Game_Temp.prototype.markZOrderChanged = function() { this._zOrderChanged = true; }; Game_Temp.prototype.clearZOrderChanged = function() { this._zOrderChanged = false; }; var oldGameTempInitialize = Game_Temp.prototype.initialize; Game_Temp.prototype.initialize = function() { oldGameTempInitialize.call(this); this._zOrderChanged = false; }; var oldTileMapSortChildren = Tilemap.prototype._sortChildren; Tilemap.prototype._sortChildren = function() { if ($gameTemp.canSortTileMapChildren()) { oldTileMapSortChildren.call(this); $gameTemp.clearZOrderChanged(); } }; var oldSpriteCharacterUpdatePosition = Sprite_Character.prototype.updatePosition; Sprite_Character.prototype.updatePosition = function() { if (this.z !== this._character.screenZ() || this.y !== this._character.screenY()) { $gameTemp.markZOrderChanged(); } oldSpriteCharacterUpdatePosition.call(this); }; Window.prototype._refreshBack = function() { var m = this._margin; var w = this._width - m * 2; var h = this._height - m * 2; var bitmap = this._windowBackSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w, h); } else if (bitmap.width !== w || bitmap.height !== h) { bitmap.resize(w, h); } this._windowBackSprite.bitmap = bitmap; this._windowBackSprite.setFrame(0, 0, w, h); this._windowBackSprite.move(m, m); if (w > 0 && h > 0 && this._windowskin) { var p = 96; bitmap.bltImage(this._windowskin, 0, 0, p, p, 0, 0, w, h); for (var y = 0; y < h; y += p) { for (var x = 0; x < w; x += p) { bitmap.bltImage(this._windowskin, 0, p, p, p, x, y, p, p); } } var tone = this._colorTone; bitmap.adjustTone(tone[0], tone[1], tone[2]); } }; Window.prototype._refreshFrame = function() { var w = this._width; var h = this._height; var m = 24; var bitmap = this._windowFrameSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w, h); } else if (bitmap.width != w || bitmap.height != h) { bitmap.resize(w, h); } this._windowFrameSprite.bitmap = bitmap; this._windowFrameSprite.setFrame(0, 0, w, h); if (w > 0 && h > 0 && this._windowskin) { var skin = this._windowskin; var p = 96; var q = 96; bitmap.bltImage(skin, p+m, 0+0, p-m*2, m, m, 0, w-m*2, m); bitmap.bltImage(skin, p+m, 0+q-m, p-m*2, m, m, h-m, w-m*2, m); bitmap.bltImage(skin, p+0, 0+m, m, p-m*2, 0, m, m, h-m*2); bitmap.bltImage(skin, p+q-m, 0+m, m, p-m*2, w-m, m, m, h-m*2); bitmap.bltImage(skin, p+0, 0+0, m, m, 0, 0, m, m); bitmap.bltImage(skin, p+q-m, 0+0, m, m, w-m, 0, m, m); bitmap.bltImage(skin, p+0, 0+q-m, m, m, 0, h-m, m, m); bitmap.bltImage(skin, p+q-m, 0+q-m, m, m, w-m, h-m, m, m); } }; Window.prototype._refreshCursor = function() { var pad = this._padding; var x = this._cursorRect.x + pad - this.origin.x; var y = this._cursorRect.y + pad - this.origin.y; var w = this._cursorRect.width; var h = this._cursorRect.height; var m = 4; var x2 = Math.max(x, pad); var y2 = Math.max(y, pad); var ox = x - x2; var oy = y - y2; var w2 = Math.min(w, this._width - pad - x2); var h2 = Math.min(h, this._height - pad - y2); var bitmap = this._windowCursorSprite.bitmap; if (!bitmap) { bitmap = new Bitmap(w2, h2); } else if (bitmap.width !== w2 || bitmap.height !== h2) { bitmap.resize(w2, h2); } this._windowCursorSprite.bitmap = bitmap; this._windowCursorSprite.setFrame(0, 0, w2, h2); this._windowCursorSprite.move(x2, y2); if (w > 0 && h > 0 && this._windowskin) { var skin = this._windowskin; var p = 96; var q = 48; bitmap.bltImage(skin, p+m, p+m, q-m*2, q-m*2, ox+m, oy+m, w-m*2, h-m*2); bitmap.bltImage(skin, p+m, p+0, q-m*2, m, ox+m, oy+0, w-m*2, m); bitmap.bltImage(skin, p+m, p+q-m, q-m*2, m, ox+m, oy+h-m, w-m*2, m); bitmap.bltImage(skin, p+0, p+m, m, q-m*2, ox+0, oy+m, m, h-m*2); bitmap.bltImage(skin, p+q-m, p+m, m, q-m*2, ox+w-m, oy+m, m, h-m*2); bitmap.bltImage(skin, p+0, p+0, m, m, ox+0, oy+0, m, m); bitmap.bltImage(skin, p+q-m, p+0, m, m, ox+w-m, oy+0, m, m); bitmap.bltImage(skin, p+0, p+q-m, m, m, ox+0, oy+h-m, m, m); bitmap.bltImage(skin, p+q-m, p+q-m, m, m, ox+w-m, oy+h-m, m, m); } }; Window_Base.prototype.createContents = function() { var w = this.contentsWidth(); var h = this.contentsHeight(); if (!this.contents) { this.contents = new Bitmap(w, h); } else if (this.contents.width != w || this.contents.height != h) { this.contents.resize(w, h); this.contents.clear(); } else { this.contents.clear(); } this.resetFontSettings(); }; var uniqueMessageWindow = false; Scene_Map.prototype.createMessageWindow = function() { if (uniqueMessageWindow) { this._messageWindow = uniqueMessageWindow; this._messageWindow.openness = 0; this._messageWindow.initMembers(); // this._messageWindow.updatePlacement(); } else { this._messageWindow = new Window_Message(); uniqueMessageWindow = this._messageWindow; } this.addWindow(this._messageWindow); this._messageWindow.subWindows().forEach(function(window) { this.addWindow(window); }, this); }; var uniqueScrollTextWindow = false; Scene_Map.prototype.createScrollTextWindow = function() { if (uniqueScrollTextWindow) { this._scrollTextWindow = uniqueScrollTextWindow; this._scrollTextWindow.opacity = 0; this._scrollTextWindow.hide(); this._scrollTextWindow._text = ''; this._scrollTextWindow._allTextHeight = 0; } else { this._scrollTextWindow = new Window_ScrollText(); uniqueScrollTextWindow = this._scrollTextWindow; } this.addWindow(this._scrollTextWindow); }; var uniqueMapNameWindow = false; Scene_Map.prototype.createMapNameWindow = function() { if (uniqueMapNameWindow) { this._mapNameWindow = uniqueMapNameWindow; this._mapNameWindow.opacity = 0; this._mapNameWindow.contentsOpacity = 0; this._mapNameWindow._showCount = 0; this._mapNameWindow.refresh(); } else { this._mapNameWindow = new Window_MapName(); uniqueMapNameWindow = this._mapNameWindow; } this.addChild(this._mapNameWindow); }; var uniqueDestinationSprite = false; Spriteset_Map.prototype.createDestination = function() { if (uniqueDestinationSprite) { this._destinationSprite = uniqueDestinationSprite; this._destinationSprite._frameCount = 0; } else { this._destinationSprite = new Sprite_Destination(); uniqueDestinationSprite = this._destinationSprite; } this._destinationSprite.z = 9; this._tilemap.addChild(this._destinationSprite); }; var uniqueTimerSprite = false; Spriteset_Base.prototype.createTimer = function() { if (uniqueTimerSprite) { this._timerSprite = uniqueTimerSprite; this._timerSprite._seconds = 0; this._timerSprite.update(); } else { this._timerSprite = new Sprite_Timer(); uniqueTimerSprite = this._timerSprite; } this.addChild(this._timerSprite); }; var uniqueWeather = false; Spriteset_Map.prototype.createWeather = function() { if (uniqueWeather) { this._weather = uniqueWeather; this._weather.power = 0; this._weather.type = 'none'; this._weather.origin = new Point(); } else { this._weather = new Weather(); uniqueWeather = this._weather; } this.addChild(this._weather); }; })(OrangeAntiLag); Imported.OrangeAntiLag = true;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - PluginName * By Hudell - www.hudell.com * OrangePluginName.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Plugin Description <OrangePluginName> * @author Hudell * * @param paramName * @desc Description * @default 0 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangePluginName = Hudell.OrangePluginName || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangePluginName>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangePluginName parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; // Param validation //$.Param.paramName = Number($.Parameters.paramName || 0); // Code goes here })(Hudell.OrangePluginName); OrangePluginName = Hudell.OrangePluginName; Imported.OrangePluginName = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Map Change Event * By Hudell - www.hudell.com * OrangeMapChangeEvent.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Will let you call a common event everytime the player is transfered to a new map * * @author Hudell * * @param commonEventId * @desc The number of the common event to call * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/map-change-event * *=============================================================================*/ var Imported = Imported || {}; var OrangeMapChangeEvent = OrangeMapChangeEvent || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeMapChangeEvent'); $.Param = $.Param || {}; $.Param.commonEventId = Number($.Parameters['commonEventId'] || 0); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { if (this.isTransferring()) { if ($.Param.commonEventId !== undefined && $.Param.commonEventId > 0) { $gameTemp.reserveCommonEvent($.Param.commonEventId); } } oldGamePlayer_performTransfer.call(this); }; })(OrangeMapChangeEvent); if (Imported['MVCommons'] !== undefined) { PluginManager.register("OrangeMapChangeEvent", "1.0.0", "Will let you call a common event everytime the player is transfered to a new map", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-19"); } else { Imported["OrangeMapChangeEvent"] = true; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Pathfinding * By Hudell - www.hudell.com * OrangePathfinding.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Faster Pathfinding for Rpg Maker MV <OrangePathfinding> * @author Hudell * * @param searchLimit * @desc The higher this number, the smarter (and slower) the pathfinding will be * @default 12 * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangePathfinding = Hudell.OrangePathfinding || {}; if (Imported["SuperOrangeMovement"] !== undefined || Imported["SuperOrangeMovementEx"] !== undefined) { throw new Error("You don't need OrangePathfinding if you're using Super Orange Movement."); } (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangePathfinding>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangePathfinding parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.Param.searchLimit = Number($.Parameters.searchLimit || 12); Game_Character.prototype.getDirectionNode = function(start, goalX, goalY) { var searchLimit = this.searchLimit(); var mapWidth = $gameMap.width(); var nodeList = []; var openList = []; var closedList = []; var best = start; if (this.x === goalX && this.y === goalY) { return undefined; } nodeList.push(start); openList.push(start.y * mapWidth + start.x); while (nodeList.length > 0) { var bestIndex = 0; for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].f < nodeList[bestIndex].f) { bestIndex = i; } } var current = nodeList[bestIndex]; var x1 = current.x; var y1 = current.y; var pos1 = y1 * mapWidth + x1; var g1 = current.g; nodeList.splice(bestIndex, 1); openList.splice(openList.indexOf(pos1), 1); closedList.push(pos1); if (current.x === goalX && current.y === goalY) { best = current; break; } if (g1 >= searchLimit) { continue; } for (var j = 0; j < 4; j++) { var direction = 2 + j * 2; var x2 = $gameMap.roundXWithDirection(x1, direction); var y2 = $gameMap.roundYWithDirection(y1, direction); var pos2 = y2 * mapWidth + x2; if (closedList.contains(pos2)) { continue; } if (!this.canPass(x1, y1, direction) && (x2 !== goalX || y2 !== goalY)) { continue; } var g2 = g1 + 1; var index2 = openList.indexOf(pos2); if (index2 < 0 || g2 < nodeList[index2].g) { var neighbor; if (index2 >= 0) { neighbor = nodeList[index2]; } else { neighbor = {}; nodeList.push(neighbor); openList.push(pos2); } neighbor.parent = current; neighbor.x = x2; neighbor.y = y2; neighbor.g = g2; neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY); if (!best || neighbor.f - neighbor.g < best.f - best.g) { best = neighbor; } } } } return best; }; Game_Character.prototype.clearCachedNode = function() { this.setCachedNode(); }; Game_Character.prototype.setCachedNode = function(node, goalX, goalY) { this._cachedNode = node; this._cachedGoalX = goalX; this._cachedGoalY = goalY; }; Game_Character.prototype.findDirectionTo = function(goalX, goalY) { if (this.x === goalX && this.y === goalY) { return 0; } if (this._cachedGoalX !== goalX || this._cachedGoalY !== goalY) { this.clearCachedNode(); } var node = this._cachedNode; var start = {}; start.parent = null; start.x = this.x; start.y = this.y; start.g = 0; start.f = $gameMap.distance(start.x, start.y, goalX, goalY); var canRetry = true; if (node === undefined) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } canRetry = false; } if (node.x !== start.x || node.y !== start.y) { while (node.parent && (node.parent.x !== start.x || node.parent.y !== start.y)) { node = node.parent; } if (!node.parent) { this.clearCachedNode(); if (canRetry) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } } } } var deltaX1 = $gameMap.deltaX(node.x, start.x); var deltaY1 = $gameMap.deltaY(node.y, start.y); if (deltaY1 > 0) { return 2; } else if (deltaX1 < 0) { return 4; } else if (deltaX1 > 0) { return 6; } else if (deltaY1 < 0) { return 8; } var deltaX2 = this.deltaXFrom(goalX); var deltaY2 = this.deltaYFrom(goalY); var direction = 0; if (Math.abs(deltaX2) > Math.abs(deltaY2)) { direction = deltaX2 > 0 ? 4 : 6; } else if (deltaY2 !== 0) { direction = deltaY2 > 0 ? 8 : 2; } if (direction > 0) { if (!this.canPass(this._x, this._y, direction)) { this.clearCachedNode(); direction = 0; } } return direction; }; Game_Character.prototype.searchLimit = function() { return $.Param.searchLimit; }; })(Hudell.OrangePathfinding); Imported["OrangePathfinding"] = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Instant Trigger Mouse Events * By Hudell - www.hudell.com * OrangeInstantTriggerMouseEvents.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will trigger events instantly when you click on them * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/trigger-mouse-events * *=============================================================================*/ var Imported = Imported || {}; var OrangeInstantTriggerMouseEvents = OrangeInstantTriggerMouseEvents || {}; (function($) { "use strict"; Scene_Map.prototype.tryTriggeringEvent = function() { if ($gameMap.isAnyEventStarting() || $gameMap.isEventRunning() || !$gamePlayer.canStartLocalEvents()) { return false; } if (TouchInput.isTriggered() || this._touchCount > 0) { if (TouchInput.isPressed()) { if (this._touchCount === 0 || this._touchCount >= 15) { var x = $gameMap.canvasToMapX(TouchInput.x); var y = $gameMap.canvasToMapY(TouchInput.y); var events = $gameMap.eventsXy(x, y); if (events.length === 0) { return false; } for (var i = 0; i < events.length; i++) { if (events[i].isTriggerIn([0])) { events[i].start(); return true; } } } } } return false; }; var oldSceneMap_processMapTouch = Scene_Map.prototype.processMapTouch; Scene_Map.prototype.processMapTouch = function() { if (!this.tryTriggeringEvent()) { oldSceneMap_processMapTouch.call(this); } }; })(OrangeInstantTriggerMouseEvents); // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons'] !== undefined) { PluginManager.register("OrangeInstantTriggerMouseEvents", "1.0.0", "This plugin will trigger events instantly when you click on them", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-22"); } else { Imported["OrangeInstantTriggerMouseEvents"] = true; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Trigger Blocked Touch Events * By Hudell - www.hudell.com * OrangeTriggerBlockedTouchEvents.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will trigger onTouch events on normal priority if the player tries to walk into them * @author Hudell * * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/trigger-blocked-touch-events * *=============================================================================*/ var Imported = Imported || {}; var OrangeTriggerBlockedTouchEvents = OrangeTriggerBlockedTouchEvents || {}; (function($) { "use strict"; // alias the updateNonmoving method from the Game_Player class to check // if there's any event to trigger var oldGamePlayer_updateNonmoving = Game_Player.prototype.updateNonmoving; Game_Player.prototype.updateNonmoving = function(wasMoving) { oldGamePlayer_updateNonmoving.call(this, wasMoving); // If the player was moving or it's pressing an arrow key if (wasMoving || Input.dir4 !== 0) { // Doesn't trigger anything if there's already something running if (!$gameMap.isEventRunning()) { // Makes sure the player is blocked before checking the events if (!this.isMapPassable(this._x, this._y, this.direction)) { this.checkEventTriggerThere([1]); // Setups the starting event if there's any. if ($gameMap.setupStartingEvent()) { return; } } } } }; })(OrangeTriggerBlockedTouchEvents); // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons'] !== undefined) { PluginManager.register("OrangeTriggerBlockedTouchEvents", "1.0.0", "Will trigger onTouch events on normal priority if the player tries to walk into them", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-21"); } else { Imported["OrangeTriggerBlockedTouchEvents"] = true; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - AutoSave * By Hudell - www.hudell.com * OrangeAutoSave.js * Version: 1.1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Automatically save the game on map change <OrangeAutoSave> * @author Hudell * * @param saveSlot * @desc Set this to the number of the slot where the plugin should save * @default 1 * * @param saveOnPluginTransfer * @desc save game automatically on any kind of player transfer * @default false * * @param saveOnTransferCommand * @desc save game automatically when the "transfer player" command is used * @default true * * @param autoSaveSlot * @desc Instead of using the saveSlot param, the plugin will pick the last used slot * @default false * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * * You only need to enable saveOnPluginTransfer if you have other plugins * that transfer the player and you want the game to be saved on those * transfers too. * * When you enable it, this plugin will have to change the "new game" and * "load game" commands to make sure the game isn't autosaved by them too. * * ============================================================================ * * You can trigger an auto save with the following script call: * * DataManager.autoSave(); * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeAutoSave = Hudell.OrangeAutoSave || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeAutoSave>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeAutoSave parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.enabled = true; $.skipCalls = 0; // Param validation if ($.Parameters.saveSlot !== "false") { $.Param.saveSlot = Number($.Parameters.saveSlot || 1); } else { $.Param.saveSlot = 99; } $.Param.saveOnPluginTransfer = ($.Parameters.saveOnPluginTransfer || "").toLowerCase() === "true"; $.Param.saveOnTransferCommand = ($.Parameters.saveOnTransferCommand || "").toLowerCase() !== "false"; $.Param.autoSaveSlot = ($.Parameters.autoSaveSlot || "").toLowerCase() !== "false"; $.Param.currentSaveSlot = $.Param.saveSlot; // Code $.getSaveSlot = function() { return $.Param.currentSaveSlot; }; $.skipNextCall = function() { $.skipCalls++; }; $.doAutoSave = function() { $gameSystem.onBeforeSave(); DataManager.saveGameWithoutRescue($.getSaveSlot()); }; //Only change the performTransfer method if it's activated through params if ($.Param.saveOnPluginTransfer) { $.oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { $.oldGamePlayer_performTransfer.call(this); if ($.skipCalls > 0) { $.skipCalls--; return; } if (this._newMapId > 0) { if ($.enabled) { $.doAutoSave(); } } }; //Changes setupNewGame so that the initial player transfer doesn't trigger an auto save $.oldDataManager_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { $.skipNextCall(); $.oldDataManager_setupNewGame.call(this); }; //Changes reloadMapIfUpdated so that loading a game doesn't trigger an auto save $.oldSceneLoad_reloadMapIfUpdated = Scene_Load.prototype.reloadMapIfUpdated; Scene_Load.prototype.reloadMapIfUpdated = function() { if ($gameSystem.versionId() !== $dataSystem.versionId) { $.skipNextCall(); } $.oldSceneLoad_reloadMapIfUpdated.call(this); }; //Only change the command if the performTransfer is disabled and the transfer command is enabled } else if ($.Param.saveOnTransferCommand) { $.oldGameInterpreter_command201 = Game_Interpreter.prototype.command201; Game_Interpreter.prototype.command201 = function() { $.oldGameInterpreter_command201.call(this); if ($gamePlayer.isTransferring() && $.enabled) { $.doAutoSave(); } }; } if ($.Param.autoSaveSlot) { var oldDataManager_saveGameWithoutRescue = DataManager.saveGameWithoutRescue; DataManager.saveGameWithoutRescue = function(savefileId) { oldDataManager_saveGameWithoutRescue.call(this, savefileId); $.Param.currentSaveSlot = savefileId; }; var oldDataManager_loadGameWithoutRescue = DataManager.loadGameWithoutRescue; DataManager.loadGameWithoutRescue = function(savefileId) { oldDataManager_loadGameWithoutRescue.call(this, savefileId); $.Param.currentSaveSlot = savefileId; }; var autoSaveSlot_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { autoSaveSlot_setupNewGame.call(this); $.Param.currentSaveSlot = $.Param.saveSlot; }; } DataManager.autoSave = $.doAutoSave; })(Hudell.OrangeAutoSave); Imported.OrangeAutoSave = 1.1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Move Character To * By Hudell - www.hudell.com * OrangeMoveCharacterTo.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin adds a script call and a plugin command you can use to move the player or an event to a specific position. * @author Hudell * * @param failedMovementDelay * @desc How many frames should the characters wait before trying to move again after failing to move once. * @default 30 * * @help * Plugin Commands Examples: * move event 10 to position 15 20 and face left * move player to event 5 * move event 7 to player and follow * clear player path * clear event 7 path * * Script calls (can be used inside move routes): * this.setDestination(x, y, d); * this.setCharacterDestination(eventId, follow) * * Example: * this.setDestination(15, 20, 2); * this.setCharacterDestination(10, true); * * Direction numbers are the RPG Maker default: * left = 4 * right = 6 * top = 8 * down = 2 * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/move-character-to * *=============================================================================*/ var Imported = Imported || {}; var OrangeMoveCharacterTo = OrangeMoveCharacterTo || {}; (function($) { "use strict"; var parameters = PluginManager.parameters('OrangeMoveCharacterTo') || {}; var failedMovementDelay = Number(parameters.failedMovementDelay || 30); Game_Interpreter.prototype.checkOldOrangeMoveToFormat = function(command, args) { if (command.toUpperCase() === 'ORANGEMOVETO') { var character = this.character(parseInt(args[0], 10)); if (args.length > 2) { var x = parseFloat(args[1]); var y = parseFloat(args[2]); var d = 0; if (args.length > 3) { switch(args[3].toUpperCase()) { case 'LEFT' : d = 4; break; case 'RIGHT' : d = 6; break; case 'UP' : d = 8; break; case 'DOWN' : d = 2; break; default : d = parseInt(args[3], 10); break; } } character.setDestination(x, y, d); } else { character.clearDestination(); } } }; Game_Interpreter.prototype.checkOrangeClearPathCommand = function(command, args) { if (command.toUpperCase() !== 'CLEAR') return; if (args.length < 2) return; var nextIndex = 0; var eventId = undefined; if (args[0].toUpperCase() === 'EVENT') { eventId = parseInt(args[1], 10); nextIndex = 2; } else if (args[0].toUpperCase() === 'PLAYER') { eventId = -1; nextIndex = 1; } else if (args[0].toUpperCase() === 'THIS' && args[1].toUpperCase() === 'EVENT') { eventId = 0; nextIndex = 2; } if (args.length > nextIndex && args[nextIndex].toUpperCase() === 'PATH') { var character = this.character(eventId); if (character !== undefined && character !== null) { character.clearDestination(); } } }; Game_Interpreter.prototype.checkNewOrangeMoveToFormat = function(command, args) { if (command.toUpperCase() !== 'MOVE') return; if (args.length <= 4) return; var eventId = undefined; var newEventId = undefined; var newX = undefined; var newY = undefined; var nextIndex = 0; var follow = false; var direction = 0; if (args[0].toUpperCase() === 'EVENT') { eventId = parseInt(args[1], 10); nextIndex = 2; } else if (args[0].toUpperCase() === 'PLAYER') { eventId = -1; nextIndex = 1; } else if (args[0].toUpperCase === 'THIS' && args[1].toUpperCase() === 'EVENT') { eventId = 0; nextIndex = 2; } else { return; } if (args[nextIndex].toUpperCase() !== 'TO') return; nextIndex++; if (args.length <= nextIndex) return; if (args[nextIndex].toUpperCase() === 'EVENT') { nextIndex++; if (args.length <= nextIndex) return; newEventId = parseInt(args[nextIndex], 10); nextIndex++; } else if (args[nextIndex].toUpperCase() === 'PLAYER') { newEventId = -1; nextIndex++; } else if (args[nextIndex].toUpperCase() === 'POSITION') { if (args.length <= nextIndex + 2) return; newX = parseFloat(args[nextIndex + 1]); newY = parseFloat(args[nextIndex + 2]); nextIndex += 3; } if (args.length > nextIndex +1) { if (args[nextIndex].toUpperCase() === 'AND') { nextIndex++; if (args[nextIndex].toUpperCase() === 'FOLLOW') { follow = true; nextIndex++; } else if (args[nextIndex].toUpperCase() === 'FACE' || args[nextIndex].toUpperCase() === 'TURN') { nextIndex++; if (args.length > nextIndex) { if (args[nextIndex].toUpperCase() === 'LEFT') { direction = 4; } else if (args[nextIndex].toUpperCase() === 'RIGHT') { direction = 6; } else if (args[nextIndex].toUpperCase() === 'UP') { direction = 8; } else if (args[nextIndex].toUpperCase() === 'DOWN') { direction = 2; } else { direction = parseInt(args[nextIndex], 10); } nextIndex++; } } } } var character = this.character(eventId); if (newEventId !== undefined) { var newCharacter = this.character(newEventId); if (newCharacter === undefined || newCharacter === null) return; character.setCharacterDestination(newCharacter, follow); } else { character.setDestination(newX, newY, direction); } }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); this.checkOldOrangeMoveToFormat.call(this, command, args); this.checkNewOrangeMoveToFormat.call(this, command, args); this.checkOrangeClearPathCommand.call(this, command, args); }; var oldGameCharacterBase_updateStop = Game_CharacterBase.prototype.updateStop; Game_CharacterBase.prototype.updateStop = function() { var direction = undefined; var distance = undefined; if (this._orangeMovementDelay !== undefined && this._orangeMovementDelay > 0) { this._orangeMovementDelay--; return; } if (this._xDestination !== undefined && this._yDestination !== undefined) { if (this._xDestination == this._x && this._yDestination == this._y) { // If the character reached the destination, check if there's a direction to face if (this._dDestination !== undefined && this._dDestination !== 0) { if (this.isMoving()) { return; } this._direction = this._dDestination; } this.clearDestination(); } if (this._xDestination !== undefined) { if (!this.isMoving()) { var xDistance = this._x - this._xDestination; var yDistance = this._y - this._yDestination; // Check if there's any additional partial tile to walk if (Math.abs(xDistance) < 1 && Math.abs(yDistance) < 1) { if (xDistance < 0) { this._direction = 6; this._x = this._xDestination; return; } else if (yDistance < 0) { this._direction = 2; this._y = this._yDestination; return; } else if (xDistance > 0) { this._direction = 4; this._x = this._xDestination; return; } else if (yDistance > 0) { this._y = this._yDestination; this._direction = 8; return; } } else { //Check if there's any partial position to fix before start walking if (this._x - Math.floor(this._x) || this._y - Math.floor(this._y)) { if (this._xDestination > this._x) { this._direction = 6; this._x = Math.ceil(this._x); } else { this._direction = 4; this._x = Math.floor(this._x); } if (this._yDestination > this._y) { this._direction = 2; this._y = Math.ceil(this._y); } else { this._direction = 8; this._y = Math.floor(this._y); } return; } } direction = this.findDirectionTo(Math.floor(this._xDestination), Math.floor(this._yDestination)); if (direction > 0) { this.moveStraight(direction); if (!this.isMovementSucceeded()) { this._orangeMovementDelay = failedMovementDelay; } return; } } } } if (this._destinationCharacter !== undefined) { if (this._destinationCharacter._x === this._x && this._destinationCharacter._y == this._y) { //If the stalker reached the character, check if it needs to keep following it if (this._followCharacter !== true) { this.clearDestination(); } else { return; } } if (this._destinationCharacter !== undefined) { if (!this.isMoving()) { direction = this.findDirectionTo(this._destinationCharacter._x, this._destinationCharacter._y); if (direction > 0) { this.moveStraight(direction); if (!this.isMovementSucceeded()) { //If failed to move, and it's not set to follow the character and distance is less than 1 tile, stop moving. if (this._followCharacter !== true) { distance = Math.abs(this._x - this._destinationCharacter._x) + Math.abs(this._y - this._destinationCharacter._y); if (distance <= 1) { this.clearDestination(); return; } } this._orangeMovementDelay = failedMovementDelay; } return; } } } } oldGameCharacterBase_updateStop.call(this); }; // Change the advanceMoveRouteIndex to only advance the index when the character reach the destination. var oldGameCharacter_advanceMoveRouteIndex = Game_Character.prototype.advanceMoveRouteIndex; Game_Character.prototype.advanceMoveRouteIndex = function() { if (this._xDestination === undefined && this._yDestination === undefined && this._destinationCharacter === undefined) { oldGameCharacter_advanceMoveRouteIndex.call(this); } }; // Clears the destination automatically if a new move route is set var oldGameCharacter_setMoveRoute = Game_Character.prototype.setMoveRoute; Game_Character.prototype.setMoveRoute = function(moveRoute) { this.clearDestination(); oldGameCharacter_setMoveRoute.call(this, moveRoute); }; Game_CharacterBase.prototype.setDestination = function(x, y, d) { if (this._x != x || this._y != y || this.isMoving()) { this._xDestination = x; this._yDestination = y; if (d !== undefined) { this._dDestination = d; } } else if (d !== undefined && d !== 0) { this._direction = d; } }; Game_CharacterBase.prototype.setCharacterDestination = function(character, follow) { if (follow === undefined) follow = false; if (typeof(character) == "number") { character = $gameMap._interpreter.character(character); } if (character === undefined) return; if (follow === true) { this._destinationCharacter = character; this._followCharacter = true; } else { if (this._x != character._x || this._y != character._y || this.isMoving()) { this._destinationCharacter = character; this._followCharacter = false; } } }; //Updates Game_Temp.prototype.setDestination to only be executed when the player has no destination set on itself var oldGameTemp_setDestination = Game_Temp.prototype.setDestination; Game_Temp.prototype.setDestination = function(x, y) { if ($gamePlayer._xDestination === undefined && $gamePlayer._destinationCharacter === undefined && $gamePlayer._yDestination === undefined) { oldGameTemp_setDestination.call(this, x, y); } }; Game_CharacterBase.prototype.clearDestination = function() { this._xDestination = undefined; this._yDestination = undefined; this._dDestination = undefined; this._destinationCharacter = undefined; this._followCharacter = false; }; Game_Interpreter.prototype.waitForEventMovement = function(eventId) { this._waitingForEventMovement = eventId; if (!!this._waitingForEventMovement) { this._waitMode = 'eventMovement'; } }; var oldGameInterpreter_updateWaitMode = Game_Interpreter.prototype.updateWaitMode; Game_Interpreter.prototype.updateWaitMode = function() { if (this._waitMode == 'eventMovement') { if (!!this._waitingForEventMovement) { var eventId = this._waitingForEventMovement; var event = this.character(eventId); if (event.isMoving() || event.isJumping() || event.isBalloonPlaying()) { return true; } if (event._xDestination !== undefined && event._yDestination !== undefined) { return true; } } this._waitMode = ''; } return oldGameInterpreter_updateWaitMode.apply(this, arguments); }; })(OrangeMoveCharacterTo); Imported['OrangeMoveCharacterTo'] = 1.3;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Notetag to Variable * By Hudell - www.hudell.com * OrangeNoteTagToVariable.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to automatically change a Variable value everytime a notetag is found on a map or event - <OrangeNoteTagToVariable> * @author Hudell * * @param VariableId * @desc The number of the Variable to store the value of the notetag * @default 0 * * @param notetag * @desc The name of the notetag to look for on the maps and event notes * @default 0 * * @param noteList * @desc Configure several notes with a single plugin using this param * @default * * @help * Add the <notetag:value> on the notes of the maps and events that you want to tag. * * This plugin can be added multiple times to the same project * (just make a copy of the file and add it) * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeNoteTagToVariable"] === undefined) { (function() { "use strict"; var getProp = undefined; if (Imported["MVCommons"] !== undefined) { getProp = MVC.getProp; } else { getProp = function (meta, propName){ if (meta === undefined) return undefined; if (meta[propName] !== undefined) return meta[propName]; for (var key in meta) { if (key.toLowerCase() == propName.toLowerCase()) { return meta[key]; } } return undefined; }; } var paramList = []; function updateParamList(){ for (var i = 0; i < $plugins.length; i++) { if ($plugins[i].description.indexOf('<OrangeNoteTagToVariable>') >= 0) { var variableId = Number($plugins[i].parameters['VariableId'] || 0); var notetagName = $plugins[i].parameters['notetag'] || ''; if (variableId > 0 && notetagName.trim().length > 0) { paramList.push({ variableId : variableId, notetagName : notetagName }); } var list = $plugins[i].parameters['noteList']; if (list !== undefined) { var re = /<([^<>:]+):([^>]*)>/g; while(true) { var match = re.exec(list); if (match) { notetagName = match[1]; variableId = Number(match[2] || 0); if (variableId > 0 && notetagName.trim().length > 0) { paramList.push({ variableId : variableId, notetagName : notetagName }); } } else { break; } } } } } } updateParamList(); if (paramList.length > 0) { var updateVariableList = function() { if (SceneManager._scene instanceof Scene_Map) { for (var i = 0; i < paramList.length; i++) { var value = undefined; if ($gameMap._interpreter.isRunning() && $gameMap._interpreter._eventId > 0) { var eventData = $dataMap.events[$gameMap._interpreter._eventId]; if (eventData) { value = getProp(eventData.meta, paramList[i].notetagName); } } if (value === undefined) { value = $gameMap.getNoteTagValue(paramList[i].notetagName); } if (value !== undefined) { $gameVariables.setValue(paramList[i].variableId, value); } } } }; var oldGameInterpreter_setup = Game_Interpreter.prototype.setup; Game_Interpreter.prototype.setup = function(list, eventId) { oldGameInterpreter_setup.call(this, list, eventId); updateVariableList(); }; var oldGameInterpreter_terminate = Game_Interpreter.prototype.terminate; Game_Interpreter.prototype.terminate = function(list, eventId) { oldGameInterpreter_terminate.call(this, list, eventId); updateVariableList(); }; Game_Map.prototype.getNoteTagValue = function(notetagName) { return getProp($dataMap.meta, notetagName); }; var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); updateVariableList(); }; } })(); Imported["OrangeNoteTagToVariable"] = 1.2; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
# mv-plugins Javascript plugins for RPG Maker MV Please note: I no longer work on those plugins. You're free to use it on any kind of project (free and commercial), but **I do not provide support for them** anymore. You can make any change you need (or commission someone else to change it).
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - On Load Event * By Hudell - www.hudell.com * OrangeOnLoadEvent.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Will let you call a common event immediately after a load game * * @author Hudell * * @param commonEventId * @desc The number of the common event to call * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/on-load-event * *=============================================================================*/ var Imported = Imported || {}; var OrangeOnLoadEvent = OrangeOnLoadEvent || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeOnLoadEvent'); $.Param = $.Param || {}; $.Param.commonEventId = Number($.Parameters['commonEventId'] || 0); var oldGameSystem_onAfterLoad = Game_System.prototype.onAfterLoad; Game_System.prototype.onAfterLoad = function() { oldGameSystem_onAfterLoad.call(this); if ($.Param.commonEventId !== undefined && $.Param.commonEventId > 0) { $gameTemp.reserveCommonEvent($.Param.commonEventId); } }; })(OrangeOnLoadEvent); if (Imported['MVCommons'] !== undefined) { PluginManager.register("OrangeOnLoadEvent", "1.0.0", "Will let you call a common event immediately after a load game", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-19"); } else { Imported["OrangeOnLoadEvent"] = true; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Greenworks * By Hudell - www.hudell.com * OrangeGreenworks.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Steamworks Integration <OrangeGreenworks> * @author Hudell * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website to learn how to use this plugin: * http://hudell.com/blog/orangegreenworks/ * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeGreenworks = Hudell.OrangeGreenworks || {}; (function($) { "use strict"; $.getScreenName = function() { return 'Play Test'; }; $.getUILanguage = function() { return 'english'; }; $.getGameLanguage = function() { return 'english'; }; $.activateAchievement = function(achievementName) { console.log('Activate achievement ', achievementName); }; $.getAchievement = function(achievementName) { return false; }; $.clearAchievement = function(achievementName) { console.log('Clear achievement ', achievementName); }; $.getNumberOfAchievements = function() { return 0; }; $.isSteamRunning = function() { return false; }; $.activateGameOverlay = function(option) { }; $.isGameOverlayEnabled = function() { return false; }; $.activateGameOverlayToWebPage = function(url) { console.log('Open URL'); }; $.getDLCCount = function() { return 0; }; $.isDLCInstalled = function(dlcAppId) { return false; }; $.installDLC = function(dlcAppId) { }; $.uninstallDLC = function(dlcAppId) { }; $.getStatInt = function(name) { return 0; }; $.getStatFloat = function(name) { return 0; }; $.setStat = function(name, value) { console.log('Change Stat', name, value); return false; }; $.storeStats = function() { console.log('Store Stats'); return false; }; $.isSubscribedApp = function(appId) { return false; }; if (Utils.isNwjs()) { $.initialized = false; try { $.greenworks = require('./greenworks'); } catch(e) { $.greenworks = false; console.log('Greenworks failed to load. Make sure you copied all files from the Steamworks SDK to the right folders;'); console.log('http://hudell.com/blog/orange-greenworks'); console.error(e); } if (!!$.greenworks) { $.initialized = $.greenworks.initAPI(); if (!$.initialized) { console.log('Greenworks failed to initialize.'); return; } $.steamId = $.greenworks.getSteamId(); console.log('Steam User: ', $.steamId.screenName); $.getScreenName = function() { return $.steamId.screenName; }; $.getUILanguage = function() { return $.greenworks.getCurrentUILanguage(); }; $.getGameLanguage = function() { return $.greenworks.getCurrentGameLanguage(); }; $.isSteamRunning = function() { return $.greenworks.isSteamRunning(); }; $._storeStatsSuccess = function(){ console.log('Stored Stats Successfully', arguments); }; $._storeStatsError = function(){ console.log('Failed to Store Stats', arguments); }; $._achievementSuccess = function(){ console.log('Achievement activated', arguments); }; $._achievementError = function(){ console.log('Achievement activation error', arguments); }; $._clearAchievementSuccess = function(){ console.log('Successfully Cleared Achievement', arguments); }; $._clearAchievementError = function(){ console.log('Failed to Clear Achievement', arguments); }; $._getAchievementSuccess = function(){ }; $._getAchievementError = function(){ console.log('Failed to check Achievement', arguments); }; $.activateAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return; } $.greenworks.activateAchievement(achievementName, $._achievementSuccess, $._achievementError); }; $.getAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return false; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.getAchievement(achievementName, $._getAchievementSuccess, $._getAchievementError); }; $.clearAchievement = function(achievementName) { if (!achievementName) { console.log('Achievement name not provided.'); return false; } if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.clearAchievement(achievementName, $._clearAchievementSuccess, $._clearAchievementError); }; $.getNumberOfAchievements = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.getNumberOfAchievements(); }; $.activateGameOverlay = function(option) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.activateGameOverlay(option); }; $.isGameOverlayEnabled = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isGameOverlayEnabled(); }; $.activateGameOverlayToWebPage = function(url) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.activateGameOverlayToWebPage(url); }; $.isSubscribedApp = function(appId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isSubscribedApp(appId); }; $.getDLCCount = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getDLCCount(); }; $.isDLCInstalled = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.isDLCInstalled(dlcAppId); }; $.installDLC = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.installDLC(dlcAppId); }; $.uninstallDLC = function(dlcAppId) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } $.greenworks.uninstallDLC(dlcAppId); }; $.getStatInt = function(name) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getStatInt(name); }; $.getStatFloat = function(name) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return 0; } return $.greenworks.getStatFloat(name); }; $.setStat = function(name, value) { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.setStat(name, value); }; $.storeStats = function() { if (!$.isSteamRunning()) { console.log('Steam isn\'t running'); return false; } return $.greenworks.setStat($._storeStatsSuccess, $._storeStatsError); }; $.getFriendCount = function() { return $.greenworks.getFriendCount($.greenworks.FriendFlags.Immediate); }; $.isCloudEnabled = function() { return $.greenworks.isCloudEnabled(); }; $.isCloudEnabledForUser = function() { return $.greenworks.isCloudEnabledForUser(); }; } } })(Hudell.OrangeGreenworks); OrangeGreenworks = Hudell.OrangeGreenworks; Imported.OrangeGreenworks = 1.2;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Change Save File Name * By Hudell - www.hudell.com * OrangeChangeSaveFileName.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will help you change the base name of the save files * @author Hudell * * @param localFilePattern * @desc The pattern for the local file name. Include '%1' on the position where you want the number of the save file to be. * @default file%1.rpgsave * * @param webStorageKeyPattern * @desc The pattern for web storage key name. Include '%1' on the position where you want the number of the save file to be. * @default RPG File%1 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/savefilename * *=============================================================================*/ var Imported = Imported || {}; var OrangeChangeSaveFileName = OrangeChangeSaveFileName || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeChangeSaveFileName'); // If a new localFilePattern was defined, alias the localFilePath method // from the StorageManager and use the new pattern if ($.Parameters["localFilePattern"] !== undefined) { var saveFilePattern = $.Parameters["localFilePattern"] || "file%1.rpgsave"; var oldStorageManager_localFilePath = StorageManager.localFilePath; StorageManager.localFilePath = function(savefileId) { if (savefileId <= 0) { return oldStorageManager_localFilePath.call(this, savefileId); } var name = saveFilePattern.format(savefileId); return this.localFileDirectoryPath() + name; }; } // If a new webStorageKeyPattern was defined, alias the webStorageKey method // from the StorageManager and use the new pattern if ($.Parameters["webStorageKeyPattern"] !== undefined) { var webStorageKeyPattern = $.Parameters["webStorageKeyPattern"] || "RPG File%1"; var oldStorageManager_webStorageKey = StorageManager.webStorageKey; StorageManager.webStorageKey = function(savefileId) { if (savefileId <= 0) { return oldStorageManager_webStorageKey.call(this, savefileId); } return webStorageKeyPattern.format(savefileId); }; } })(OrangeChangeSaveFileName); Imported["OrangeChangeSaveFileName"] = 1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Instant Mouse Movement * By Hudell - www.hudell.com * OrangeInstantMouseMovement.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will instantly teleport the player to the clicked position * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/instant-mouse-movement * *=============================================================================*/ /*:pt-br * @plugindesc Este plugin vai teletransportar o jogador instantaneamente para a posição clicada * @author Hudell * * @help * ============================================================================ * Última VersΓ£o * ============================================================================ * * Baixe a ΓΊltima versΓ£o deste script em * http://link.hudell.com/instant-mouse-movement * *=============================================================================*/ Game_Temp.prototype.setDestination = function(x, y) { $gamePlayer.setPosition(x, y); }; var Imported = Imported || {}; // If MVCommons is imported, register the plugin with it's PluginManager. if (Imported['MVCommons'] !== undefined) { PluginManager.register("OrangeInstantMouseMovement", "1.0.0", "This plugin will instantly teleport the player to the clicked position", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-24"); } else { Imported["OrangeInstantMouseMovement"] = true; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Mapshot * By Hudell - www.hudell.com * OrangeMapshot.js * Version: 1.7 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin will save a picture of the entire map on a Mapshots folder when you press a key. <OrangeMapshot> * @author Hudell * * @param useMapName * @desc if true, the filename will be the name of the map. If false it will be the number. * @default true * * @param layerType * @desc 0 = all, 1 = upper and lower, 2 = separate everything * @default 0 * * @param drawAutoShadows * @desc set this to false to disable autoshadows on the map shot * @default true * * @param drawEvents * @desc set this to false to stop drawing the events on the full bitmap * @default true * * @param keyCode * @desc code of the key that will be used (44 = printscreen). http://www.javascriptkeycode.com * @default 44 * * @param imageType * @desc What type of image should be generated. Can be png, jpeg or webp * @default png * * @param imageQuality * @desc If the imageType is jpeg or webp, you can set this to a number between 0 and 100 indicating the quality of the image * @default 70 * * @param imagePath * @desc The path where the images will be saved * @default ./Mapshots * * @help * Check keycodes at http://www.javascriptkeycode.com */ var Imported = Imported || {}; var OrangeMapshot = OrangeMapshot || {}; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.indexOf('<OrangeMapshot>') >= 0; }); if (parameters.length === 0) { throw new Error("Couldn't find OrangeMapshot parameters."); } $.Parameters = parameters[0].parameters; $.Param = {}; $.Param.useMapName = $.Parameters.useMapName !== "false"; $.Param.drawAutoShadows = $.Parameters.drawAutoShadows !== "false"; $.Param.drawEvents = $.Parameters.drawEvents !== "false"; $.Param.layerType = Number($.Parameters.layerType || 0); $.Param.imageType = $.Parameters.imageType || 'png'; $.Param.imagePath = $.Parameters.imagePath || './Mapshots'; $.Param.imageQuality = Number($.Parameters.imageQuality || 70); $.Param.keyCode = Number($.Parameters.keyCode || 44); $.imageType = function() { if ($.Param.imageType == 'webp') return 'image/webp'; if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return 'image/jpeg'; return 'image/png'; }; $.imageRegex = function() { if ($.Param.imageType == 'webp') return (/^data:image\/webp;base64,/); if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return (/^data:image\/jpeg;base64,/); return (/^data:image\/png;base64,/); }; $.fileExtension = function() { if ($.Param.imageType == 'webp') return '.webp'; if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return '.jpg'; return '.png'; }; $.imageQuality = function() { if ($.fileExtension() == '.jpg' || $.fileExtension() == '.webp') { return Math.min($.Param.imageQuality, 100) / 100; } return 1; }; $.baseFileName = function() { var mapName = ($gameMap._mapId).padZero(3); if ($.Param.useMapName) { mapName = $dataMapInfos[$gameMap._mapId].name; } else { mapName = 'Map' + mapName; } return mapName; }; $.getMapshot = function() { var lowerBitmap; var upperBitmap; switch($.Param.layerType) { case 1 : lowerBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); upperBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); SceneManager._scene._spriteset._tilemap._paintEverything(lowerBitmap, upperBitmap); return [lowerBitmap, upperBitmap]; case 2 : var groundBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var ground2Bitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var lowerBitmapLayer = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var upperBitmapLayer = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var shadowBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var lowerEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var normalEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); var upperEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); SceneManager._scene._spriteset._tilemap._paintLayered(groundBitmap, ground2Bitmap, lowerBitmapLayer, upperBitmapLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents); return [groundBitmap, ground2Bitmap, lowerBitmapLayer, upperBitmapLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents]; default : lowerBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); upperBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); SceneManager._scene._spriteset._tilemap._paintEverything(lowerBitmap, upperBitmap); var bitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight()); bitmap.blt(lowerBitmap, 0, 0, lowerBitmap.width, lowerBitmap.height, 0, 0, lowerBitmap.width, lowerBitmap.height); bitmap.blt(upperBitmap, 0, 0, upperBitmap.width, upperBitmap.height, 0, 0, upperBitmap.width, upperBitmap.height); return [bitmap]; } }; function MapShotTileMap() { } MapShotTileMap.prototype = Object.create(Tilemap.prototype); MapShotTileMap.prototype.constructor = MapShotTileMap; MapShotTileMap.prototype._drawAutotile = function(bitmap, tileId, dx, dy) { var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE; var kind = Tilemap.getAutotileKind(tileId); var shape = Tilemap.getAutotileShape(tileId); var tx = kind % 8; var ty = Math.floor(kind / 8); var bx = 0; var by = 0; var setNumber = 0; var isTable = false; if (Tilemap.isTileA1(tileId)) { var waterSurfaceIndex = [0, 1, 2, 1][this.animationFrame % 4]; setNumber = 0; if (kind === 0) { bx = waterSurfaceIndex * 2; by = 0; } else if (kind === 1) { bx = waterSurfaceIndex * 2; by = 3; } else if (kind === 2) { bx = 6; by = 0; } else if (kind === 3) { bx = 6; by = 3; } else { bx = Math.floor(tx / 4) * 8; by = ty * 6 + Math.floor(tx / 2) % 2 * 3; if (kind % 2 === 0) { bx += waterSurfaceIndex * 2; } else { bx += 6; autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE; by += this.animationFrame % 3; } } } else if (Tilemap.isTileA2(tileId)) { setNumber = 1; bx = tx * 2; by = (ty - 2) * 3; isTable = this._isTableTile(tileId); } else if (Tilemap.isTileA3(tileId)) { setNumber = 2; bx = tx * 2; by = (ty - 6) * 2; autotileTable = Tilemap.WALL_AUTOTILE_TABLE; } else if (Tilemap.isTileA4(tileId)) { setNumber = 3; bx = tx * 2; by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0)); if (ty % 2 === 1) { autotileTable = Tilemap.WALL_AUTOTILE_TABLE; } } var table = autotileTable[shape]; var source = this.bitmaps[setNumber]; if (table && source) { var w1 = this._tileWidth / 2; var h1 = this._tileHeight / 2; for (var i = 0; i < 4; i++) { var qsx = table[i][0]; var qsy = table[i][1]; var sx1 = (bx * 2 + qsx) * w1; var sy1 = (by * 2 + qsy) * h1; var dx1 = dx + (i % 2) * w1; var dy1 = dy + Math.floor(i / 2) * h1; if (isTable && (qsy === 1 || qsy === 5)) { var qsx2 = qsx; var qsy2 = 3; if (qsy === 1) { qsx2 = [0,3,2,1][qsx]; } var sx2 = (bx * 2 + qsx2) * w1; var sy2 = (by * 2 + qsy2) * h1; bitmap.blt(source, sx2, sy2, w1, h1, dx1, dy1, w1, h1); dy1 += h1/2; bitmap.blt(source, sx1, sy1, w1, h1 / 2, dx1, dy1, w1, h1 / 2); } else { bitmap.blt(source, sx1, sy1, w1, h1, dx1, dy1, w1, h1); } } } }; MapShotTileMap.prototype._drawNormalTile = function(bitmap, tileId, dx, dy) { var setNumber = 0; if (Tilemap.isTileA5(tileId)) { setNumber = 4; } else { setNumber = 5 + Math.floor(tileId / 256); } var w = this._tileWidth; var h = this._tileHeight; var sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w; var sy = (Math.floor(tileId % 256 / 8) % 16) * h; var source = this.bitmaps[setNumber]; if (source) { bitmap.blt(source, sx, sy, w, h, dx, dy, w, h); } }; MapShotTileMap.prototype._drawTableEdge = function(bitmap, tileId, dx, dy) { if (Tilemap.isTileA2(tileId)) { var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE; var kind = Tilemap.getAutotileKind(tileId); var shape = Tilemap.getAutotileShape(tileId); var tx = kind % 8; var ty = Math.floor(kind / 8); var setNumber = 1; var bx = tx * 2; var by = (ty - 2) * 3; var table = autotileTable[shape]; if (table) { var source = this.bitmaps[setNumber]; var w1 = this._tileWidth / 2; var h1 = this._tileHeight / 2; for (var i = 0; i < 2; i++) { var qsx = table[2 + i][0]; var qsy = table[2 + i][1]; var sx1 = (bx * 2 + qsx) * w1; var sy1 = (by * 2 + qsy) * h1 + h1/2; var dx1 = dx + (i % 2) * w1; var dy1 = dy + Math.floor(i / 2) * h1; bitmap.blt(source, sx1, sy1, w1, h1/2, dx1, dy1, w1, h1/2); } } } }; Tilemap.prototype._drawTileOldStyle = function(bitmap, tileId, dx, dy) { if (Tilemap.isVisibleTile(tileId)) { if (Tilemap.isAutotile(tileId)) { MapShotTileMap.prototype._drawAutotile.call(this, bitmap, tileId, dx, dy); } else { MapShotTileMap.prototype._drawNormalTile.call(this, bitmap, tileId, dx, dy); } } }; Tilemap.prototype._paintEverything = function(lowerBitmap, upperBitmap) { var tileCols = $dataMap.width; var tileRows = $dataMap.height; for (var y = 0; y < tileRows; y++) { for (var x = 0; x < tileCols; x++) { this._paintTilesOnBitmap(lowerBitmap, upperBitmap, x, y); } } if ($.Param.drawEvents !== false) { this._paintCharacters(lowerBitmap, 0); this._paintCharacters(lowerBitmap, 1); this._paintCharacters(upperBitmap, 2); } }; Tilemap.prototype._paintLayered = function(groundBitmap, ground2Bitmap, lowerBitmap, upperLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents) { var tileCols = $dataMap.width; var tileRows = $dataMap.height; for (var y = 0; y < tileRows; y++) { for (var x = 0; x < tileCols; x++) { this._paintTileOnLayers(groundBitmap, ground2Bitmap, lowerBitmap, upperLayer, shadowBitmap, x, y); } } this._paintCharacters(lowerEvents, 0); this._paintCharacters(normalEvents, 1); this._paintCharacters(upperEvents, 2); }; Tilemap.prototype._paintCharacters = function(bitmap, priority) { this.children.forEach(function(child) { if (child instanceof Sprite_Character) { if (child._character !== null) { if (child._character instanceof Game_Player || child._character instanceof Game_Follower || child._character instanceof Game_Vehicle) return; } child.update(); if (child._characterName === '' && child._tileId === 0) return; if (priority !== undefined && child._character._priorityType !== priority) return; var x = child.x - child._frame.width / 2 + $gameMap._displayX * $gameMap.tileWidth(); var y = child.y - child._frame.height + $gameMap._displayY * $gameMap.tileHeight(); bitmap.blt(child.bitmap, child._frame.x, child._frame.y, child._frame.width, child._frame.height, x, y, child._frame.width, child._frame.height); } }); }; Tilemap.prototype._paintTileOnLayers = function(groundBitmap, ground2Bitmap, lowerBitmap, upperBitmap, shadowBitmap, x, y) { var tableEdgeVirtualId = 10000; var mx = x; var my = y; var dx = (mx * this._tileWidth); var dy = (my * this._tileHeight); var lx = dx / this._tileWidth; var ly = dy / this._tileHeight; var tileId0 = this._readMapData(mx, my, 0); var tileId1 = this._readMapData(mx, my, 1); var tileId2 = this._readMapData(mx, my, 2); var tileId3 = this._readMapData(mx, my, 3); var shadowBits = this._readMapData(mx, my, 4); var upperTileId1 = this._readMapData(mx, my - 1, 1); if (groundBitmap !== undefined) { groundBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); } if (ground2Bitmap !== undefined) { ground2Bitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); } if (lowerBitmap !== undefined) { lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); } if (upperBitmap !== undefined) { upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); } if (shadowBitmap !== undefined) { shadowBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); } var me = this; function drawTiles(bitmap, tileId, shadowBits, upperTileId1) { if (tileId < 0) { if ($.Param.drawAutoShadows && shadowBits !== undefined) { MapShotTileMap.prototype._drawShadow.call(me, bitmap, shadowBits, dx, dy); } } else if (tileId >= tableEdgeVirtualId) { MapShotTileMap.prototype._drawTableEdge.call(me, bitmap, upperTileId1, dx, dy); } else { me._drawTileOldStyle(bitmap, tileId, dx, dy); } } if (groundBitmap !== undefined) { drawTiles(groundBitmap, tileId0, undefined, upperTileId1); if (shadowBitmap !== undefined && tileId0 < 0) { drawTiles(shadowBitmap, tileId0, shadowBits, upperTileId1); } } if (ground2Bitmap !== undefined) { drawTiles(ground2Bitmap, tileId1, undefined, upperTileId1); if (shadowBitmap !== undefined && tileId1 < 0) { drawTiles(shadowBitmap, tileId1, shadowBits, upperTileId1); } } if (lowerBitmap !== undefined) { drawTiles(lowerBitmap, tileId2, undefined, upperTileId1); if (shadowBitmap !== undefined && tileId2 < 0) { drawTiles(shadowBitmap, tileId2, shadowBits, upperTileId1); } } if (upperBitmap !== undefined) { drawTiles(upperBitmap, tileId3, shadowBits, upperTileId1); if (shadowBitmap !== undefined && tileId3 < 0) { drawTiles(shadowBitmap, tileId3, shadowBits, upperTileId1); } } }; Tilemap.prototype._paintTilesOnBitmap = function(lowerBitmap, upperBitmap, x, y) { var tableEdgeVirtualId = 10000; var mx = x; var my = y; var dx = (mx * this._tileWidth); var dy = (my * this._tileHeight); var lx = dx / this._tileWidth; var ly = dy / this._tileHeight; var tileId0 = this._readMapData(mx, my, 0); var tileId1 = this._readMapData(mx, my, 1); var tileId2 = this._readMapData(mx, my, 2); var tileId3 = this._readMapData(mx, my, 3); var shadowBits = this._readMapData(mx, my, 4); var upperTileId1 = this._readMapData(mx, my - 1, 1); var lowerTiles = []; var upperTiles = []; if (this._isHigherTile(tileId0)) { upperTiles.push(tileId0); } else { lowerTiles.push(tileId0); } if (this._isHigherTile(tileId1)) { upperTiles.push(tileId1); } else { lowerTiles.push(tileId1); } lowerTiles.push(-shadowBits); if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) { if (!Tilemap.isShadowingTile(tileId0)) { lowerTiles.push(tableEdgeVirtualId + upperTileId1); } } if (this._isOverpassPosition(mx, my)) { upperTiles.push(tileId2); upperTiles.push(tileId3); } else { if (this._isHigherTile(tileId2)) { upperTiles.push(tileId2); } else { lowerTiles.push(tileId2); } if (this._isHigherTile(tileId3)) { upperTiles.push(tileId3); } else { lowerTiles.push(tileId3); } } lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); for (var i = 0; i < lowerTiles.length; i++) { var lowerTileId = lowerTiles[i]; if (lowerTileId < 0) { if ($.Param.drawAutoShadows) { MapShotTileMap.prototype._drawShadow.call(this, lowerBitmap, shadowBits, dx, dy); } } else if (lowerTileId >= tableEdgeVirtualId) { MapShotTileMap.prototype._drawTableEdge.call(this, lowerBitmap, upperTileId1, dx, dy); } else { this._drawTileOldStyle(lowerBitmap, lowerTileId, dx, dy); } } for (var j = 0; j < upperTiles.length; j++) { this._drawTileOldStyle(upperBitmap, upperTiles[j], dx, dy); } }; $.saveMapshot = function() { if (!Utils.isNwjs()) return; var fs = require('fs'); var path = $.Param.imagePath; try { fs.mkdir(path, function() { try{ var fileName = path + '/' + $.baseFileName(); var ext = $.fileExtension(); var names = [fileName + ext]; var regex = $.imageRegex(); switch ($.Param.layerType) { case 1 : names = [ fileName + ' Lower' + ext, fileName + ' Upper' + ext ]; break; case 2 : names = [ fileName + ' Ground' + ext, fileName + ' Ground 2' + ext, fileName + ' Lower' + ext, fileName + ' Upper' + ext, fileName + ' Shadows' + ext, fileName + ' Lower Events' + ext, fileName + ' Normal Events' + ext, fileName + ' Upper Events' + ext ]; break; default : names = [fileName + ext]; break; } var snaps = $.getMapshot(); var callback = function(error) { if (error !== undefined && error !== null) { console.error('An error occured while saving the mapshot', error); } }; for (var i = 0; i < names.length; i++) { var urlData = snaps[i].canvas.toDataURL($.imageType(), $.imageQuality()); var base64Data = urlData.replace(regex, ""); fs.writeFile(names[i], base64Data, 'base64', callback); } } catch (error) { if (error !== undefined && error !== null) { console.error('An error occured while saving the map shot:', error); } } }); var nodePath = require('path'); var longPath = nodePath.resolve(path); if (process.platform == 'win32' && $._openedFolder === undefined) { $._openedFolder = true; setTimeout(function(){ var exec = require('child_process').exec; exec('explorer ' + longPath); }, 100); } else { $gameMessage.add('Mapshot saved to \n' + longPath.replace(/\\/g, '\\\\').match(/.{1,40}/g).join('\n')); } } catch (error) { if (error !== undefined && error !== null) { console.error('An error occured while saving the mapshot:', error); } } }; $.onKeyUp = function(event) { if (event.keyCode == $.Param.keyCode) { if (SceneManager._scene instanceof Scene_Map) { $.saveMapshot(); } } }; document.addEventListener('keyup', $.onKeyUp); })(OrangeMapshot); Imported.OrangeMapshot = 1.7;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Event Manager * By Hudell - www.hudell.com * OrangeEventManager.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Provides an event listener interface to any plugin * * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/event-manager * *=============================================================================*/ var Imported = Imported || {}; var OrangeEventManager = OrangeEventManager || {}; (function($) { "use strict"; $._events = []; var oldGameTemp_initialize = Game_Temp.prototype.initialize; Game_Temp.prototype.initialize = function() { oldGameTemp_initialize.call(this); this._orangeCommonEvents = []; }; Game_Temp.prototype.reserveOrangeCommonEvent = function(commonEventId) { if (commonEventId > 0) { this._orangeCommonEvents = this._orangeCommonEvents || []; this._orangeCommonEvents.push(commonEventId); } }; var oldGameInterpreter_setupReservedCommonEvent = Game_Interpreter.prototype.setupReservedCommonEvent; Game_Interpreter.prototype.setupReservedCommonEvent = function() { if (!$gameTemp) return false; var result = oldGameInterpreter_setupReservedCommonEvent.call(this); if (result) return result; if (!$gameTemp._orangeCommonEvents) return result; if ($gameTemp._orangeCommonEvents.length > 0) { var commonEventId = $gameTemp._orangeCommonEvents.shift(); var commonEvent = $dataCommonEvents[commonEventId]; this.setup(commonEvent.list); return true; } return result; }; $.on = function(eventName, callback) { if (this._events[eventName] === undefined) this._events[eventName] = []; this._events[eventName].push(callback); }; $.un = function(eventName, callback) { if (this._events[eventName] === undefined) return; for (var i = 0; i < this._events[eventName].length; i++) { if (this._events[eventName][i] == callback) { this._events[eventName][i] = undefined; return; } } }; $.executeCallback = function(callback) { if (typeof(callback) == "function") { return callback.call(this); } if (typeof(callback) == "number") { $gameTemp.reserveOrangeCommonEvent(callback); return true; } if (typeof(callback) == "string") { var id = parseInt(callback, 10); if (parseInt(callback, 10) == callback.trim()) { $gameTemp.reserveOrangeCommonEvent(parseInt(callback, 10)); return true; } else if (callback.substr(0, 2) == 'SS') { //Self Switch var selfSwitchData = callback.split(','); var usedData = [0, 0, 'A', 'TRUE']; for (var i = 0; i < selfSwitchData.length; i++) { if (usedData.length > i) { usedData[i] = selfSwitchData[i]; } } var mapId = parseInt(usedData[0].substr(2), 10); var eventId = parseInt(usedData[1], 10); var switchName = usedData[2].toUpperCase(); var switchValue = usedData[3].toUpperCase(); var key = [mapId, eventId, switchName]; if (!!$gameSelfSwitches) { if (switchValue == 'TOGGLE') { switchValue = !$gameSelfSwitches.value(key); } else if (switchValue === 'FALSE' || switchValue === 'OFF') { switchValue = false; } else { switchValue = true; } $gameSelfSwitches.setValue(key, switchValue); return true; } else { return false; } } else if (callback.substr(0, 1) == 'S') { //Switch var data = callback.split(','); var value = 'TRUE'; if (data.length >= 2) { value = data[1].toUpperCase(); } id = parseInt(data[0].substr(1)); if (!!$gameSwitches) { if (value == 'TOGGLE') { value = !$gameSwitches.value(id); } else if (value === 'FALSE' || value === 'OFF') { value = false; } else { value = true; } $gameSwitches.setValue(id, value); return true; } else { return false; } } return eval(callback); } console.error("Unknown callback type: ", callback); return undefined; }; $.runEvent = function(eventName) { if (this._events[eventName] === undefined) return; for (var i = 0; i < this._events[eventName].length; i++) { var callback = this._events[eventName][i]; if (this.executeCallback(callback) === false) { break; } } }; })(OrangeEventManager); Imported.OrangeEventManager = 1.2;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - HUD * By HUDell - www.hudell.com * OrangeHud.js * Version: 2.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc <OrangeHud> 2.1 - Creates a custom HUD based on the params * * @author Hudell * * @param DefaultFontFace * @desc The font face to use by default * @default Verdana * * @param DefaultFontSize * @desc The font size to use by default * @default 18 * * @param DefaultFontColor * @desc The font color to use by default * @default #FFFFFF * * @param DefaultFontItalic * @desc Should use italic by default? * @default false * * @param HudWidth * @desc The width of the hud. 0 == 100% * @default 0 * * @param HudHeight * @desc The height of the hud. 0 == 100% * @default 0 * * @param HudX * @desc The X position of the hud * @default 0 * * @param HudY * @desc The Y position of the hud * @default 0 * * @param HudOpacity * @desc The Opacity of the hud * @default 0 * * @param SwitchId * @desc Number of a switch to hide / show the hud * @default 0 * * @param WindowMargin * @desc The number of pixels to use on the margin of the hud window * @default 4 * * @param WindowPadding * @desc The number of pixels to use on the padding of the hud window * @default 18 * * @param ShowOnMap * @desc Display this HUD on the map * @default true * * @param ShowOnBattle * @desc Display this HUD on battles? * @default false * * @param ShowOnMenu * @desc Display this HUD on the menu? * @default false * * @param ShowOnTitle * @desc Display this HUD on the title screen? * @default false * * @param ShowUnderTintLayer * @desc Set this to true to hide the HUD under tint and fade effects * @default false * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the HUD * @default true * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/hud * *=============================================================================*/ var Imported = Imported || {}; var OrangeHud = OrangeHud || {}; function Window_OrangeHud() { this.initialize.apply(this, arguments); } Window_OrangeHud.prototype = Object.create(Window_Base.prototype); Window_OrangeHud.prototype.constructor = Window_OrangeHud; if (Imported["MVCommons"] === undefined) { (function($){ $.getParamList = function(partialPluginName) { var list = []; for (var pluginName in PluginManager._parameters) { if (pluginName.search(partialPluginName.toLowerCase()) >= 0) { list.push(PluginManager._parameters[pluginName]); } } return list; }; })(PluginManager); if (Utils.isOptionValid('test')) { console.log('MVC not found, OrangeHud will be using essentials (copied from MVC 1.2.1).'); } } (function($) { "use strict"; var plugin = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeHud>'); })[0]; $.Parameters = plugin.parameters; $.Param = $.Param || {}; $.Param.GroupName = "main"; $.Param.DefaultFontFace = String($.Parameters.DefaultFontFace || "GameFont"); $.Param.DefaultFontSize = Number($.Parameters.DefaultFontSize || 18); $.Param.DefaultFontColor = String($.Parameters.DefaultFontColor || '#FFFFFF'); $.Param.DefaultFontItalic = $.Parameters.DefaultFontItalic === "true"; $.Param.ShowUnderTintLayer = ($.Parameters.ShowUnderTintLayer || "false").toLowerCase() === "true"; $.Param.HudWidth = Number($.Parameters.HudWidth || SceneManager._screenWidth); if ($.Param.HudWidth === 0) { $.Param.HudWidth = SceneManager._screenWidth; } $.Param.HudHeight = Number($.Parameters.HudHeight || SceneManager._screenHeight); if ($.Param.HudHeight === 0) { $.Param.HudHeight = SceneManager._screenHeight; } $.Param.HudX = Number($.Parameters.HudX || 0); $.Param.HudY = Number($.Parameters.HudY || 0); $.Param.HudOpacity = Number($.Parameters.HudOpacity || 0); $.Param.SwitchId = Number($.Parameters.SwitchId || 0); $.Param.WindowMargin = Number($.Parameters.WindowMargin); if (isNaN($.Param.WindowMargin)) { $.Param.WindowMargin = 4; } $.Param.WindowPadding = Number($.Parameters.WindowPadding); if (isNaN($.Param.WindowPadding)) { $.Param.WindowPadding = 18; } $.Param.ShowOnTitle = $.Parameters.ShowOnTitle === "true"; $.Param.ShowOnMenu = $.Parameters.ShowOnMenu === "true"; $.Param.ShowOnBattle = $.Parameters.ShowOnBattle === "true"; $.Param.ShowOnMap = $.Parameters.ShowOnMap !== "false"; $.Param.AutoRefresh = $.Parameters.AutoRefresh !== "false"; $._addons = {}; $._groups = {}; $._isDirty = false; $.setDirty = function() { $._isDirty = true; }; $.refresh = function() { $.setDirty(); }; $.validateGroupParams = function(params) { params.GroupName = params.GroupName || "group"; params.AutoRefresh = params.AutoRefresh !== "false"; params.DefaultFontFace = String(params.DefaultFontFace || "GameFont"); params.DefaultFontSize = Number(params.DefaultFontSize || 18); params.DefaultFontColor = String(params.DefaultFontColor || '#FFFFFF'); params.DefaultFontItalic = params.DefaultFontItalic === "true"; params.ShowUnderTintLayer = (params.ShowUnderTintLayer || "false").toLowerCase() === "true"; params.HudWidth = Number(params.HudWidth || SceneManager._screenWidth); if (params.HudWidth === 0) { params.HudWidth = SceneManager._screenWidth; } params.HudHeight = Number(params.HudHeight || SceneManager._screenHeight); if (params.HudHeight === 0) { params.HudHeight = SceneManager._screenHeight; } params.HudX = Number(params.HudX || 0); params.HudY = Number(params.HudY || 0); params.HudOpacity = Number(params.HudOpacity || 0); params.SwitchId = Number(params.SwitchId || 0); params.WindowMargin = Number(params.WindowMargin || 4); params.WindowPadding = Number(params.WindowPadding || 18); params.ShowOnTitle = params.ShowOnTitle === "true"; params.ShowOnMenu = params.ShowOnMenu === "true"; params.ShowOnBattle = params.ShowOnBattle === "true"; params.ShowOnMap = params.ShowOnMap !== "false"; }; $.configureGroups = function() { this._groups = { main : [this.Param] }; var groups = PluginManager.getParamList('OrangeHudGroup'); for (var i = 0; i < groups.length; i++) { var group = groups[i]; this.validateGroupParams(group); if (!!group.GroupName) { if (this._groups[group.GroupName] === undefined) { this._groups[group.GroupName] = []; } this._groups[group.GroupName].push(group); } } }; $.registerLineType = function(lineType, manager) { $._addons[lineType] = { manager : manager, lines : {}, params : PluginManager.getParamList(lineType) }; for (var i = 0; i < $._addons[lineType].params.length; i++) { manager.validateParams($._addons[lineType].params[i]); } }; Window_OrangeHud.prototype.initialize = function(group) { this.group = group; Window_Base.prototype.initialize.call(this, 0, 0, this.windowWidth(), this.windowHeight()); this.refresh(); }; Window_OrangeHud.prototype.windowWidth = function() { return this.group.HudWidth; }; Window_OrangeHud.prototype.windowHeight = function() { return this.group.HudHeight; }; Window_OrangeHud.prototype.standardPadding = function() { return this.group.WindowPadding; }; Window_OrangeHud.prototype.drawTextEx = function(text, x, y) { if (text) { var textState = { index: 0, x: x, y: y, left: x }; //Adds line break support with \n textState.text = text.replace(/\\n/g, '\n'); textState.text = this.convertEscapeCharacters(textState.text); textState.height = this.calcTextHeight(textState, false); // this.resetFontSettings(); while (textState.index < textState.text.length) { this.processCharacter(textState); } return textState.x - x; } else { return 0; } }; Window_OrangeHud.prototype.drawPicture = function(filename, x, y) { var bitmap = ImageManager.loadPicture(filename); this.contents.blt(bitmap, 0, 0, bitmap._canvas.width, bitmap._canvas.height, x, y); }; Window_OrangeHud.prototype.refresh = function() { if (this.contents) { this.contents.clear(); this.drawHud(); } }; Window_OrangeHud.prototype.drawHud = function() { var self = this; this._lines = {}; for (var lineType in $._addons) { var addOn = $._addons[lineType]; addOn.params.forEach(function(line){ if (line.GroupName == self.group.GroupName || (!line.GroupName && self.group.GroupName == "main")) { addOn.manager.drawLine(self, line); addOn.lines[addOn.manager.getKey(line)] = addOn.manager.getValue(line); } }); } }; Window_OrangeHud.prototype.update = function() { Window_Base.prototype.update.call(this); var shouldRefresh = $._isDirty; var self = this; if (self.group.AutoRefresh) { for (var lineType in $._addons) { var addOn = $._addons[lineType]; addOn.params.forEach(function(line){ if (line.GroupName == self.group.GroupName || (!line.GroupName && self.group.GroupName == "main")) { var key = addOn.manager.getKey(line); var value = addOn.manager.getValue(line); if (value != addOn.lines[key]) { shouldRefresh = true; } } }); } } if (shouldRefresh) { this.refresh(); } }; $.canShowOnThisScene = function(scene) { if (scene instanceof Scene_Map) { return $.Param.ShowOnMap; } else if (scene instanceof Scene_Menu) { return $.Param.ShowOnMenu; } else if (scene instanceof Scene_Battle) { return $.Param.ShowOnBattle; } else if (scene instanceof Scene_Title) { return $.Param.ShowOnTitle; } else { return false; } }; var oldSceneBase_start = Scene_Base.prototype.start; Scene_Base.prototype.start = function() { oldSceneBase_start.call(this); if (!$.canShowOnThisScene(this)) { return; } this.createVarHudWindow(); }; Scene_Base.prototype.createVarHudWindow = function() { this._hudWindows = {}; for (var key in OrangeHud._groups) { var groups = OrangeHud._groups[key]; this._hudWindows[key] = []; for (var i = 0; i < groups.length; i++) { var group = groups[i]; var newWindow = new Window_OrangeHud(group); newWindow.x = group.HudX; newWindow.y = group.HudY; newWindow.opacity = group.HudOpacity; newWindow.padding = group.WindowPadding; newWindow.margin = group.WindowMargin; this._hudWindows[key].push(newWindow); if (this instanceof Scene_Map && group.ShowUnderTintLayer) { this._spriteset._baseSprite.addChild(newWindow); } else { this.addChild(newWindow); } if (group.SwitchId !== undefined && group.SwitchId > 0) { newWindow.visible = $gameSwitches.value(group.SwitchId); } } } }; var oldSceneBase_update = Scene_Base.prototype.update; Scene_Base.prototype.update = function() { oldSceneBase_update.call(this); if (this._hudWindows === undefined) { return; } for (var key in this._hudWindows) { var groupWindows = this._hudWindows[key]; for (var i = 0; i < groupWindows.length; i++) { var hudWindow = groupWindows[i]; if (SceneManager.isSceneChanging()) { hudWindow.visible = false; } else { if (hudWindow.group.SwitchId !== undefined && hudWindow.group.SwitchId > 0) { hudWindow.visible = $gameSwitches.value(hudWindow.group.SwitchId); } else { hudWindow.visible = true; } } hudWindow.update(); } } $._isDirty = false; }; var oldSceneMap_updateScene = Scene_Map.prototype.updateScene; Scene_Map.prototype.updateScene = function() { oldSceneMap_updateScene.call(this); if (SceneManager.isSceneChanging()) { if (this._hudWindows === undefined) { return; } for (var key in this._hudWindows) { var groupWindows = this._hudWindows[key]; for (var i = 0; i < groupWindows.length; i++) { var hudWindow = groupWindows[i]; hudWindow.visible = false; } } } }; var oldGameMap_requestRefresh = Game_Map.prototype.requestRefresh; Game_Map.prototype.requestRefresh = function(mapId) { oldGameMap_requestRefresh.call(this, mapId); $._isDirty = true; }; $.configureGroups(); })(OrangeHud); Imported.OrangeHud = 2.1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Actor Status HUD * By HUDell - www.hudell.com * OrangeHudActorStatus.js * Version: 1.5.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new line to Orange Hud to display an actor's status * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn. Click the help button for more info. * @default <hp> / <mhp> * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * ============================================================================ * Valid variables: * ============================================================================ * <hp> * <mp> * <tp> * <mhp> * <mmp> * <atk> * <def> * <mat> * <mdf> * <agi> * <luk> * <hit> * <eva> * <cri> * <cev> * <mev> * <mrf> * <cnt> * <hrg> * <mrg> * <trg> * <tgr> * <grd> * <rec> * <pha> * <mcr> * <tcr> * <pdr> * <mdr> * <fdr> * <exr> * <level> * <maxlevel> * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudActorStatus!"); } var OrangeHudActorStatusLine = OrangeHudActorStatusLine || {}; if (Imported["OrangeHudActorStatus"] === undefined) { OrangeHudActorStatusLine.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "<hp> / <mhp>"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.ActorIndex = Number(line.ActorIndex || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudActorStatusLine.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getLine(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudActorStatusLine.getLine = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var members = $gameParty.members(); if (members.length > variableData.ActorIndex) { var line = pattern; var actorData = members[variableData.ActorIndex]; line = line.replace(/\<hp\>/gi, actorData.hp); line = line.replace(/\<mp\>/gi, actorData.mp); line = line.replace(/\<tp\>/gi, actorData.tp); line = line.replace(/\<mhp\>/gi, actorData.mhp); line = line.replace(/\<mmp\>/gi, actorData.mmp); line = line.replace(/\<atk\>/gi, actorData.atk); line = line.replace(/\<def\>/gi, actorData.def); line = line.replace(/\<mat\>/gi, actorData.mat); line = line.replace(/\<mdf\>/gi, actorData.mdf); line = line.replace(/\<agi\>/gi, actorData.agi); line = line.replace(/\<luk\>/gi, actorData.luk); line = line.replace(/\<hit\>/gi, actorData.hit); line = line.replace(/\<eva\>/gi, actorData.eva); line = line.replace(/\<cri\>/gi, actorData.cri); line = line.replace(/\<cev\>/gi, actorData.cev); line = line.replace(/\<mev\>/gi, actorData.mev); line = line.replace(/\<mrf\>/gi, actorData.mrf); line = line.replace(/\<cnt\>/gi, actorData.cnt); line = line.replace(/\<hrg\>/gi, actorData.hrg); line = line.replace(/\<mrg\>/gi, actorData.mrg); line = line.replace(/\<trg\>/gi, actorData.trg); line = line.replace(/\<tgr\>/gi, actorData.tgr); line = line.replace(/\<grd\>/gi, actorData.grd); line = line.replace(/\<rec\>/gi, actorData.rec); line = line.replace(/\<pha\>/gi, actorData.pha); line = line.replace(/\<mcr\>/gi, actorData.mcr); line = line.replace(/\<tcr\>/gi, actorData.tcr); line = line.replace(/\<pdr\>/gi, actorData.pdr); line = line.replace(/\<mdr\>/gi, actorData.mdr); line = line.replace(/\<fdr\>/gi, actorData.fdr); line = line.replace(/\<exr\>/gi, actorData.exr); line = line.replace(/\<level\>/gi, actorData.level); line = line.replace(/\<maxlevel\>/gi, actorData.maxLevel()); line = line.replace(/\<exp\>/gi, actorData.currentExp()); return line; } else { return ''; } }; OrangeHudActorStatusLine.getValue = function(variableData) { return this.getLine(variableData); }; OrangeHudActorStatusLine.getKey = function(variableData) { return 'actor' + variableData.ActorIndex; }; OrangeHud.registerLineType('OrangeHudActorStatus', OrangeHudActorStatusLine); Imported.OrangeHudActorStatus = 1.5; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Actor Gauge HUD * By HUDell - www.hudell.com * OrangeHudActorGauge.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudActorGauge 1.2 - Adds a new Gauge to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param ValueExpression * @desc The expression for the the value. Click the help button for more info. * @default <hp> * * @param MaxValueExpression * @desc The expression for the the max value. Click the help button for more info. * @default <mhp> * * @param ScriptValue * @desc A script to run to get the current value of the gauge. * @default * * @param ScriptMaxValue * @desc A script to run to get the max value of the gauge. * @default * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the gauge inside the HUD * @default * * @param Y * @desc The Y position of the gauge inside the HUD * @default * * @param Width * @desc The width of the Gauge * @default 100 * * @param Direction * @desc The direction in which the gauge is filled * @default right * * @param Height * @desc The height of the Gauge * @default 6 * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @param GaugeColor1 * @desc The color (or color ID) to use on the gauge * @default 20 * * @param GaugeColor2 * @desc The color (or color ID) to use on the gauge * @default 21 * * @param AllowOverflow * @desc Set this to true if you want the gauge bar to overflow when the value is too high * @default false * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the gauge * @default true * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * ============================================================================ * Valid variables: * ============================================================================ * <hp> * <mp> * <tp> * <mhp> * <mmp> * <atk> * <def> * <mat> * <mdf> * <agi> * <luk> * <hit> * <eva> * <cri> * <cev> * <mev> * <mrf> * <cnt> * <hrg> * <mrg> * <trg> * <tgr> * <grd> * <rec> * <pha> * <mcr> * <tcr> * <pdr> * <mdr> * <fdr> * <exr> * <level> * <maxlevel> * */ var Imported = Imported || {}; if (Imported.OrangeHud === undefined) { throw new Error("Please add OrangeHud before OrangeHudActorGauge!"); } if (Imported.OrangeHud < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudActorGauge = OrangeHudActorGauge || {}; if (Imported.OrangeHudActorGauge === undefined) { OrangeHudActorGauge.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ValueExpression = paramsLine.ValueExpression || ""; paramsLine.MaxValueExpression = paramsLine.MaxValueExpression || ""; paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.Width = Number(paramsLine.Width || 0); paramsLine.Height = Number(paramsLine.Height || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); if (!paramsLine.Direction) { paramsLine.Direction = 'right'; } else { paramsLine.Direction = paramsLine.Direction.toLowerCase().trim(); if (paramsLine.Direction !== 'left' && paramsLine.Direction !== 'up' && paramsLine.Direction !== 'down') { paramsLine.Direction = 'right'; } } if (paramsLine.ScriptValue !== undefined && paramsLine.ScriptValue.trim() === "") { paramsLine.ScriptValue = undefined; } else { paramsLine.ScriptValue = Function("return " + paramsLine.ScriptValue); // jshint ignore:line } if (paramsLine.ScriptMaxValue !== undefined && paramsLine.ScriptMaxValue.trim() === "") { paramsLine.ScriptMaxValue = undefined; } else { paramsLine.ScriptMaxValue = Function("return " + paramsLine.ScriptMaxValue); //jshint ignore:line } paramsLine.AllowOverflow = paramsLine.AllowOverflow === "true"; paramsLine.AutoRefresh = paramsLine.AutoRefresh !== "false"; if (!paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = 20; } else if (parseInt(paramsLine.GaugeColor1, 10) == paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = parseInt(paramsLine.GaugeColor1, 10); } if (!paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = 21; } else if (parseInt(paramsLine.GaugeColor2, 10) == paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = parseInt(paramsLine.GaugeColor2, 10); } }; OrangeHudActorGauge.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudActorGauge.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudActorGauge.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } this.drawGauge(hudWindow, variableData); }; OrangeHudActorGauge.getRealColor = function(hudWindow, color) { if (typeof(color) == "number") { return hudWindow.textColor(color); } else { return color; } }; OrangeHudActorGauge.drawGauge = function(hudWindow, variableData) { var x = this.realX(variableData); var y = this.realY(variableData); var color1 = this.getRealColor(hudWindow, variableData.GaugeColor1); var color2 = this.getRealColor(hudWindow, variableData.GaugeColor2); var value = this.getCurrentValue(variableData); var maxValue = this.getMaxValue(variableData); var rate; var width = variableData.Width; var height = variableData.Height; if (maxValue > 0) { rate = parseFloat((value / maxValue).toPrecision(12)); } else { rate = 0; } if (isNaN(rate)) { rate = 0; } if (!variableData.AllowOverflow) { rate = rate.clamp(0, 1); } if (width > 0 && height > 0) { var fillW; var fillH; var fillX = x; var gaugeY = y; var fillY = gaugeY; if (variableData.Direction === 'left' || variableData.Direction === 'right') { fillW = Math.floor(width * rate); fillH = height; if (variableData.Direction === 'left') { fillX = fillX + width - fillW; } } else { fillW = width; fillH = Math.floor(height * rate); if (variableData.Direction == 'up') { fillY = fillY + height - fillH; } } hudWindow.contents.fillRect(x, gaugeY, width, height, hudWindow.gaugeBackColor()); hudWindow.contents.gradientFillRect(fillX, fillY, fillW, fillH, color1, color2); } }; OrangeHudActorGauge.getValue = function(variableData) { if (variableData.AutoRefresh) { return this.getCurrentValue(variableData) + ' / ' + this.getMaxValue(variableData); } else { return 0; } }; OrangeHudActorGauge.getCurrentValue = function(variableData) { if (variableData.ScriptValue !== undefined) { if (typeof(variableData.ScriptValue) == "function") { return parseFloat(variableData.ScriptValue()); } else { return parseFloat(Function("return " + variableData.ScriptValue)()); //jshint ignore:line } } else { return OrangeHudActorGauge.getActorValue(variableData, variableData.ValueExpression); } }; OrangeHudActorGauge.getActorValue = function(variableData, expression) { var members = $gameParty.members(); if (members.length > variableData.ActorIndex) { var actorData = members[variableData.ActorIndex]; expression = expression.replace(/<hp>/gi, actorData.hp); expression = expression.replace(/<mp>/gi, actorData.mp); expression = expression.replace(/<tp>/gi, actorData.tp); expression = expression.replace(/<mhp>/gi, actorData.mhp); expression = expression.replace(/<mmp>/gi, actorData.mmp); expression = expression.replace(/<atk>/gi, actorData.atk); expression = expression.replace(/<def>/gi, actorData.def); expression = expression.replace(/<mat>/gi, actorData.mat); expression = expression.replace(/<mdf>/gi, actorData.mdf); expression = expression.replace(/<agi>/gi, actorData.agi); expression = expression.replace(/<luk>/gi, actorData.luk); expression = expression.replace(/<hit>/gi, actorData.hit); expression = expression.replace(/<eva>/gi, actorData.eva); expression = expression.replace(/<cri>/gi, actorData.cri); expression = expression.replace(/<cev>/gi, actorData.cev); expression = expression.replace(/<mev>/gi, actorData.mev); expression = expression.replace(/<mrf>/gi, actorData.mrf); expression = expression.replace(/<cnt>/gi, actorData.cnt); expression = expression.replace(/<hrg>/gi, actorData.hrg); expression = expression.replace(/<mrg>/gi, actorData.mrg); expression = expression.replace(/<trg>/gi, actorData.trg); expression = expression.replace(/<tgr>/gi, actorData.tgr); expression = expression.replace(/<grd>/gi, actorData.grd); expression = expression.replace(/<rec>/gi, actorData.rec); expression = expression.replace(/<pha>/gi, actorData.pha); expression = expression.replace(/<mcr>/gi, actorData.mcr); expression = expression.replace(/<tcr>/gi, actorData.tcr); expression = expression.replace(/<pdr>/gi, actorData.pdr); expression = expression.replace(/<mdr>/gi, actorData.mdr); expression = expression.replace(/<fdr>/gi, actorData.fdr); expression = expression.replace(/<exr>/gi, actorData.exr); expression = expression.replace(/<level>/gi, actorData.level); expression = expression.replace(/<maxlevel>/gi, actorData.maxLevel()); expression = expression.replace(/<exp>/gi, actorData.currentExp()); try { return parseFloat(Function("return " + expression)()); //jshint ignore:line } catch(e) { console.error(e); return 0; } } else { return 0; } }; OrangeHudActorGauge.getMaxValue = function(variableData) { if (variableData.ScriptMaxValue !== undefined) { if (typeof(variableData.ScriptMaxValue) == "function") { return parseFloat(variableData.ScriptMaxValue()); } else { return parseFloat(Function("return " + variableData.ScriptMaxValue)()); //jshint ignore:line } } else { return OrangeHudActorGauge.getActorValue(variableData, variableData.MaxValueExpression); } }; OrangeHudActorGauge.getKey = function(variableData) { return variableData.ValueVariableId; }; OrangeHud.registerLineType('OrangeHudActorGauge', OrangeHudActorGauge); Imported.OrangeHudActorGauge = 1.0; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Gold HUD * By HUDell - www.hudell.com * OrangeHudGold.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds the Gold value to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudGold!"); } var OrangeHudGoldLine = OrangeHudGoldLine || {}; if (Imported["OrangeHudGold"] === undefined) { OrangeHudGoldLine.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudGoldLine.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var line = pattern.format($gameParty.gold()); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudGoldLine.getValue = function(variableData) { return $gameParty.gold(); }; OrangeHudGoldLine.getKey = function(variableData) { return 'gold'; }; OrangeHud.registerLineType('OrangeHudGold', OrangeHudGoldLine); Imported["OrangeHudGold"] = 1.1; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Script Icon HUD * By HUDell - www.hudell.com * OrangeHudScriptIcon.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Script Icon to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ScriptCall * @desc A script that when called should result in the index of the icon that should be displayed. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param VariableX * @desc The number of the variable that holds the X position of the Icon inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the Icon inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudScriptIcon!"); } var OrangeHudScriptIcon = OrangeHudScriptIcon || {}; if (Imported["OrangeHudScriptIcon"] === undefined) { OrangeHudScriptIcon.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ScriptCall = paramsLine.ScriptCall || "1"; if (typeof(paramsLine.ScriptCall) !== "string") { paramsLine.ScriptCall = paramsLine.ScriptCall.toString(); } paramsLine.ScriptCall = paramsLine.ScriptCall.trim(); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); }; OrangeHudScriptIcon.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudScriptIcon.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudScriptIcon.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var iconindex; try { iconindex = Function("return " + variableData.ScriptCall)(); } catch(e) { iconindex = 0; } x = this.realX(variableData); y = this.realY(variableData); if (iconindex >= 0) { this.drawIcon(hudWindow, iconindex, x, y, variableData); } }; OrangeHudScriptIcon.drawIcon = function(hudWindow, iconindex, x, y, variableData) { hudWindow.drawIcon(iconindex, x, y); }; OrangeHudScriptIcon.getValue = function(variableData) { if (variableData.VariableId > 0) { return $gameVariables.value(variableData.VariableId); } else { return 0; } }; OrangeHudScriptIcon.getIconIndex = function(variableData) { var varValue = -1; if (variableData.VariableId > 0) { varValue = Number($gameVariables.value(variableData.VariableId)); } return varValue; }; OrangeHudScriptIcon.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudScriptIcon', OrangeHudScriptIcon); Imported["OrangeHudScriptIcon"] = 1.0; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Line HUD * By HUDell - www.hudell.com * OrangeHudLine.js * Version: 1.6 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudLine 1.5 - Adds a new Variable to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1 * * @param VariableId * @desc The number of the variable that will be displayed on this line. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/hud-line * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudLine!"); } var OrangeHudDefaultLine = OrangeHudDefaultLine || {}; if (Imported["OrangeHudLine"] === undefined) { OrangeHudDefaultLine.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableId = Number(line.VariableId || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.VariableX = Number(line.VariableX || 0); line.VariableY = Number(line.VariableY || 0); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudDefaultLine.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var line = pattern.format($gameVariables.value(variableData.VariableId)); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, this.realX(variableData), this.realY(variableData)); window.resetFontSettings(); }; OrangeHudDefaultLine.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudDefaultLine.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudDefaultLine.getValue = function(variableData) { return $gameVariables.value(variableData.VariableId); }; OrangeHudDefaultLine.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudLine', OrangeHudDefaultLine); Imported["OrangeHudLine"] = 1.6; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - HUD Group * By HUDell - www.hudell.com * OrangeHudGroup.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc v1.0 - Adds a new group of lines to create a different hud * @author Hudell * * @param GroupName * @desc The name of this HUD group. Don't use special characters. * @default group * * @param DefaultFontFace * @desc The font face to use by default * @default Verdana * * @param DefaultFontSize * @desc The font size to use by default * @default 18 * * @param DefaultFontColor * @desc The font color to use by default * @default #FFFFFF * * @param DefaultFontItalic * @desc Should use italic by default? * @default false * * @param HudWidth * @desc The width of the hud. 0 == 100% * @default 0 * * @param HudHeight * @desc The height of the hud. 0 == 100% * @default 0 * * @param HudX * @desc The X position of the hud * @default 0 * * @param HudY * @desc The Y position of the hud * @default 0 * * @param HudOpacity * @desc The Opacity of the hud * @default 0 * * @param SwitchId * @desc Number of a switch to hide / show the hud * @default 0 * * @param WindowMargin * @desc The number of pixels to use on the margin of the hud window * @default 4 * * @param WindowPadding * @desc The number of pixels to use on the padding of the hud window * @default 18 * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the HUD * @default true * * @param ShowUnderTintLayer * @desc Set this to true to hide the HUD under tint and face effects * @default false * * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Fixed Picture HUD * By HUDell - www.hudell.com * OrangeHudFixedPicture.js * Version: 1.6 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Fixed Picture to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param FileName * @desc The picture filename that will be drawn * @default * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this picture * @default 0 * * @param X * @desc The X position of the picture inside the HUD * @default * * @param Y * @desc The Y position of the picture inside the HUD * @default * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/hud-line-picture * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudFixedPicture!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudFixedPicture = OrangeHudFixedPicture || {}; if (Imported["OrangeHudFixedPicture"] === undefined) { OrangeHudFixedPicture.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.FileName === undefined) { line.FileName = ""; } else if (line.FileName.trim() === "") { line.FileName = ""; } line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudFixedPicture.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } if (variableData.FileName !== "") { var bitmap = ImageManager.loadPicture(variableData.FileName); bitmap.addLoadListener(function(){ OrangeHud.setDirty(); }); window.drawPicture(variableData.FileName, variableData.X, variableData.Y); } }; OrangeHudFixedPicture.getValue = function(variableData) { return 0; }; OrangeHudFixedPicture.getKey = function(variableData) { return 'fixed-picture'; }; OrangeHud.registerLineType('OrangeHudFixedPicture', OrangeHudFixedPicture); Imported["OrangeHudFixedPicture"] = 1.6; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Date HUD * By HUDell - www.hudell.com * OrangeHudDate.js * Version: 1.5 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1/%2/%3 * * @param VariableDay * @desc The number of the variable that holds the Day value. * @default 0 * * @param VariableMonth * @desc The number of the variable that holds the Month value. * @default 0 * * @param VariableYear * @desc The number of the variable that holds the Year value. * @default 0 * * @param YearDigits * @desc The number of digits to display on the year number. * @default 4 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudDate!"); } var OrangeHudDate = OrangeHudDate || {}; if (Imported["OrangeHudDate"] === undefined) { OrangeHudDate.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1/%2/%3"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableDay = Number(line.VariableDay || 0); line.VariableMonth = Number(line.VariableMonth || 0); line.VariableYear = Number(line.VariableYear || 0); line.YearDigits = Number(line.YearDigits || 4); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudDate.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getValue(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudDate.getValue = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var day = ''; var month = ''; var year = ''; if (variableData.VariableDay > 0) { day = $gameVariables.value(variableData.VariableDay); if (typeof(day) == "number" || parseInt(day, 10) == day) { day = Number(day).padZero(2); } } if (variableData.VariableMonth > 0) { month = $gameVariables.value(variableData.VariableMonth); if (typeof(month) == "number" || parseInt(month, 10) == month) { month = Number(month).padZero(2); } } if (variableData.VariableYear > 0) { year = Number($gameVariables.value(variableData.VariableYear)).padZero(variableData.YearDigits); } return pattern.format(day, month, year); }; OrangeHudDate.getKey = function(variableData) { return variableData.VariableYear + ',' + variableData.VariableMonth + ',' + variableData.VariableDay; }; OrangeHud.registerLineType('OrangeHudDate', OrangeHudDate); Imported["OrangeHudDate"] = 1.5; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Aligned Line HUD * By HUDell - www.hudell.com * OrangeHudAlignedLine.js * Version: 1.1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudAlignedLine 1.0 - Adds a new Variable to Orange Hud with alignment support * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1 * * @param VariableId * @desc The number of the variable that will be displayed on this line. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param Width * @desc The Width of the line text. Required. * @default 0 * * @param Align * @desc The type of alignment. Left, Right or Center. * @default center * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @param VariableX * @desc The number of the variable that holds the X position of the text inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the text inside the HUD * @default 0 * * @param VariableWidth * @desc The number of the variable that holds the width of the text inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudAlignedLine!"); } var OrangeHudAlignedLine = OrangeHudAlignedLine || {}; if (Imported["OrangeHudAlignedLine"] === undefined) { OrangeHudAlignedLine.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableId = Number(line.VariableId || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.VariableX = Number(line.VariableX || 0); line.VariableWidth = Number(line.VariableWidth || 0); line.VariableY = Number(line.VariableY || 0); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); line.Width = Number(line.Width || 0); line.Align = line.Align.toLowerCase(); if (line.Align != 'right' && line.Align != 'center') { line.Align = 'left'; } if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudAlignedLine.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var line = pattern.format($gameVariables.value(variableData.VariableId)); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawText(line, this.realX(variableData), this.realY(variableData), this.realWidth(variableData), variableData.Align); window.resetFontSettings(); }; OrangeHudAlignedLine.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudAlignedLine.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudAlignedLine.realWidth = function(variableData) { var width = variableData.Width; if (variableData.VariableWidth > 0) { width = $gameVariables.value(variableData.VariableWidth); } return width; }; OrangeHudAlignedLine.getValue = function(variableData) { return $gameVariables.value(variableData.VariableId); }; OrangeHudAlignedLine.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudAlignedLine', OrangeHudAlignedLine); Imported["OrangeHudAlignedLine"] = 1.0; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Face Picture HUD * By HUDell - www.hudell.com * OrangeHudFacePicture.js * Version: 1.3.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Draws a character's face on the OrangeHud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ActorIndex * @desc The index of the actor in the party. If the index is invalid, nothing will be shown * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudFacePicture!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudFacePicture = OrangeHudFacePicture || {}; if (Imported["OrangeHudFacePicture"] === undefined) { OrangeHudFacePicture.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ActorIndex = Number(paramsLine.ActorIndex || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); }; OrangeHudFacePicture.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudFacePicture.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudFacePicture.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var fileData = this.getValue(variableData); if (fileData !== false) { x = this.realX(variableData); y = this.realY(variableData); var bitmap = ImageManager.loadFace(fileData[0]); bitmap.addLoadListener(function(){ OrangeHud.setDirty(); }); hudWindow.drawFace(fileData[0], fileData[1], x, y); } }; OrangeHudFacePicture.drawPicture = function(hudWindow, filename, x, y, variableData) { hudWindow.drawPicture(filename, x, y); }; OrangeHudFacePicture.getValue = function(variableData) { if (variableData.ActorIndex >= 0) { var members = $gameParty.members(); if (variableData.ActorIndex < members.length) { var faceName = members[variableData.ActorIndex]._faceName; var faceIndex = members[variableData.ActorIndex]._faceIndex; return [faceName, faceIndex]; } } return false; }; OrangeHudFacePicture.getKey = function(variableData) { return variableData.ActorIndex; }; OrangeHud.registerLineType('OrangeHudFacePicture', OrangeHudFacePicture); Imported["OrangeHudFacePicture"] = 1.3; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Variable Picture HUD * By HUDell - www.hudell.com * OrangeHudVariablePicture.js * Version: 1.6 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudVariablePicture 1.5.1 - Adds a new Variable Picture to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the picture file name that will be drawn * @default %1 * * @param VariableId * @desc The number of the variable that will be used to control this picture. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param ScriptPattern * @desc A script call to be used to decide the filename of the picture instead of the pattern * @default * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @param CommonEventId * @desc Number of a common event to call if the player clicks on this picture * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudVariablePicture!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudVariablePicture = OrangeHudVariablePicture || {}; if (Imported["OrangeHudVariablePicture"] === undefined) { OrangeHudVariablePicture.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; if (paramsLine.ScriptPattern !== undefined && paramsLine.ScriptPattern.trim() === "") { paramsLine.ScriptPattern = undefined; } if (paramsLine.Pattern === undefined) { paramsLine.Pattern = "%1"; } else if (paramsLine.Pattern.trim() === "") { paramsLine.Pattern = ""; } paramsLine.VariableId = Number(paramsLine.VariableId || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.CommonEventId = Number(paramsLine.CommonEventId || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); if (paramsLine.CommonEventId > 0) { var key = OrangeHudVariablePicture.getKey(paramsLine); this.images = this.images || {}; this.images[key] = this.images[key] || {}; var alias = TouchInput._onMouseDown; var me = this; TouchInput._onMouseDown = function(event) { if (paramsLine.SwitchId > 0) { if (!$gameSwitches.value(paramsLine.SwitchId)) { return; } } var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); var width = me.images[key].width; var height = me.images[key].height; if (width !== undefined && height !== undefined) { var imageX = me.realX(paramsLine) + OrangeHud.Param.HudX + OrangeHud.Param.WindowMargin + OrangeHud.Param.WindowPadding; var imageY = me.realY(paramsLine) + OrangeHud.Param.HudY + OrangeHud.Param.WindowMargin + OrangeHud.Param.WindowPadding; if (x >= imageX && y >= imageY) { if (x <= imageX + width && y <= imageY + height) { $gameTemp.reserveCommonEvent(paramsLine.CommonEventId); return; } } } // If the click wasn't triggered, call the alias to keep the mouseDown event happening alias.call(this, event); }; } }; OrangeHudVariablePicture.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudVariablePicture.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudVariablePicture.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var filename = this.getFileName(variableData); x = this.realX(variableData); y = this.realY(variableData); var bitmap = ImageManager.loadPicture(filename); bitmap.addLoadListener(function(){ OrangeHud.setDirty(); }); var key = OrangeHudVariablePicture.getKey(variableData); this.images = this.images || {}; this.images[key] = this.images[key] || {}; this.images[key].width = bitmap._canvas.width; this.images[key].height = bitmap._canvas.height; this.drawPicture(hudWindow, filename, x, y, variableData); }; OrangeHudVariablePicture.drawPicture = function(hudWindow, filename, x, y, variableData) { hudWindow.drawPicture(filename, x, y); }; OrangeHudVariablePicture.getValue = function(variableData) { if (variableData.VariableId > 0) { return $gameVariables.value(variableData.VariableId); } else { return 0; } }; OrangeHudVariablePicture.getFileName = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var varValue = ''; if (variableData.VariableId > 0) { varValue = Number($gameVariables.value(variableData.VariableId)); } return pattern.format(varValue); }; OrangeHudVariablePicture.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudVariablePicture', OrangeHudVariablePicture); Imported["OrangeHudVariablePicture"] = 1.6; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Clock HUD * By HUDell - www.hudell.com * OrangeHudClock.js * Version: 1.5 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param Pattern * @desc The pattern of the line that will be drawn * @default %1:%2:%3 * * @param VariableHour * @desc The number of the variable that holds the Hour value. * @default 0 * * @param VariableMinute * @desc The number of the variable that holds the Minute value. * @default 0 * * @param VariableSecond * @desc The number of the variable that holds the Second value. * @default 0 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param ScriptPattern * @desc A script call to be used instead of the Pattern * @default * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudClock!"); } var OrangeHudClock = OrangeHudClock || {}; if (Imported["OrangeHudClock"] === undefined) { OrangeHudClock.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.ScriptPattern !== undefined && line.ScriptPattern.trim() === "") { line.ScriptPattern = undefined; } if (line.Pattern === undefined) { line.Pattern = "%1:%2:%3"; } else if (line.Pattern.trim() === "") { line.Pattern = ""; } line.VariableHour = Number(line.VariableHour || 0); line.VariableMinute = Number(line.VariableMinute || 0); line.VariableSecond = Number(line.VariableSecond || 0); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || line.FontItalic.trim() === "") { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudClock.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var line = this.getValue(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); window.drawTextEx(line, variableData.X, variableData.Y); window.resetFontSettings(); }; OrangeHudClock.getValue = function(variableData) { var pattern = variableData.Pattern; if (variableData.ScriptPattern !== undefined) { pattern = Function("return " + variableData.ScriptPattern)(); } var hour = ''; var minute = ''; var second = ''; if (variableData.VariableHour > 0) { hour = Number($gameVariables.value(variableData.VariableHour)).padZero(2); } if (variableData.VariableMinute > 0) { minute = Number($gameVariables.value(variableData.VariableMinute)).padZero(2); } if (variableData.VariableSecond > 0) { second = Number($gameVariables.value(variableData.VariableSecond)).padZero(2); } return pattern.format(hour, minute, second); }; OrangeHudClock.getKey = function(variableData) { return variableData.VariableHour + ',' + variableData.VariableMinute + ',' + variableData.VariableSecond; }; OrangeHud.registerLineType('OrangeHudClock', OrangeHudClock); Imported["OrangeHudClock"] = 1.5; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Line Group HUD * By HUDell - www.hudell.com * OrangeHudLineGroup.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds Several new Variables to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param DefaultPattern * @desc The pattern of each line that will be drawn * @default %1 * * @param VariableList * @desc The list of variables that should be displayed, separated by comma * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this group * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param FontFace * @desc The font face to use. Leave empty to use the HUD default * @default * * @param FontSize * @desc The font size to use. Leave empty to use the HUD default * @default * * @param FontColor * @desc The font color to use. Leave empty to use the HUD default * @default * * @param FontItalic * @desc Should use italic? Leave empty to use the HUD default * @default * * @param LineHeight * @desc The Y distance between each line on the group * @default 24 * * @param LineWidth * @desc The X distance between each line on the group * @default 0 * * @param UseScriptPattern * @desc If true, the pattern lines will be evaluated as scripts * @default false * * @param PatternLine1 * @desc The pattern of the line 1. Leave empty to use the default pattern. * @default * * @param PatternLine2 * @desc The pattern of the line 2. Leave empty to use the default pattern. * @default * * @param PatternLine3 * @desc The pattern of the line 3. Leave empty to use the default pattern. * @default * * @param PatternLine4 * @desc The pattern of the line 4. Leave empty to use the default pattern. * @default * * @param PatternLine5 * @desc The pattern of the line 5. Leave empty to use the default pattern. * @default * * @param PatternLine6 * @desc The pattern of the line 6. Leave empty to use the default pattern. * @default * * @param PatternLine7 * @desc The pattern of the line 7. Leave empty to use the default pattern. * @default * * @param PatternLine8 * @desc The pattern of the line 8. Leave empty to use the default pattern. * @default * * @param PatternLine9 * @desc The pattern of the line 9. Leave empty to use the default pattern. * @default * * @param PatternLine10 * @desc The pattern of the line 10. Leave empty to use the default pattern. * @default * * @param VariableXGroup * @desc The number of the variable that holds the X position of the line group inside the HUD * @default 0 * * @param VariableYGroup * @desc The number of the variable that holds the Y position of the line group inside the HUD * @default 0 * * @param VariableXLine1 * @desc The number of the variable that holds the X position of the line 1 inside the HUD * @default 0 * * @param VariableXLine2 * @desc The number of the variable that holds the X position of the line 2 inside the HUD * @default 0 * * @param VariableXLine3 * @desc The number of the variable that holds the X position of the line 3 inside the HUD * @default 0 * * @param VariableXLine4 * @desc The number of the variable that holds the X position of the line 4 inside the HUD * @default 0 * * @param VariableXLine5 * @desc The number of the variable that holds the X position of the line 5 inside the HUD * @default 0 * * @param VariableXLine6 * @desc The number of the variable that holds the X position of the line 6 inside the HUD * @default 0 * * @param VariableXLine7 * @desc The number of the variable that holds the X position of the line 7 inside the HUD * @default 0 * * @param VariableXLine8 * @desc The number of the variable that holds the X position of the line 8 inside the HUD * @default 0 * * @param VariableXLine9 * @desc The number of the variable that holds the X position of the line 9 inside the HUD * @default 0 * * @param VariableXLine10 * @desc The number of the variable that holds the X position of the line 10 inside the HUD * @default 0 * * @param VariableYLine1 * @desc The number of the variable that holds the Y position of the line 1 inside the HUD * @default 0 * * @param VariableYLine2 * @desc The number of the variable that holds the Y position of the line 2 inside the HUD * @default 0 * * @param VariableYLine3 * @desc The number of the variable that holds the Y position of the line 3 inside the HUD * @default 0 * * @param VariableYLine4 * @desc The number of the variable that holds the Y position of the line 4 inside the HUD * @default 0 * * @param VariableYLine5 * @desc The number of the variable that holds the Y position of the line 5 inside the HUD * @default 0 * * @param VariableYLine6 * @desc The number of the variable that holds the Y position of the line 6 inside the HUD * @default 0 * * @param VariableYLine7 * @desc The number of the variable that holds the Y position of the line 7 inside the HUD * @default 0 * * @param VariableYLine8 * @desc The number of the variable that holds the Y position of the line 8 inside the HUD * @default 0 * * @param VariableYLine9 * @desc The number of the variable that holds the Y position of the line 9 inside the HUD * @default 0 * * @param VariableYLine10 * @desc The number of the variable that holds the Y position of the line 10 inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudLineGroup!"); } var OrangeHudLineGroup = OrangeHudLineGroup || {}; if (Imported["OrangeHudLineGroup"] === undefined) { OrangeHudLineGroup.validateParams = function(line) { line.GroupName = line.GroupName || "main"; if (line.DefaultPattern === undefined) { line.DefaultPattern = "%1"; } else if (line.DefaultPattern.trim() === "") { line.DefaultPattern = ""; } if (line.UseScriptPattern === undefined || line.UseScriptPattern !== 'true') { line.UseScriptPattern = false; } else { line.UseScriptPattern = true; } line.VariableList = line.VariableList.split(','); if (line.FontFace === undefined || line.FontFace.trim() === "") { line.FontFace = OrangeHud.Param.DefaultFontFace; } if (line.FontColor === undefined || line.FontColor.trim() === "") { line.FontColor = OrangeHud.Param.DefaultFontColor; } line.FontSize = Number(line.FontSize || OrangeHud.Param.DefaultFontSize); line.VariableXGroup = Number(line.VariableXGroup || 0); line.VariableYGroup = Number(line.VariableYGroup || 0); line.LineHeight = Number(line.LineHeight || line.FontSize + 4); line.LineWidth = Number(line.LineWidth || 0); line.X = Number(line.X || 0); line.Y = Number(line.Y || 0); if (line.FontItalic === undefined || (typeof line.FontItalic == "string" && line.FontItalic.trim() === "")) { line.FontItalic = OrangeHud.Param.DefaultFontItalic; } else { line.FontItalic = line.FontItalic == "true"; } line.SwitchId = Number(line.SwitchId || 0); }; OrangeHudLineGroup.drawLine = function(window, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var defaultPattern = variableData.DefaultPattern; var x = OrangeHudLineGroup.realX(variableData); var y = OrangeHudLineGroup.realY(variableData); window.contents.fontFace = variableData.FontFace; window.contents.fontSize = variableData.FontSize; window.contents.fontItalic = variableData.FontItalic; window.changeTextColor(variableData.FontColor); for (var i = 0; i < variableData.VariableList.length; i++) { var lineNumber = (i + 1) % 10; if (lineNumber === 0) lineNumber = 10; var pattern = variableData['PatternLine' + lineNumber]; if (pattern === undefined || pattern === "") { pattern = defaultPattern; } if (variableData.UseScriptPattern) { pattern = Function("return " + pattern)(); // jshint ignore:line } var variableId = parseInt(variableData.VariableList[i], 10); if (variableId > 0) { var line = pattern.format($gameVariables.value(variableId)); var customX = variableData['VariableXLine' + lineNumber]; if (customX === undefined || customX === "") { customX = x; } else { customX = Number(customX); if (isNaN(customX) || customX === 0) { customX = x; } else { customX = $gameVariables.value(customX); } } var customY = variableData['VariableYLine' + lineNumber]; if (customY === undefined || customY === "") { customY = y; } else { customY = Number(customY); if (isNaN(customY) || customY === 0) { customY = y; } else { customY = $gameVariables.value(customY); } } window.drawTextEx(line, customX, customY); y += variableData.LineHeight; x += variableData.LineWidth; } } window.resetFontSettings(); }; OrangeHudLineGroup.getValue = function(variableData) { var values = []; for (var i = 0; i < variableData.VariableList.length; i++) { var variableId = parseInt(variableData.VariableList[i], 10); if (variableId > 0) { values.push($gameVariables.value(variableId)); } else { values.push(0); } } return values.join(','); }; OrangeHudLineGroup.realX = function(variableData) { var x = variableData.X; if (variableData.VariableXGroup > 0) { x = $gameVariables.value(variableData.VariableXGroup); } return x; }; OrangeHudLineGroup.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableYGroup > 0) { y = $gameVariables.value(variableData.VariableYGroup); } return y; }; OrangeHudLineGroup.getKey = function(variableData) { return variableData.VariableList.join(','); }; OrangeHud.registerLineType('OrangeHudLineGroup', OrangeHudLineGroup); Imported["OrangeHudLineGroup"] = 1.3; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Variable Icon HUD * By HUDell - www.hudell.com * OrangeHudVariableIcon.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds a new Variable Icon to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param VariableId * @desc The number of the variable that will be used to control this Icon. * @default 1 * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the variable line inside the HUD * @default * * @param Y * @desc The Y position of the variable line inside the HUD * @default * * @param VariableX * @desc The number of the variable that holds the X position of the Icon inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the Icon inside the HUD * @default 0 * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudVariableIcon!"); } var OrangeHudVariableIcon = OrangeHudVariableIcon || {}; if (Imported["OrangeHudVariableIcon"] === undefined) { OrangeHudVariableIcon.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.VariableId = Number(paramsLine.VariableId || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); }; OrangeHudVariableIcon.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudVariableIcon.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudVariableIcon.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } var iconindex = this.getIconIndex(variableData); x = this.realX(variableData); y = this.realY(variableData); if (iconindex >= 0) { this.drawIcon(hudWindow, iconindex, x, y, variableData); } }; OrangeHudVariableIcon.drawIcon = function(hudWindow, iconindex, x, y, variableData) { hudWindow.drawIcon(iconindex, x, y); }; OrangeHudVariableIcon.getValue = function(variableData) { if (variableData.VariableId > 0) { return $gameVariables.value(variableData.VariableId); } else { return 0; } }; OrangeHudVariableIcon.getIconIndex = function(variableData) { var varValue = -1; if (variableData.VariableId > 0) { varValue = Number($gameVariables.value(variableData.VariableId)); } return varValue; }; OrangeHudVariableIcon.getKey = function(variableData) { return variableData.VariableId; }; OrangeHud.registerLineType('OrangeHudVariableIcon', OrangeHudVariableIcon); Imported["OrangeHudVariableIcon"] = 1.1; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Gauge HUD * By HUDell - www.hudell.com * OrangeHudGauge.js * Version: 1.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc OrangeHudGauge 1.2 - Adds a new Gauge to Orange Hud * @author Hudell * * @param GroupName * @desc The name of the HUD group where this line should be displayed * @default main * * @param ValueVariableId * @desc The number of the variable that holds the value of the gauge. * @default 1 * * @param MaxValueVariableId * @desc The number of the variable that holds the maximum value of the gauge. * @default 2 * * @param ScriptValue * @desc A script to run to get the current value of the gauge. * @default * * @param ScriptMaxValue * @desc A script to run to get the max value of the gauge. * @default * * @param SwitchId * @desc Set this to a switch number to use it to control the visibility of this line * @default 0 * * @param X * @desc The X position of the gauge inside the HUD * @default * * @param Y * @desc The Y position of the gauge inside the HUD * @default * * @param Width * @desc The width of the Gauge * @default 100 * * @param Direction * @desc The direction in which the gauge is filled * @default right * * @param Height * @desc The height of the Gauge * @default 6 * * @param VariableX * @desc The number of the variable that holds the X position of the picture inside the HUD * @default 0 * * @param VariableY * @desc The number of the variable that holds the Y position of the picture inside the HUD * @default 0 * * @param GaugeColor1 * @desc The color (or color ID) to use on the gauge * @default 20 * * @param GaugeColor2 * @desc The color (or color ID) to use on the gauge * @default 21 * * @param AllowOverflow * @desc Set this to true if you want the gauge bar to overflow when the value is too high * @default false * * @param AutoRefresh * @desc Set this to false to disable automatic refresh of the gauge * @default true * * @help * ============================================================================ * My Blog: * ============================================================================ * http://hudell.com * */ var Imported = Imported || {}; if (Imported["OrangeHud"] === undefined) { throw new Error("Please add OrangeHud before OrangeHudGauge!"); } if (Imported["OrangeHud"] < 1.7) { throw new Error("Please update OrangeHud!"); } var OrangeHudGauge = OrangeHudGauge || {}; if (Imported["OrangeHudGauge"] === undefined) { OrangeHudGauge.validateParams = function(paramsLine) { paramsLine.GroupName = paramsLine.GroupName || "main"; paramsLine.ValueVariableId = Number(paramsLine.ValueVariableId || 0); paramsLine.MaxValueVariableId = Number(paramsLine.MaxValueVariableId || 0); paramsLine.X = Number(paramsLine.X || 0); paramsLine.Y = Number(paramsLine.Y || 0); paramsLine.Width = Number(paramsLine.Width || 0); paramsLine.Height = Number(paramsLine.Height || 0); paramsLine.VariableX = Number(paramsLine.VariableX || 0); paramsLine.VariableY = Number(paramsLine.VariableY || 0); paramsLine.SwitchId = Number(paramsLine.SwitchId || 0); if (!paramsLine.Direction) { paramsLine.Direction = 'right'; } else { paramsLine.Direction = paramsLine.Direction.toLowerCase().trim(); if (paramsLine.Direction !== 'left' && paramsLine.Direction !== 'up' && paramsLine.Direction !== 'down') { paramsLine.Direction = 'right'; } } if (paramsLine.ScriptValue !== undefined && paramsLine.ScriptValue.trim() === "") { paramsLine.ScriptValue = undefined; } else { paramsLine.ScriptValue = Function("return " + paramsLine.ScriptValue); } if (paramsLine.ScriptMaxValue !== undefined && paramsLine.ScriptMaxValue.trim() === "") { paramsLine.ScriptMaxValue = undefined; } else { paramsLine.ScriptMaxValue = Function("return " + paramsLine.ScriptMaxValue); } paramsLine.AllowOverflow = paramsLine.AllowOverflow === "true"; paramsLine.AutoRefresh = paramsLine.AutoRefresh !== "false"; if (!paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = 20; } else if (parseInt(paramsLine.GaugeColor1, 10) == paramsLine.GaugeColor1) { paramsLine.GaugeColor1 = parseInt(paramsLine.GaugeColor1, 10); } if (!paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = 21; } else if (parseInt(paramsLine.GaugeColor2, 10) == paramsLine.GaugeColor2) { paramsLine.GaugeColor2 = parseInt(paramsLine.GaugeColor2, 10); } }; OrangeHudGauge.realX = function(variableData) { var x = variableData.X; if (variableData.VariableX > 0) { x = $gameVariables.value(variableData.VariableX); } return x; }; OrangeHudGauge.realY = function(variableData) { var y = variableData.Y; if (variableData.VariableY > 0) { y = $gameVariables.value(variableData.VariableY); } return y; }; OrangeHudGauge.drawLine = function(hudWindow, variableData) { if (variableData.SwitchId > 0) { if (!$gameSwitches.value(variableData.SwitchId)) { return; } } this.drawGauge(hudWindow, variableData); }; OrangeHudGauge.getRealColor = function(hudWindow, color) { if (typeof(color) == "number") { return hudWindow.textColor(color); } else { return color; } }; OrangeHudGauge.drawGauge = function(hudWindow, variableData) { var x = this.realX(variableData); var y = this.realY(variableData); var color1 = this.getRealColor(hudWindow, variableData.GaugeColor1); var color2 = this.getRealColor(hudWindow, variableData.GaugeColor2); var value = this.getCurrentValue(variableData); var maxValue = this.getMaxValue(variableData); var rate; var width = variableData.Width; var height = variableData.Height; if (maxValue > 0) { rate = parseFloat((value / maxValue).toPrecision(12)); } else { rate = 0; } if (isNaN(rate)) { rate = 0; } if (!variableData.AllowOverflow) { rate = rate.clamp(0, 1); } if (width > 0 && height > 0) { var fillW; var fillH; var fillX = x; var gaugeY = y; var fillY = gaugeY; if (variableData.Direction === 'left' || variableData.Direction === 'right') { fillW = Math.floor(width * rate); fillH = height; if (variableData.Direction === 'left') { fillX = fillX + width - fillW; } } else { fillW = width; fillH = Math.floor(height * rate); if (variableData.Direction == 'up') { fillY = fillY + height - fillH; } } hudWindow.contents.fillRect(x, gaugeY, width, height, hudWindow.gaugeBackColor()); hudWindow.contents.gradientFillRect(fillX, fillY, fillW, fillH, color1, color2); } }; OrangeHudGauge.getValue = function(variableData) { if (variableData.AutoRefresh) { return this.getCurrentValue(variableData) + ' / ' + this.getMaxValue(variableData); } else { return 0; } }; OrangeHudGauge.getCurrentValue = function(variableData) { if (variableData.ScriptValue !== undefined) { if (typeof(variableData.ScriptValue) == "function") { return parseFloat(variableData.ScriptValue()); } else { return parseFloat(Function("return " + variableData.ScriptValue)()); } } else if (variableData.ValueVariableId > 0) { return $gameVariables.value(variableData.ValueVariableId); } else { return 0; } }; OrangeHudGauge.getMaxValue = function(variableData) { if (variableData.ScriptMaxValue !== undefined) { if (typeof(variableData.ScriptMaxValue) == "function") { return parseFloat(variableData.ScriptMaxValue()); } else { return parseFloat(Function("return " + variableData.ScriptMaxValue)()); } } else if (variableData.MaxValueVariableId > 0) { return $gameVariables.value(variableData.MaxValueVariableId); } else { return 0; } }; OrangeHudGauge.getKey = function(variableData) { return variableData.ValueVariableId; }; OrangeHud.registerLineType('OrangeHudGauge', OrangeHudGauge); Imported.OrangeHudGauge = 1.2; }
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Time System Events * By Hudell - www.hudell.com * OrangeTimeSystemEvents.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Allow you to configure common events to be called when the time system changes * * @author Hudell *============================================================================= * * @param onChangeSecond * @desc The number of the common event to call when the second change * @default 0 * * @param onChangeMinute * @desc The number of the common event to call when the minute change * @default 0 * * @param onChangeHour * @desc The number of the common event to call when the hour change * @default 0 * * @param onChangeDay * @desc The number of the common event to call when the day change * @default 0 * * @param onChangeMonth * @desc The number of the common event to call when the month change * @default 0 * * @param onChangeYear * @desc The number of the common event to call when the year change * @default 0 * * @param onChangeDayPeriod * @desc The number of the common event to call when the day period change * @default 0 * * @param onChangeTime * @desc The number of the common event to call when the time changes * @default 0 * * @param onNightPeriod * @desc The number of the common event to call when the night starts * @default 0 * * @param onEarlyMorningPeriod * @desc The number of the common event to call when the night ends * @default 0 * * @param onDayPeriod * @desc The number of the common event to call when the sun rises * @default 0 * * @param onEveningPeriod * @desc The number of the common event to call when the sun starts to set * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/time-system-events * *=============================================================================*/ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeTimeSystemEvents = OrangeTimeSystemEvents || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeTimeSystemEvents'); $.Param = $.Param || {}; $.Param.onChangeDay = Number($.Parameters['onChangeDay'] || 0); $.Param.onChangeMonth = Number($.Parameters['onChangeMonth'] || 0); $.Param.onChangeYear = Number($.Parameters['onChangeYear'] || 0); $.Param.onChangeHour = Number($.Parameters['onChangeHour'] || 0); $.Param.onChangeMinute = Number($.Parameters['onChangeMinute'] || 0); $.Param.onChangeSecond = Number($.Parameters['onChangeSecond'] || 0); $.Param.onChangeDayPeriod = Number($.Parameters['onChangeDayPeriod'] || 0); $.Param.onChangeTime = Number($.Parameters['onChangeTime'] || 0); $.Param.onNightPeriod = Number($.Parameters['onNightPeriod'] || 0); $.Param.onEarlyMorningPeriod = Number($.Parameters['onEarlyMorningPeriod'] || 0); $.Param.onDayPeriod = Number($.Parameters['onDayPeriod'] || 0); $.Param.onEveningPeriod = Number($.Parameters['onEveningPeriod'] || 0); $.onChangeDay = function() { if ($.Param.onChangeDay !== undefined && $.Param.onChangeDay > 0) { this.executeCallback($.Param.onChangeDay); } }; $.onChangeMonth = function() { if ($.Param.onChangeMonth !== undefined && $.Param.onChangeMonth > 0) { this.executeCallback($.Param.onChangeMonth); } }; $.onChangeYear = function() { if ($.Param.onChangeYear !== undefined && $.Param.onChangeYear > 0) { this.executeCallback($.Param.onChangeYear); } }; $.onChangeHour = function() { if ($.Param.onChangeHour !== undefined && $.Param.onChangeHour > 0) { this.executeCallback($.Param.onChangeHour); } }; $.onChangeMinute = function() { if ($.Param.onChangeMinute !== undefined && $.Param.onChangeMinute > 0) { this.executeCallback($.Param.onChangeMinute); } }; $.onChangeSecond = function() { if ($.Param.onChangeSecond !== undefined && $.Param.onChangeSecond > 0) { this.executeCallback($.Param.onChangeSecond); } }; $.onChangeDayPeriod = function() { if ($.Param.onChangeDayPeriod !== undefined && $.Param.onChangeDayPeriod > 0) { this.executeCallback($.Param.onChangeDayPeriod); } if (OrangeTimeSystem.dayPeriod == DayPeriods.NIGHT) { if ($.Param.onNightPeriod !== undefined && $.Param.onNightPeriod > 0) { this.executeCallback($.Param.onNightPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.EARLY_MORNING) { if ($.Param.onEarlyMorningPeriod !== undefined && $.Param.onEarlyMorningPeriod > 0) { this.executeCallback($.Param.onEarlyMorningPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.DAY) { if ($.Param.onDayPeriod !== undefined && $.Param.onDayPeriod > 0) { this.executeCallback($.Param.onDayPeriod); } } if (OrangeTimeSystem.dayPeriod === DayPeriods.EVENING) { if ($.Param.onEveningPeriod !== undefined && $.Param.onEveningPeriod > 0) { this.executeCallback($.Param.onEveningPeriod); } } }; $.onChangeTime = function() { if ($.Param.onChangeTime !== undefined && $.Param.onChangeTime > 0) { this.executeCallback($.Param.onChangeTime); } }; OrangeTimeSystem.on('changeDay', $.onChangeDay); OrangeTimeSystem.on('changeMonth', $.onChangeMonth); OrangeTimeSystem.on('changeYear', $.onChangeYear); OrangeTimeSystem.on('changeHour', $.onChangeHour); OrangeTimeSystem.on('changeMinute', $.onChangeMinute); OrangeTimeSystem.on('changeSecond', $.onChangeSecond); OrangeTimeSystem.on('changeDayPeriod', $.onChangeDayPeriod); OrangeTimeSystem.on('changeTime', $.onChangeTime); })(OrangeTimeSystemEvents); Imported["OrangeTimeSystemEvents"] = 1.3;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Time System * By Hudell - www.hudell.com * OrangeTimeSystem.js * Version: 2.8.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc <OrangeTimeSystem> 2.8.1 - Adds a time system to your game * @author Hudell * * @param useRealTimeStructure * @desc If true, the time "Length" (except secondLength) variables will be ignored and the plugin will use the real time structure * @default false * * @param useRealTime * @desc If true, the time will be synced with the player's computer * @default false * * @param secondLength * @desc How many real time milliseconds should an ingame second last * @default 100 * * @param secondLengthDuringTest * @desc Use a different testLength during playtest * @default 0 * * @param secondLengthVariable * @desc Load the length of the second from a variable instead of a fixed value * @default 0 * * @param minuteLength * @desc How many ingame seconds should an ingame minute last * @default 60 * * @param hourLength * @desc How many ingame minutes should an ingame hour last * @default 60 * * @param dayLength * @desc How many ingame hours should an ingame day last * @default 24 * * @param weekLength * @desc How many ingame days should an ingame week last * @default 7 * * @param monthLength * @desc How many ingame days should an ingame month last * @default 31 * * @param yearLength * @desc How many ingame months should an ingame year last * @default 12 * * @param dayPeriod1Hour * @desc At what hour does night turn into early morning * @default 6 * * @param dayPeriod2Hour * @desc At what hour does early morning turn into day * @default 9 * * @param dayPeriod3Hour * @desc At what hour does day turn into evening * @default 18 * * @param dayPeriod4Hour * @desc At what hour does evening turn into night * @default 20 * * @param mainSwitchId * @desc The Number of the Switch used to activate the flow of time * @default 0 * * @param pauseClockDuringConversations * @desc If true, it will stop the flow of time while messages are being displayed on screen. * @default true * * @param initialSecond * @desc At what second will the game start? * @default 0 * * @param initialMinute * @desc At what minute will the game start? * @default 0 * * @param initialHour * @desc At what hour will the game start? * @default 6 * * @param initialDay * @desc At what day will the game start? * @default 1 * * @param initialMonth * @desc At what month will the game start? * @default 1 * * @param initialYear * @desc At what year will the game start? * @default 1 * * @param weekDayOffset * @desc Change the value here to a number betwen 0 and 6 to change the week day of the first day of the firstyear * @default 0 * * @param dayNames * @desc A list of all the day names, separated by comma. If empty, the day number will be used * @default Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday * * @param dayShortNames * @desc A list of all the day short names, separated by comma. If empty, the day number will be used * @default Mon, Tue, Wed, Thur, Fri, Sat, Sun * * @param monthNames * @desc A list of all the month names, separated by comma. If empty, the month number will be used * @default January, February, March, April, May, June, July, August, September, October, November, December * * @param monthShortNames * @desc A list of all the month short names, separated by comma. If empty, the month number will be used * @default Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec * * @param insideSwitch * @desc A switch to indicate if a map is inside a building or closed space * @default 0 * * @param tilesetList * @desc You can set a list of comma separated tilesets that will always be treated as "inside", regardless of the switch value. * @default * * @help * ============================================================================ * Introduction and Instructions * ============================================================================ * * This plugin creates a time system for your game. Nothing will change on the * game itself, unless you use another plugin that uses this one. * ============================================================================ * Plugin Commands and Script Calls * ============================================================================ * The plugin commands for this plugin are written in plain english, using * the following formats: * * ---------------------------------------------------------------------------- * COMMAND: REFRESH TIME SYSTEM * COMMAND: RESTART TIME SYSTEM * SCRIPT: OrangeTimeSystem.refreshTimeSystem(); * ---------------------------------------------------------------------------- * Both commands do the same: They disable the time system and enable it again. * This is required when you use the secondLengthVariable param. * Call this every time you change the value of that variable for it to work. * * * ---------------------------------------------------------------------------- * COMMAND: RUN COMMON EVENT 10 IN 6 SECONDS * SCRIPT: OrangeTimeSystem.runInSecondss(10, 6); * * COMMAND: RUN COMMON EVENT 10 IN 5 MINUTES * SCRIPT: OrangeTimeSystem.runInMinutes(10, 5); * * COMMAND: RUN COMMON EVENT 10 IN 4 HOURS * SCRIPT: OrangeTimeSystem.runInHours(10, 4); * * COMMAND: RUN COMMON EVENT 10 IN 1 DAY * SCRIPT: OrangeTimeSystem.runInDays(10, 1); * * COMMAND: RUN COMMON EVENT 10 IN 2 MONTHS * SCRIPT: OrangeTimeSystem.runInDays(10, 2); * * COMMAND: RUN COMMON EVENT 10 IN 1 YEAR * SCRIPT: OrangeTimeSystem.runInYears(10, 1); * ---------------------------------------------------------------------------- * Commands in this format will make the specified common event (10 in this example) * be triggered when the specified amount of time is passed. * This info is saved on the save file. * If you are using real time and call "run common event 2 in 1 day" * if the player only loads that game three days later, the common event will * called anyway (as soon as the player loads the game). * The common event will only be triggered once. * * * ---------------------------------------------------------------------------- * COMMAND: RUN COMMON EVENT 10 EVERY HOUR * SCRIPT: OrangeTimeSystem.on('changeHour', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY MINUTE * SCRIPT: OrangeTimeSystem.on('changeMinute', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY SECOND * SCRIPT: OrangeTimeSystem.on('changeSecond', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY DAY * SCRIPT: OrangeTimeSystem.on('changeDay', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY MONTH * SCRIPT: OrangeTimeSystem.on('changeMonth', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY YEAR * SCRIPT: OrangeTimeSystem.on('changeYear', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY PERIOD * SCRIPT: OrangeTimeSystem.on('changeDayPeriod', 10); * * COMMAND: RUN COMMON EVENT 10 EVERY TIME * SCRIPT: OrangeTimeSystem.on('changeTime', 10); * ---------------------------------------------------------------------------- * Commands in this format will trigger the specified common event every time * the specified variable changes. * * * ---------------------------------------------------------------------------- * COMMAND: RUN COMMON EVENT 10 ON HOUR 10 MINUTE 20 * COMMAND: RUN COMMON EVENT 10 ON DAY 1 HOUR 20 MINUTE 15 * COMMAND: RUN COMMON EVENT 10 ON YEAR 2 DAY 1 HOUR 15 * COMMAND: RUN COMMON EVENT 10 ON PERIOD 2 * * SCRIPT: OrangeTimeSystem.onDateTime(commonEvent, day, month, year, hour, minute, second) * SCRIPT: OrangeTimeSystem.onTime(commonEvent, hour, minute, second) * SCRIPT: OrangeTimeSystem.onDayPeriod(commonEvent, dayPeriod) * ---------------------------------------------------------------------------- * Those script calls will trigger the specified commonEvent at the exact datetime * specified. * * For example, to trigger common event 10 at 11:50:21, call: * * SCRIPT: OrangeTimeSystem.onTime(10, 11, 50, 21) * COMMAND: RUN COMMON EVENT 10 ON HOUR 11 MINUTE 50 SECOND 21 * * If you don't want to specify any of the variables, use the word undefined. * For example, to trigger common event 10 at every hour when the minutes turn 50, call: * * SCRIPT: OrangeTimeSystem.onTime(10, undefined, 50, 0) * COMMAND: RUN COMMON EVENT 10 ON MINUTE 50 SECOND 0 * * This will trigger the event at 00:50:00, 01:50:00, 02:50:00 and so on. * * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/time-system * */ var Imported = Imported || {}; if (Imported.MVCommons === undefined) { var MVC = MVC || {}; (function($){ $.isArray = function(obj) { return Object.prototype.toString.apply(obj) === '[object Array]'; }; $.shallowClone = function(obj) { var result; if ($.isArray(obj)) { return obj.slice(0); } else if (obj && !obj.prototype && (typeof obj == 'object' || obj instanceof Object)) { result = {}; for (var p in obj) { result[p] = obj[p]; } return result; } return obj; }; $.defaultGetter = function(name) { return function () { return this['_' + name]; }; }; $.defaultSetter = function(name) { return function (value) { var prop = '_' + name; if ((!this[prop]) || this[prop] !== value) { this[prop] = value; if (this._refresh) { this._refresh(); } } }; }; $.accessor = function(value, name /* , setter, getter */) { Object.defineProperty(value, name, { get: arguments.length > 3 ? arguments[3] : $.defaultGetter(name), set: arguments.length > 2 ? arguments[2] : $.defaultSetter(name), configurable: true });}; $.reader = function(obj, name /*, getter */) { Object.defineProperty(obj, name, { get: arguments.length > 2 ? arguments[2] : defaultGetter(name), configurable: true }); }; })(MVC); Number.prototype.fix = function() { return parseFloat(this.toPrecision(12)); }; Number.prototype.floor = function() { return Math.floor(this.fix()); }; } if (Imported.OrangeEventManager === undefined) { var OrangeEventManager = {}; (function($) {"use strict"; $._events = [];var oldGameTemp_initialize = Game_Temp.prototype.initialize;Game_Temp.prototype.initialize = function() {oldGameTemp_initialize.call(this);this._orangeCommonEvents = [];};Game_Temp.prototype.reserveOrangeCommonEvent = function(commonEventId) {if (commonEventId > 0) {this._orangeCommonEvents = this._orangeCommonEvents || [];this._orangeCommonEvents.push(commonEventId);}};var oldGameInterpreter_setupReservedCommonEvent = Game_Interpreter.prototype.setupReservedCommonEvent;Game_Interpreter.prototype.setupReservedCommonEvent = function() {if (!$gameTemp) return false;var result = oldGameInterpreter_setupReservedCommonEvent.call(this);if (result) return result;if (!$gameTemp._orangeCommonEvents) return result;if ($gameTemp._orangeCommonEvents.length > 0) {var commonEventId = $gameTemp._orangeCommonEvents.shift();var commonEvent = $dataCommonEvents[commonEventId];this.setup(commonEvent.list);return true;}return result;};$.on = function(eventName, callback) {if (this._events[eventName] === undefined) this._events[eventName] = [];this._events[eventName].push(callback);};$.un = function(eventName, callback) {if (this._events[eventName] === undefined) return;for (var i = 0; i < this._events[eventName].length; i++) {if (this._events[eventName][i] == callback) {this._events[eventName][i] = undefined;return;}}};$.executeCallback = function(callback) {if (typeof(callback) == "function") {return callback.call(this);}if (typeof(callback) == "number") {$gameTemp.reserveOrangeCommonEvent(callback);return true;}if (typeof(callback) == "string") {var id = parseInt(callback, 10);if (parseInt(callback, 10) == callback.trim()) {$gameTemp.reserveOrangeCommonEvent(parseInt(callback, 10));return true;} else if (callback.substr(0, 2) == 'SS') {var selfSwitchData = callback.split(',');var usedData = [0, 0, 'A', 'TRUE'];for (var i = 0; i < selfSwitchData.length; i++) {if (usedData.length > i) {usedData[i] = selfSwitchData[i];}}var mapId = parseInt(usedData[0].substr(2), 10);var eventId = parseInt(usedData[1], 10);var switchName = usedData[2].toUpperCase();var switchValue = usedData[3].toUpperCase();var key = [mapId, eventId, switchName];if (!!$gameSelfSwitches) {if (switchValue == 'TOGGLE') {switchValue = !$gameSelfSwitches.value(key);} else if (switchValue === 'FALSE' || switchValue === 'OFF') {switchValue = false;} else {switchValue = true;}$gameSelfSwitches.setValue(key, switchValue);return true;} else {return false;}} else if (callback.substr(0, 1) == 'S') {var data = callback.split(',');var value = 'TRUE';if (data.length >= 2) {value = data[1].toUpperCase();}id = parseInt(data[0].substr(1));if (!!$gameSwitches) {if (value == 'TOGGLE') {value = !$gameSwitches.value(id);} else if (value === 'FALSE' || value === 'OFF') {value = false;} else {value = true;}$gameSwitches.setValue(id, value);return true;} else {return false;}}return eval(callback);}console.error("Unknown callback type: ", callback);return undefined;};$.runEvent = function(eventName) {if (this._events[eventName] === undefined) return;for (var i = 0; i < this._events[eventName].length; i++) {var callback = this._events[eventName][i];if (this.executeCallback(callback) === false) {break;}}};})(OrangeEventManager); Imported.OrangeEventManager = 1.2; if (Utils.isOptionValid('test')) { console.log('OrangeTimeSystem will be using it\'s internal copy of OrangeEventManager 1.2.'); } } var OrangeTimeSystem = OrangeTimeSystem || MVC.shallowClone(OrangeEventManager); var DayPeriods = { EARLY_MORNING: 1, DAY: 2, EVENING: 3, NIGHT: 4 }; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeTimeSystem'); $.Param = $.Param || {}; $.Param.useRealTime = $.Parameters.useRealTime == "true"; $.Param.useRealTimeStructure = $.Parameters.useRealTimeStructure == "true"; if ($.Param.useRealTime) { $.Param.secondLength = 1000; } else { $.Param.secondLength = Number($.Parameters.secondLength || 100); if (Utils.isOptionValid('test')) { var testingLength = Number($.Parameters.secondLengthDuringTest || 0); if (testingLength > 0) { $.Param.secondLength = testingLength; } } } if ($.Param.useRealTime || $.Param.useRealTimeStructure) { $.Param.yearLength = 12; $.Param.minuteLength = 60; $.Param.hourLength = 60; $.Param.dayLength = 24; $.Param.weekLength = 7; $.Param.monthLength = 31; } else { $.Param.yearLength = Number($.Parameters.yearLength || 12); $.Param.minuteLength = Number($.Parameters.minuteLength || 60); $.Param.hourLength = Number($.Parameters.hourLength || 60); $.Param.dayLength = Number($.Parameters.dayLength || 24); $.Param.weekLength = Number($.Parameters.weekLength || 7); $.Param.monthLength = Number($.Parameters.monthLength || 31); } $.Param.secondLengthVariable = Number($.Parameters.secondLengthVariable || 0); $.Param.initialSecond = Number($.Parameters.initialSecond || 0); $.Param.initialMinute = Number($.Parameters.initialMinute || 0); $.Param.initialHour = Number($.Parameters.initialHour || 6); $.Param.initialDay = Number($.Parameters.initialDay || 1); $.Param.initialMonth = Number($.Parameters.initialMonth || 1); $.Param.initialYear = Number($.Parameters.initialYear || 1); $.Param.dayPeriod1Hour = Number($.Parameters.dayPeriod1Hour || 6); $.Param.dayPeriod2Hour = Number($.Parameters.dayPeriod2Hour || 9); $.Param.dayPeriod3Hour = Number($.Parameters.dayPeriod3Hour || 18); $.Param.dayPeriod4Hour = Number($.Parameters.dayPeriod4Hour || 20); $.Param.insideSwitch = Number($.Parameters.insideSwitch || 0); $.Param.tilesetList = ($.Parameters.tilesetList || '').split(','); for (var i = 0; i < $.Param.tilesetList.length; i++) { $.Param.tilesetList[i] = parseInt($.Param.tilesetList[i], 10); } $.Param.weekDayOffset = Number($.Parameters.weekDayOffset || 1); $.Param.pauseClockDuringConversations = $.Parameters.pauseClockDuringConversations !== "false"; var switchId = parseInt($.Parameters.mainSwitchId, 10); var monthNames = ($.Parameters.monthNames || "").trim(); var monthShortNames = ($.Parameters.monthShortNames || "").trim(); var dayNames = ($.Parameters.dayNames || "").trim(); var dayShortNames = ($.Parameters.dayShortNames || "").trim(); if (monthNames.length > 0) { $.Param.monthNames = monthNames.split(','); } else { $.Param.monthNames = []; } if (monthShortNames.length > 0) { $.Param.monthShortNames = monthShortNames.split(','); } else { $.Param.monthShortNames = []; } if (dayNames.length > 0) { $.Param.dayNames = dayNames.split(','); } else { $.Param.dayNames = []; } if (dayShortNames.length > 0) { $.Param.dayShortNames = dayShortNames.split(','); } else { $.Param.dayShortNames = []; } while ($.Param.monthNames.length < $.Param.yearLength) { $.Param.monthNames.push(($.Param.monthNames.length + 1).toString()); } while ($.Param.monthShortNames.length < $.Param.yearLength) { $.Param.monthShortNames.push(($.Param.monthShortNames.length + 1).toString()); } while ($.Param.dayNames.length < $.Param.weekLength) { $.Param.dayNames.push(($.Param.dayNames.length + 1).toString()); } while ($.Param.dayShortNames.length < $.Param.weekLength) { $.Param.dayShortNames.push(($.Param.dayShortNames.length + 1).toString()); } if (!isNaN(switchId) && switchId > 0) { $.Param.mainSwitchId = switchId; } else { $.Param.mainSwitchId = undefined; } MVC.accessor($, 'seconds'); MVC.accessor($, 'minute'); MVC.accessor($, 'hour'); MVC.accessor($, 'day'); MVC.accessor($, 'month'); MVC.accessor($, 'year'); MVC.accessor($, 'dayPeriod'); MVC.accessor($, 'weekDay'); MVC.reader($, 'monthName', function(){ return $.Param.monthNames[(this.month - 1) % $.Param.monthNames.length]; }); MVC.reader($, 'monthShortName', function(){ return $.Param.monthShortNames[(this.month - 1) % $.Param.monthShortNames.length]; }); MVC.reader($, 'dayName', function(){ return $.Param.dayNames[(this.weekDay - 1 + $.Param.dayNames.length) % $.Param.dayNames.length]; }); MVC.reader($, 'dayShortName', function(){ return $.Param.dayShortNames[(this.weekDay - 1 + $.Param.dayShortNames.length) % $.Param.dayShortNames.length]; }); MVC.reader($, 'inside', function(){ if (SceneManager._scene instanceof Scene_Map) { if ($.Param.tilesetList.length > 0) { if ($dataMap !== null) { if ($.Param.tilesetList.indexOf($dataMap.tilesetId) >= 0) { return true; } } } if ($.Param.insideSwitch > 0) { if ($gameSwitches.value($.Param.insideSwitch)) { return true; } } } return false; }); $.seconds = $.Param.initialSecond; $.minute = $.Param.initialMinute; $.hour = $.Param.initialHour; $.day = $.Param.initialDay; $.month = $.Param.initialMonth; $.year = $.Param.initialYear; MVC.accessor($, 'paused', function(value) { if ($.Param.mainSwitchId !== undefined) { $gameSwitches.setValue($.Param.mainSwitchId, !value); return; } this._paused = value; }, function() { if ($.Param.mainSwitchId !== undefined) { if ($gameSwitches === undefined || $gameSwitches === null) return true; return !$gameSwitches.value($.Param.mainSwitchId); } if (this._paused !== undefined) { return this._paused; } return false; }); $._timeEvents = {}; $._afterTimeEvents = {}; $._timeEventsNextId = 0; $._afterTimeEventsNextId = 0; $.seconds = 0; $.minute = 0; $.hour = 0; $.day = 1; $.month = 1; $.year = 1; $.dayPeriod = 0; $.weekDay = 0; $.runTimeChangeEvents = function(oldData) { var changedTime = false; if (oldData.seconds != this.seconds) { changedTime = true; this._onChangeSecond(); } if (oldData.minute !== this.minute) { changedTime = true; this._onChangeMinute(); } if (oldData.hour !== this.hour) { changedTime = true; this._onChangeHour(); } if (oldData.day !== this.day) { changedTime = true; this._onChangeDay(); } if (oldData.month !== this.month) { changedTime = true; this._onChangeMonth(); } if (oldData.year !== this.year) { changedTime = true; this._onChangeYear(); } if (oldData.dayPeriod !== this.dayPeriod) { changedTime = true; this._onChangeDayPeriod(); } if (changedTime) { this._onChangeTime(); } }; $.convertConfigToTimestamp = function(config) { var years = config.year; var months = config.month; var days = config.day; var hours = config.hour; var minutes = config.minute; var seconds = config.seconds; if ($.Param.useRealTime || $.Param.useRealTimeStructure) { var dateObj = new Date(); dateObj.setFullYear(years); dateObj.setMonth(months - 1); dateObj.setDate(days); dateObj.setHours(hours); dateObj.setMinutes(minutes); dateObj.setSeconds(seconds); return dateObj.getTime(); } else { years -= 1; if (years > 0) { months += years * $.Param.yearLength; } months -= 1; if (months > 0) { days += months * $.Param.monthLength; } days -= 1; if (days > 0) { hours += days * $.Param.dayLength; } if (hours > 0) { minutes += hours * $.Param.hourLength; } if (minutes > 0) { seconds += minutes * $.Param.minuteLength; } return seconds; } }; $.convertTimestampToConfig = function(timestamp) { if ($.Param.useRealTime || $.Param.useRealTimeStructure) { var dateObj = new Date(timestamp); return { seconds : dateObj.getSeconds(), minute : dateObj.getMinutes(), hour : dateObj.getHours(), day : dateObj.getDate(), month : dateObj.getMonth() + 1, year : dateObj.getFullYear() }; } else { var seconds = timestamp; var minutes = 0; var hours = 0; var days = 0; var months = 0; var years = 0; minutes = (seconds / $.Param.minuteLength).floor(); seconds -= (minutes * $.Param.minuteLength); hours = (minutes / $.Param.hourLength).floor(); minutes -= (hours * $.Param.hourLength); days = (hours / $.Param.dayLength).floor(); hours -= (days * $.Param.dayLength); months = (days / $.Param.monthLength).floor(); days -= (months * $.Param.monthLength); years = (months / $.Param.yearLength).floor(); months -= (years * $.Param.yearLength); return { seconds : seconds, minute : minutes, hour : hours, day : days + 1, month : months + 1, year : years + 1 }; } }; // Returns the difference in number of seconds $.compareTimestamps = function(timestamp1, timestamp2) { if (typeof timestamp1 == "object") { timestamp1 = $.convertConfigToTimestamp(timestamp1); } if (typeof timestamp2 == "object") { timestamp2 = $.convertConfigToTimestamp(timestamp2); } var diff = timestamp2 - timestamp1; if ($.Param.useRealTime || $.Param.useRealTimeStructure) { return (diff / 1000).floor(); } else { return diff; } }; $.validateDateTimeValues = function(date) { if ($.Param.useRealTime || $.Param.useRealTimeStructure) return; while (date.seconds >= $.Param.minuteLength) { date.minute += 1; date.seconds -= $.Param.minuteLength; } while (date.minute >= $.Param.hourLength) { date.hour += 1; date.minute -= $.Param.hourLength; } while (date.hour >= $.Param.dayLength) { date.day += 1; date.hour -= $.Param.dayLength; } while (date.day > $.Param.monthLength) { date.month += 1; date.day -= $.Param.monthLength; } while (date.month > $.Param.yearLength) { date.year += 1; date.month -= $.Param.yearLength; } }; $.updateTime = function(runEvents) { if (runEvents === undefined) runEvents = true; var oldData = $.getDateTime(); if ($.Param.useRealTimeStructure) { $.applyRealTimeLogic(); } var date = { seconds : this.seconds, minute : this.minute, hour : this.hour, day : this.day, month : this.month, year : this.year }; this.validateDateTimeValues(date); this.seconds = date.seconds; this.minute = date.minute; this.hour = date.hour; this.day = date.day; this.month = date.month; this.year = date.year; this.updateDayPeriod(); if (runEvents) { this.runTimeChangeEvents(oldData); } // Calculate week day if (!$.Param.useRealTime && !$.Param.useRealTimeStructure) { var previousYears = this.year - 1; var previousMonths = previousYears * $.Param.yearLength; var numMonths = previousMonths + this.month - 1; var numDays = numMonths * $.Param.monthLength + this.day; this.weekDay = numDays % $.Param.weekLength + $.Param.weekDayOffset; } this._onUpdateTime(); }; $.updateDayPeriodForDate = function(date) { // Calculate day period if (date.hour < $.Param.dayPeriod1Hour) { date.dayPeriod = 4; } else if (date.hour < $.Param.dayPeriod2Hour) { date.dayPeriod = 1; } else if (date.hour < $.Param.dayPeriod3Hour) { date.dayPeriod = 2; } else if (date.hour < $.Param.dayPeriod4Hour) { date.dayPeriod = 3; } else { date.dayPeriod = 4; } }; $.updateDayPeriod = function() { this.updateDayPeriodForDate(this); }; $.isEarlyMorning = function() { return this.dayPeriod == DayPeriods.EARLY_MORNING; }; $.isMidday = function() { return this.dayPeriod == DayPeriods.DAY; }; $.isEvening = function() { return this.dayPeriod == DayPeriods.EVENING; }; $.isNight = function() { return this.dayPeriod == DayPeriods.NIGHT; }; $.isEnabled = function() { return (this._intervalHandler !== undefined); }; $.enableTime = function() { if (this._intervalHandler !== undefined) return; var length = $.Param.secondLength; if ($.Param.useRealTime) { length = 1000; } else if ($.Param.secondLengthVariable > 0) { if ($gameVariables !== null) { if ($gameVariables.value($.Param.secondLengthVariable) > 0) { length = $gameVariables.value($.Param.secondLengthVariable); } } } var increment = 1; if (length < 10) { var multiplier = Math.ceil(10 / length); increment *= multiplier; length *= multiplier; } this._intervalHandler = setInterval(function() { $.progressTime(increment); }, length); }; $.refreshTimeSystem = function() { $.disableTime(); $.enableTime(); }; $.disableTime = function() { if (this._intervalHandler === undefined) return; clearInterval(this._intervalHandler); this._intervalHandler = undefined; }; $.applyRealTimeLogic = function(){ var date = new Date(); date.setFullYear(this.year); date.setMonth(this.month - 1); date.setDate(this.day); date.setHours(this.hour); date.setMinutes(this.minute); date.setSeconds(this.seconds); this.seconds = date.getSeconds(); this.minute = date.getMinutes(); this.hour = date.getHours(); this.day = date.getDate(); this.month = date.getMonth() + 1; this.year = date.getFullYear(); this.weekDay = date.getDay(); }; $.loadRealTime = function() { var date = new Date(); var oldData = this.getDateTime(); var anyChanged = false; $.seconds = date.getSeconds(); $.minute = date.getMinutes(); $.hour = date.getHours(); $.day = date.getDate(); $.month = date.getMonth() + 1; $.year = date.getFullYear(); $.weekDay = date.getDay(); $.updateDayPeriod(); if ($.seconds != oldData.seconds) { anyChanged = true; $._onChangeSecond(); } if ($.minute != oldData.minute) { anyChanged = true; $._onChangeMinute(); } if ($.hour != oldData.hour) { anyChanged = true; $._onChangeHour(); } if ($.day != oldData.day) { anyChanged = true; $._onChangeDay(); } if ($.month != oldData.month) { anyChanged = true; $._onChangeMonth(); } if ($.year != oldData.year) { anyChanged = true; $._onChangeYear(); } if (anyChanged) { $._onChangeTime(); } }; $.setTime = function(seconds, minute, hour, day, month, year) { var oldData = this.getDateTime(); if (seconds !== undefined) { this.seconds = seconds; } if (minute !== undefined) { this.minute = minute; } if (hour !== undefined) { this.hour = hour; } if (day !== undefined) { this.day = day; } if (month !== undefined) { this.month = month; } if (year !== undefined) { this.year = year; } $.updateTime(false); $.runTimeChangeEvents(oldData); }; $.addSeconds = function(seconds) { $.addTime({seconds : seconds}); }; $.addMinutes = function(minutes) { $.addTime({minutes : minutes}); }; $.addHours = function(hours) { $.addTime({hours : hours}); }; $.addDays = function(days) { $.addTime({days : days}); }; $.addMonths = function(months) { $.addTime({months : months}); }; $.addYears = function(years) { $.addTime({years : years}); }; $.addTime = function(timeData) { $.passTime(timeData.seconds, timeData.minutes, timeData.hours, timeData.days, timeData.months, timeData.years); }; $.passTime = function(seconds, minutes, hours, days, months, years) { var oldData = this.getDateTime(); this.seconds += Number(seconds || 0); this.minute += Number(minutes || 0); this.hour += Number(hours || 0); this.day += Number(days || 0); this.month += Number(months || 0); this.year += Number(years || 0); $.updateTime(false); $.runTimeChangeEvents(oldData); }; $.isInternallyPaused = function() { if ($.Param.pauseClockDuringConversations === true) { if (SceneManager._scene instanceof Scene_Map) { if ($gameMessage.isBusy()) { return true; } } } return false; }; $.progressTime = function(increment) { if (this.paused) return; if (this.isInternallyPaused()) return; if (increment === undefined) { increment = 1; } if ($.Param.useRealTime) { $.loadRealTime(); $._onUpdateTime(); } else if (SceneManager._scene instanceof Scene_Map) { $.seconds += increment; $.updateTime(); $._onChangeSecond(); $._onChangeTime(); } }; $._onChangeSecond = function() { this.runEvent('changeSecond'); }; $._onChangeTime = function() { this.runEvent('changeTime'); }; $._onChangeMinute = function() { this.runEvent('changeMinute'); }; $._onChangeHour = function() { this.runEvent('changeHour'); }; $._onChangeDayPeriod = function() { this.runEvent('changeDayPeriod'); }; $._onChangeDay = function() { this.runEvent('changeDay'); }; $._onChangeMonth = function() { this.runEvent('changeMonth'); }; $._onChangeYear = function() { this.runEvent('changeYear'); }; $.onTime = function(callback, hour, minute, second, autoRemove) { return this.onDateTime(callback, 0, 0, 0, hour, minute, second, autoRemove); }; $.onDate = function(callback, day, month, year, autoRemove) { return this.onDateTime(callback, day, month, year, 0, 0, 0, autoRemove); }; $.onDayPeriod = function(callback, dayPeriod, autoRemove) { if (autoRemove === undefined) { autoRemove = false; } var config = { callback : callback, dayPeriod : dayPeriod, autoRemove : autoRemove }; return $.registerTimeEvent(config); }; $.onDateTime = function(callback, day, month, year, hour, minute, second, autoRemove) { if (autoRemove === undefined) { autoRemove = false; } var config = { day: day, month: month, year: year, hour: hour, minute: minute, second: second, callback: callback, autoRemove : autoRemove, after : false }; return $.registerTimeEvent(config); }; $.onWeekDay = function(callback, weekDay) { return this.registerTimeEvent({ weekDay: weekDay, callback: callback }); }; $.atDate = $.onDate; $.atTime = $.onTime; $.atDateTime = $.onDateTime; $.atWeekDay = $.onWeekDay; $.registerAfterTimeEvent = function(config) { var id = this._afterTimeEventsNextId; this._afterTimeEvents[id] = config; this._afterTimeEventsNextId++; config.key = id; return id; }; $.runInDateTime = function(callback, years, months, days, hours, minutes, seconds, autoRemove) { var newDate = $.getDateTime(); newDate.year += Number(years || 0); newDate.month += Number(months || 0); newDate.day += Number(days || 0); newDate.hour += Number(hours || 0); newDate.minute += Number(minutes ||0); newDate.seconds += Number(seconds || 0); this.validateDateTimeValues(newDate); if (autoRemove === undefined) { autoRemove = true; } var config = { callback : callback, year : newDate.year, month : newDate.month, day : newDate.day, hour : newDate.hour, minute : newDate.minute, seconds : newDate.seconds, autoRemove : autoRemove, after : true }; return $.registerAfterTimeEvent(config); }; $.runInHours = function(callback, hours, minutes, seconds) { return $.runInDateTime(callback, 0, 0, 0, hours, minutes, seconds); }; $.runInDays = function(callback, days) { return $.runInDateTime(callback, 0, 0, days); }; $.runInMonths = function(callback, months) { return $.runInDateTime(callback, 0, months); }; $.runInYears = function(callback, years) { return $.runInDateTime(callback, years); }; $.runInMinutes = function(callback, minutes) { return $.runInHours(callback, 0, minutes); }; $.runInSeconds = function(callback, seconds) { return $.runInHours(callback, 0, 0, seconds); }; $.registerTimeEvent = function(config) { var id = this._timeEventsNextId; this._timeEventsNextId++; this._timeEvents[id] = config; config.key = id; return id; }; $.checkIfEventShouldRun = function(config) { if (config.day !== undefined && config.day > 0 && config.day != this.day) return false; if (config.month !== undefined && config.month > 0 && config.month != this.month) return false; if (config.year !== undefined && config.year > 0 && config.year != this.year) return false; if (config.hour !== undefined && config.hour != this.hour) return false; if (config.minute !== undefined && config.minute != this.minute) return false; if (config.seconds !== undefined && config.seconds != this.seconds) return false; if (config.weekDay !== undefined && config.weekDay != this.weekDay) return false; if (config.dayPeriod !== undefined && config.dayPeriod !== this.dayPeriod) return false; return true; }; $.checkEventsToRun = function(eventList, after) { var config; var keysToRemove = []; var currentTimestamp = this.convertConfigToTimestamp(this.getDateTime()); if ($.Param.useRealTime || $.Param.useRealTimeStructure) { currentTimestamp = (currentTimestamp / 1000).floor(); } for (var key in eventList) { config = eventList[key]; if (!config) continue; if (config.callback === undefined) continue; if (after) { if (config.seconds === undefined) { config.seconds = config.second; } var timestamp = this.convertConfigToTimestamp(config); if ($.Param.useRealTime || $.Param.useRealTimeStructure) { timestamp = (timestamp / 1000).floor(); } if (timestamp > currentTimestamp) { continue; } } else { if (!this.checkIfEventShouldRun(config)) { continue; } } this.executeCallback(config.callback); if (config.autoRemove === true) { config.callback = undefined; keysToRemove.push(config.key); } } for (var i = 0; i < keysToRemove.length; i++) { var keyToRemove = keysToRemove[i]; if (eventList.hasOwnProperty(keyToRemove)) { delete eventList[keyToRemove]; } } }; $._onUpdateTime = function() { $.checkEventsToRun(this._timeEvents, false); $.checkEventsToRun(this._afterTimeEvents, true); }; $.getDateTime = function() { return { hour: $.hour, minute: $.minute, seconds: $.seconds, day: $.day, month: $.month, year: $.year, dayPeriod: $.dayPeriod, weekDay: $.weekDay, paused: $.paused }; }; $.getTomorrow = function(){ var dateObj = $.getDateTime(); dateObj.day += 1; $.validateDateTimeValues(dateObj); return dateObj; }; $.setDateTime = function(dateTime) { this.hour = dateTime.hour || 0; this.minute = dateTime.minute || 0; this.seconds = dateTime.seconds || 0; this.day = dateTime.day || 1; this.month = dateTime.month || 1; this.year = dateTime.year || 1; this.dayPeriod = dateTime.dayPeriod || DayPeriods.EARLY_MORNING; this.weekDay = dateTime.weekDay || 0; if (dateTime.paused !== undefined) { this.paused = dateTime.paused; } else { this.paused = false; } }; $.getCallbacksFromList = function(eventList) { var callbackList = []; for (var key in eventList) { var config = eventList[key]; if (!config) continue; if (config.callback === undefined) continue; //can't save functions if (typeof(config.callback) == "function") continue; callbackList.push(MVC.shallowClone(config)); } return callbackList; }; $.getCallbacks = function() { var callbackList = {}; callbackList.after = this.getCallbacksFromList(this._afterTimeEvents); callbackList.normal = this.getCallbacksFromList(this._timeEvents); return callbackList; }; $.setCallbacksToList = function(callbackList, nextId) { var eventList = {}; for (var i = 0; i < callbackList.length; i++) { var config = MVC.shallowClone(callbackList[i]); eventList[nextId] = config; config.key = nextId; nextId++; } return { list : eventList, nextId : nextId }; }; $.setCallbacks = function(callbackList) { if (callbackList.after !== undefined) { var afterTimeEvents = this.setCallbacksToList(callbackList.after, this._afterTimeEventsNextId); this._afterTimeEvents = afterTimeEvents.list; this._afterTimeEventsNextId = afterTimeEvents.nextId; } if (callbackList.normal !== undefined) { var timeEvents = this.setCallbacksToList(callbackList.normal, this._timeEventsNextId); this._timeEvents = timeEvents.list; this._timeEventsNextId = timeEvents.nextId; } }; $.checkRunInCommands = function(eventId, args, nextIndex) { if (nextIndex === undefined) { nextIndex = 4; } if (args.length < (nextIndex + 2)) return; var value = $.getNumericValue(args[nextIndex]); switch (args[nextIndex +1].toUpperCase()) { case 'MINUTE' : case 'MINUTES' : $.runInMinutes(eventId, value); break; case 'SECOND' : case 'SECONDS' : $.runInSeconds(eventId, value); break; case 'HOUR' : case 'HOURS' : $.runInHours(eventId, value); break; case 'DAY' : case 'DAYS' : $.runInDays(eventId, value); break; case 'MONTH' : case 'MONTHS' : $.runInMonths(eventId, value); break; case 'YEAR' : case 'YEARS' : $.runInYears(eventId, value); break; default: return; } }; $.checkRunOnCommands = function(eventId, args, nextIndex) { if (nextIndex === undefined) { nextIndex = 4; } if (args.length < (nextIndex + 1)) return; var hour, minute, seconds, day, month, year, dayPeriod; var autoRemove = false; while (true) { if (args.length < nextIndex + 1) break; switch(args[nextIndex].toUpperCase()) { case 'HOUR' : hour = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'MINUTE' : minute = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'SECOND' : seconds = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'DAY' : day = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'MONTH' : month = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'YEAR' : year = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'PERIOD' : dayPeriod = $.getNumericValue(args[nextIndex + 1]); nextIndex++; break; case 'ONCE' : autoRemove = true; break; default : break; } nextIndex++; } var config = { callback : eventId, hour : hour, minute : minute, seconds : seconds, day : day, month : month, year : year, dayPeriod : dayPeriod }; $.registerTimeEvent(config); }; $.checkRunEveryCommands = function(eventId, args, nextIndex) { if (nextIndex === undefined) { nextIndex = 4; } if (args.length < (nextIndex + 1)) return; switch (args[nextIndex].toUpperCase()) { case 'HOUR' : $.on('changeHour', eventId); break; case 'MINUTE' : $.on('changeMinute', eventId); break; case 'SECOND' : $.on('changeSecond', eventId); break; case 'TIME' : $.on('changeTime', eventId); break; case 'DAY' : $.on('changeDay', eventId); break; case 'MONTH' : $.on('changeMonth', eventId); break; case 'YEAR' : $.on('changeYear', eventId); break; case 'PERIOD' : $.on('changeDayPeriod', eventId); break; default : break; } }; $.getNumericValue = function(stringValue) { if (stringValue.substr(0, 1) == '[' && stringValue.substr(-1) == ']') { var variableId = parseInt(stringValue.substr(1, stringValue.length - 2), 10); if (variableId > 0) { return $gameVariables.value(variableId); } } else { return parseInt(stringValue, 10); } }; $.checkRunCommands = function(command, args) { if (args.length < 4) return; if (command.toUpperCase() != 'RUN') return; if (args[0].toUpperCase() != 'COMMON') return; if (args[1].toUpperCase() != 'EVENT') return; var eventId = $.getNumericValue(args[2]); if (eventId <= 0) return; if (args[3].toUpperCase() == 'ON') { this.checkRunOnCommands(eventId, args); } else if (args[3].toUpperCase() == 'IN') { this.checkRunInCommands(eventId, args); } else if (args[3].toUpperCase() == 'EVERY') { this.checkRunEveryCommands(eventId, args); } }; $.checkSwitchCommands = function(command, args, mapId, eventId) { if (args.length < 2) return; var commandName = command.toUpperCase(); if (commandName != 'ENABLE' && commandName != 'DISABLE' && commandName != 'TOGGLE') return; var nextArg = 0; var switchId; var configString = ''; if (args[nextArg].toUpperCase() == 'SWITCH') { nextArg++; configString = 'S'; } else if (args[nextArg].toUpperCase() == 'SELF' && args[nextArg + 1].toUpperCase() == 'SWITCH') { nextArg += 2; if (!$gameMap || !$gameMap._interpreter) { return; } configString = 'SS' + mapId + ',' + eventId + ','; } if (args.length > nextArg + 1) { configString = configString + args[nextArg]; nextArg++; if (commandName == 'ENABLE') { configString += ',TRUE'; } else if (commandName == 'DISABLE') { configString += ',FALSE'; } else { configString += ',TOGGLE'; } if (args[nextArg].toUpperCase() == 'ON') { this.checkRunOnCommands(configString, args, nextArg + 1); } else if (args[nextArg].toUpperCase() == 'IN') { this.checkRunInCommands(configString, args, nextArg + 1); } else if (args[nextArg].toUpperCase() == 'EVERY') { this.checkRunEveryCommands(configString, args, nextArg + 1); } } }; $.checkSystemCommands = function(command, args) { if (command.toUpperCase() == 'RESTART' || command.toUpperCase() == 'REFRESH') { if (args.length > 0 && args[0].toUpperCase() == 'TIME') { $.refreshTimeSystem(); } } }; var oldDataManager_makeSaveContents = DataManager.makeSaveContents; DataManager.makeSaveContents = function() { var contents = oldDataManager_makeSaveContents.call(this); contents.orangeDateTime = $.getDateTime(); contents.orangeTimeSystemCallbacks = $.getCallbacks(); return contents; }; var oldDataManager_extractSaveContents = DataManager.extractSaveContents; DataManager.extractSaveContents = function(contents) { oldDataManager_extractSaveContents.call(this, contents); if (contents.orangeDateTime !== undefined) { $.setDateTime(contents.orangeDateTime); } if (contents.orangeTimeSystemCallbacks !== undefined) { $.setCallbacks(contents.orangeTimeSystemCallbacks); } }; var oldDataManager_setupNewGame = DataManager.setupNewGame; DataManager.setupNewGame = function() { oldDataManager_setupNewGame.call(this); $.setDateTime({ seconds : $.Param.initialSecond, minute : $.Param.initialMinute, hour : $.Param.initialHour, day : $.Param.initialDay, month : $.Param.initialMonth, year : $.Param.initialYear }); $.refreshTimeSystem(); }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); $.checkRunCommands(command, args); $.checkSwitchCommands(command, args, this._mapId, this._eventId); $.checkSystemCommands(command, args); }; $.enableTime(); })(OrangeTimeSystem); Imported.OrangeTimeSystem = 2.8;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Weather * By Hudell - www.hudell.com * OrangeWeather.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Adds weather effects to your game * * @author Hudell *============================================================================= * * @param weatherSpeed * @desc How many frames does it take for the weather effect to change completely * @default 60 * * @param changeWeatherStrengthAlongTheDay * @desc If true, the weather effect strength may change during the day * @default true * * @param rainChance * @desc A number between 0 and 100 identifying the chances of raining * @default 0 * * @param rainChanceByMonth * @desc You can set a different rain chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxRainStrength * @desc A number between 1 and 9 identifying the max strength of rain. * @default 9 * * @param minRainStrength * @desc A number between 1 and 9 identifying the min strength of rain. * @default 1 * * @param rainStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param snowChance * @desc A number between 0 and 100 identifying the chances of snowing * @default 0 * * @param snowChanceByMonth * @desc You can set a different snow chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxSnowStrength * @desc A number between 1 and 9 identifying the max strength of snow. * @default 9 * * @param minSnowStrength * @desc A number between 1 and 9 identifying the min strength of snow. * @default 1 * * @param snowStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param stormChance * @desc A number between 0 and 100 identifying the chances of storming * @default 0 * * @param stormChanceByMonth * @desc You can set a different storm chance for each month, in the format <monthNumber: chance>. Example: <1: 20> <12:15> * @default * * @param maxStormStrength * @desc A number between 1 and 9 identifying the max strength of storm. * @default 9 * * @param minStormStrength * @desc A number between 1 and 9 identifying the min strength of storm. * @default 1 * * @param stormStrengthByMonth * @desc You can set a different strength range for each month, in the format <monthNumber: minStrength,maxStrength>. Example: <1: 1,5> <12: 3,9> * @default * * @param playDefaultWeatherEffects * @desc set this to false if you want to use your own weather effects through common events * @default true * * @param rainCommonEvent * @desc the common event to run when it starts raining * @default 0 * * @param snowCommonEvent * @desc the common event to run when it starts snowing * @default 0 * * @param stormCommonEvent * @desc the common event to run when a storm starts * @default 0 * * @param normalWeatherCommonEvent * @desc the common event to run when the weather goes back to sunny * @default 0 * */ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeWeather = OrangeWeather || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.WeatherTypes = { NORMAL : 0, RAIN : 1, SNOW : 2, STORM : 3 }; $.Parameters = PluginManager.parameters('OrangeWeather'); $.Param = $.Param || {}; $.Param.weatherSpeed = Number($.Parameters.weatherSpeed || 60); $.Param.changeWeatherStrengthAlongTheDay = $.Parameters.changeWeatherStrengthAlongTheDay != "false"; $.Param.normalWeatherCommonEvent = Number($.Parameters.normalWeatherCommonEvent || 0); $.Param.playDefaultWeatherEffects = $.Parameters.playDefaultWeatherEffects != "false"; $.Param.rainChance = Number($.Parameters.rainChance || 0); $.Param.maxRainStrength = Number($.Parameters.maxRainStrength || 0); $.Param.minRainStrength = Number($.Parameters.minRainStrength || 0); $.Param.rainCommonEvent = Number($.Parameters.rainCommonEvent || 0); $.Param.snowChance = Number($.Parameters.snowChance || 0); $.Param.maxSnowStrength = Number($.Parameters.maxSnowStrength || 0); $.Param.minSnowStrength = Number($.Parameters.minSnowStrength || 0); $.Param.snowCommonEvent = Number($.Parameters.snowCommonEvent || 0); $.Param.stormChance = Number($.Parameters.stormChance || 0); $.Param.maxStormStrength = Number($.Parameters.maxStormStrength || 0); $.Param.minStormStrength = Number($.Parameters.minStormStrength || 0); $.Param.stormCommonEvent = Number($.Parameters.stormCommonEvent || 0); var rainChanceByMonth = ($.Parameters.rainChanceByMonth || "").trim(); var rainChanceByMonthObj = { note : rainChanceByMonth, meta : {}}; DataManager.extractMetadata(rainChanceByMonthObj); var rainStrengthByMonth = ($.Parameters.rainStrengthByMonth || "").trim(); var rainStrengthByMonthObj = { note : rainStrengthByMonth, meta : {} }; DataManager.extractMetadata(rainStrengthByMonthObj); var snowChanceByMonth = ($.Parameters.snowChanceByMonth || "").trim(); var snowChanceByMonthObj = { note : snowChanceByMonth, meta : {}}; DataManager.extractMetadata(snowChanceByMonthObj); var snowStrengthByMonth = ($.Parameters.snowStrengthByMonth || "").trim(); var snowStrengthByMonthObj = { note : snowStrengthByMonth, meta : {} }; DataManager.extractMetadata(snowStrengthByMonthObj); var stormChanceByMonth = ($.Parameters.stormChanceByMonth || "").trim(); var stormChanceByMonthObj = { note : stormChanceByMonth, meta : {}}; DataManager.extractMetadata(stormChanceByMonthObj); var stormStrengthByMonth = ($.Parameters.stormStrengthByMonth || "").trim(); var stormStrengthByMonthObj = { note : stormStrengthByMonth, meta : {} }; DataManager.extractMetadata(stormStrengthByMonthObj); var i; var monthIndex; $.Param.rainChanceByMonth = [undefined]; $.Param.rainStrengthByMonth = [undefined]; $.Param.snowChanceByMonth = [undefined]; $.Param.snowStrengthByMonth = [undefined]; $.Param.stormChanceByMonth = [undefined]; $.Param.stormStrengthByMonth = [undefined]; for (i=0; i < OrangeTimeSystem.Param.yearLength; i++) { $.Param.rainChanceByMonth.push($.Param.rainChance); $.Param.snowChanceByMonth.push($.Param.snowChance); $.Param.stormChanceByMonth.push($.Param.stormChance); $.Param.rainStrengthByMonth.push({ max :$.Param.maxRainStrength, min :$.Param.minRainStrength }); $.Param.snowStrengthByMonth.push({ max :$.Param.maxSnowStrength, min :$.Param.minSnowStrength }); $.Param.stormStrengthByMonth.push({ max :$.Param.maxStormStrength, min :$.Param.minStormStrength }); } for (monthIndex in rainChanceByMonthObj.meta) { $.Param.rainChanceByMonth[monthIndex] = parseInt(rainChanceByMonthObj.meta[monthIndex], 10); } for (monthIndex in snowChanceByMonthObj.meta) { $.Param.snowChanceByMonth[monthIndex] = parseInt(snowChanceByMonthObj.meta[monthIndex], 10); } for (monthIndex in stormChanceByMonthObj.meta) { $.Param.stormChanceByMonth[monthIndex] = parseInt(stormChanceByMonthObj.meta[monthIndex], 10); } var str, data, min, max; for (monthIndex in rainStrengthByMonthObj.meta) { str = rainStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minRainStrength; max = $.Param.maxRainStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.rainStrengthByMonth[monthIndex] = { min : min, max : max }; } for (monthIndex in snowStrengthByMonthObj.meta) { str = snowStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minSnowStrength; max = $.Param.maxSnowStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.snowStrengthByMonth[monthIndex] = { min : min, max : max }; } for (monthIndex in stormStrengthByMonthObj.meta) { str = stormStrengthByMonthObj.meta[monthIndex]; data = str.split(','); min = $.Param.minStormStrength; max = $.Param.maxStormStrength; if (data.length > 1) { min = parseInt(data[0], 10); max = parseInt(data[1], 10); } else if (data.length > 0) { max = parseInt(data[0], 10); } $.Param.stormStrengthByMonth[monthIndex] = { min : min, max : max }; } MVC.accessor($, 'weather'); MVC.accessor($, 'weatherPower'); MVC.accessor($, 'nextDayWeather'); MVC.reader($, 'rainChance', function(){ return $.Param.rainChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($, 'maxRainStrength', function(){ return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($, 'minRainStrength', function(){ return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($, 'snowChance', function(){ return $.Param.snowChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($, 'maxSnowStrength', function(){ return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($, 'minSnowStrength', function(){ return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($, 'stormChance', function(){ return $.Param.stormChanceByMonth[OrangeTimeSystem.month]; }); MVC.reader($, 'maxStormStrength', function(){ return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].max; }); MVC.reader($, 'minStormStrength', function(){ return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].min; }); MVC.reader($, 'maxWeatherStrength', function(){ switch (this.weather) { case $.WeatherTypes.RAIN : return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].max; case $.WeatherTypes.SNOW : return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].max; case $.WeatherTypes.STORM : return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].max; default : return 0; } }); MVC.reader($, 'minWeatherStrength', function(){ switch (this.weather) { case $.WeatherTypes.RAIN : return $.Param.rainStrengthByMonth[OrangeTimeSystem.month].min; case $.WeatherTypes.SNOW : return $.Param.snowStrengthByMonth[OrangeTimeSystem.month].min; case $.WeatherTypes.STORM : return $.Param.stormStrengthByMonth[OrangeTimeSystem.month].min; default : return 0; } }); MVC.reader($, 'tomorrowRainChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.rainChanceByMonth[dateObj.month]; }); MVC.reader($, 'tomorrowSnowChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.snowChanceByMonth[dateObj.month]; }); MVC.reader($, 'tomorrowStormChance', function(){ var dateObj = OrangeTimeSystem.getTomorrow(); return $.Param.stormChanceByMonth[dateObj.month]; }); $.weather = 0; $.weatherPower = 0; $.nextDayWeather = 0; $.canUpdateWeather = function() { return !OrangeTimeSystem.inside; }; $.onMinuteChange = function(){ // Randomly change the strength of the weather effect about once an hour if (Math.random() * 100 < Math.ceil(100 / OrangeTimeSystem.Param.hourLength)) { this.randomizePower(); } }; $.pickNextDayWeather = function(){ var rainChance = this.tomorrowRainChance; if (Math.random() * 100 < rainChance) { this.nextDayWeather = this.WeatherTypes.RAIN; return; } var snowChance = this.tomorrowSnowChance; if (Math.random() * 100 < snowChance) { this.nextDayWeather = this.WeatherTypes.SNOW; return; } var stormChance = this.tomorrowStormChance; if (Math.random() * 100 < stormChance) { this.nextDayWeather = this.WeatherTypes.STORM; return; } this.nextDayWeather = this.WeatherTypes.NORMAL; }; $.onDayChange = function(){ this.weather = this.nextDayWeather; this.pickNextDayWeather(); this.updateWeather($.Param.weatherSpeed); }; $.randomizePower = function(){ var maxWeatherStrength = this.maxWeatherStrength; var minWeatherStrength = this.minWeatherStrength; var diff = maxWeatherStrength - minWeatherStrength + 1; var strength = Math.floor(Math.random() * diff) + minWeatherStrength; this.weatherPower = strength; }; $.startRaining = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startRaining'); if ($.Param.rainCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.rainCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('rain', strength, speed); } }; $.startSnowing = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startSnowing'); if ($.Param.snowCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.snowCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('snow', strength, speed); } }; $.startStorm = function(strength, speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('startStorm'); if ($.Param.stormCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.stormCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('storm', strength, speed); } }; $.resetWeather = function(speed) { if ($gameScreen === undefined || $gameScreen === null) return; $.runEvent('normalWeather'); if ($.Param.normalWeatherCommonEvent > 0) { $gameTemp.reserveCommonEvent($.Param.normalWeatherCommonEvent); } if ($.Param.playDefaultWeatherEffects) { $gameScreen.changeWeather('none', 0, speed); } }; $.updateWeather = function(speed) { var type = 0; if (this.canUpdateWeather()) { type = this.weather; if (type > 0 && this.weatherPower === 0) { this.randomizePower(); } } switch(type) { case this.WeatherTypes.RAIN : this.startRaining(this.weatherPower, speed); break; case this.WeatherTypes.SNOW : this.startSnowing(this.weatherPower, speed); break; case this.WeatherTypes.STORM : this.startStorm(this.weatherPower, speed); break; default : this.resetWeather(speed); this.weatherPower = 0; break; } }; if ($.Param.changeWeatherStrengthAlongTheDay) { OrangeTimeSystem.on('changeMinute', function(){ $.onMinuteChange.call($); }); } OrangeTimeSystem.on('changeDay', function(){ $.onDayChange.call($); }); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); $.updateWeather(1); }; })(OrangeWeather); Imported["OrangeWeather"] = 1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Time System Variables * By Hudell - www.hudell.com * OrangeTimeSystemVariables.js * Version: 1.4 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Exports Orange Time System data to variables * * @author Hudell * * @param secondVariable * @desc The number of the variable where you want to store the seconds * @default 0 * * @param minuteVariable * @desc The number of the variable where you want to store the minutes * @default 0 * * @param hourVariable * @desc The number of the variable where you want to store the hours * @default 0 * * @param dayVariable * @desc The number of the variable where you want to store the days * @default 0 * * @param monthVariable * @desc The number of the variable where you want to store the months * @default 0 * * @param yearVariable * @desc The number of the variable where you want to store the years * @default 0 * * @param weekDayVariable * @desc The number of the variable where you want to store the week day * @default 0 * * @param dayPeriodVariable * @desc The number of the variable where you want to store the day period * @default 0 * * @param monthNameVariable * @desc The number of the variable where you want to store the name of the month * @default 0 * * @param monthShortNameVariable * @desc The number of the variable where you want to store the short name of the month * @default 0 * * @param dayNameVariable * @desc The number of the variable where you want to store the name of the day * @default 0 * * @param dayShortNameVariable * @desc The number of the variable where you want to store the short name of the day * @default 0 * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/time-system-variables * *=============================================================================*/ var Imported = Imported || {}; var OrangeTimeSystemVariables = OrangeTimeSystemVariables || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download MVCommons: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeTimeSystemVariables'); $.Param = $.Param || {}; $.Param.secondVariable = Number($.Parameters.secondVariable || 0); $.Param.minuteVariable = Number($.Parameters.minuteVariable || 0); $.Param.hourVariable = Number($.Parameters.hourVariable || 0); $.Param.dayVariable = Number($.Parameters.dayVariable || 0); $.Param.monthVariable = Number($.Parameters.monthVariable || 0); $.Param.yearVariable = Number($.Parameters.yearVariable || 0); $.Param.weekDayVariable = Number($.Parameters.weekDayVariable || 0); $.Param.dayPeriodVariable = Number($.Parameters.dayPeriodVariable || 0); $.Param.monthNameVariable = Number($.Parameters.monthNameVariable || 0); $.Param.monthShortNameVariable = Number($.Parameters.monthShortNameVariable || 0); $.Param.dayNameVariable = Number($.Parameters.dayNameVariable || 0); $.Param.dayShortNameVariable = Number($.Parameters.dayShortNameVariable || 0); $.configureVariables = function() { if ($gameVariables === undefined || $gameVariables === null) return; if ($.Param.secondVariable !== undefined && $.Param.secondVariable > 0) { $gameVariables.setValue($.Param.secondVariable, OrangeTimeSystem.seconds); } if ($.Param.minuteVariable !== undefined && $.Param.minuteVariable > 0) { $gameVariables.setValue($.Param.minuteVariable, OrangeTimeSystem.minute); } if ($.Param.hourVariable !== undefined && $.Param.hourVariable > 0) { $gameVariables.setValue($.Param.hourVariable, OrangeTimeSystem.hour); } if ($.Param.dayVariable !== undefined && $.Param.dayVariable > 0) { $gameVariables.setValue($.Param.dayVariable, OrangeTimeSystem.day); } if ($.Param.monthVariable !== undefined && $.Param.monthVariable > 0) { $gameVariables.setValue($.Param.monthVariable, OrangeTimeSystem.month); } if ($.Param.yearVariable !== undefined && $.Param.yearVariable > 0) { $gameVariables.setValue($.Param.yearVariable, OrangeTimeSystem.year); } if ($.Param.weekDayVariable !== undefined && $.Param.weekDayVariable > 0) { $gameVariables.setValue($.Param.weekDayVariable, OrangeTimeSystem.weekDay); } if ($.Param.dayPeriodVariable !== undefined && $.Param.dayPeriodVariable > 0) { $gameVariables.setValue($.Param.dayPeriodVariable, OrangeTimeSystem.dayPeriod); } if ($.Param.monthNameVariable !== undefined && $.Param.monthNameVariable > 0) { $gameVariables.setValue($.Param.monthNameVariable, OrangeTimeSystem.monthName); } if ($.Param.monthShortNameVariable !== undefined && $.Param.monthShortNameVariable > 0) { $gameVariables.setValue($.Param.monthShortNameVariable, OrangeTimeSystem.monthShortName); } if ($.Param.dayNameVariable !== undefined && $.Param.dayNameVariable > 0) { $gameVariables.setValue($.Param.dayNameVariable, OrangeTimeSystem.dayName); } if ($.Param.dayShortNameVariable !== undefined && $.Param.dayShortNameVariable > 0) { $gameVariables.setValue($.Param.dayShortNameVariable, OrangeTimeSystem.dayShortName); } }; var oldGameVariablesSetValue = Game_Variables.prototype.setValue; Game_Variables.prototype.setValue = function(variableId, value) { oldGameVariablesSetValue.apply(this, arguments); var changed = false; if (variableId == $.Param.secondVariable) { OrangeTimeSystem.seconds = value; changed = true; } if (variableId == $.Param.minuteVariable) { OrangeTimeSystem.minute = value; changed = true; } if (variableId == $.Param.hourVariable) { OrangeTimeSystem.hour = value; changed = true; } if (variableId == $.Param.dayVariable) { OrangeTimeSystem.day = value; changed = true; } if (variableId == $.Param.monthVariable) { OrangeTimeSystem.month = value; changed = true; } if (variableId == $.Param.yearVariable) { OrangeTimeSystem.year = value; changed = true; } if (changed) { OrangeTimeSystem.updateTime(); } }; // Updates the variables every in-game second OrangeTimeSystem.on('changeTime', $.configureVariables); })(OrangeTimeSystemVariables); Imported.OrangeTimeSystemVariables = 1.4;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Day and Night * By Hudell - www.hudell.com * OrangeDayAndNight.js * Version: 1.3 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Tints the screen to show the time passing * * @author Hudell * * @param morningTint * @desc Red, Green, Blue and Gray values to use in the morning, comma separated * @default -34, -17, 10, 68 * * @param middayTint * @desc Red, Green, Blue and Gray values to use during the day, comma separated * @default 0, 0, 0, 0 * * @param eveningTint * @desc Red, Green, Blue and Gray values to use in the evening, comma separated * @default 17, -34, -68, 17 * * @param nightTint * @desc Red, Green, Blue and Gray values to use at night, comma separated * @default -102, -85, 0, 170 * * @param tintSpeed * @desc how many frames should the tint effect take to complete? * @default 300 * * @help * Use the following plugin command to update the screen tint immediatelly: * * update screen tint * * You can specify the duration of the tint effect this way: * * update screen tint in 20 frames * * */ var Imported = Imported || {}; if (Imported["OrangeTimeSystem"] === undefined) { console.log('Download OrangeTimeSystem: http://link.hudell.com/time-system'); throw new Error("This library requires the OrangeTimeSystem!"); } var OrangeDayAndNight = OrangeDayAndNight || MVC.shallowClone(OrangeEventManager); (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeDayAndNight'); $.Param = $.Param || {}; $.Param.morningTint = $.Parameters['morningTint'] || "-34, -17, 10, 68"; $.Param.middayTint = $.Parameters['middayTint'] || "0, 0, 0, 0"; $.Param.eveningTint = $.Parameters['eveningTint'] || "17, -34, -68, 17"; $.Param.nightTint = $.Parameters['nightTint'] || "-102, -85, 0, 170"; $.Param.tintSpeed = Number($.Parameters['tintSpeed'] || 0); $.canTintScreen = function() { return !OrangeTimeSystem.inside; }; $.onDayPeriodChange = function(){ $.updateTint($.Param.tintSpeed); }; $.updateTint = function(speed) { var dataStr = ""; var data = [0, 0, 0, 0]; if ($.canTintScreen()) { switch(OrangeTimeSystem.dayPeriod) { case 1 : dataStr = $.Param.morningTint; break; case 2 : dataStr = $.Param.middayTint; break; case 3 : dataStr = $.Param.eveningTint; break; case 4 : dataStr = $.Param.nightTint; break; default : return; } data = dataStr.split(','); } if (data.length > 0) { data[0] = parseInt(data[0], 10); } else { data.push(0); } if (data.length > 1) { data[1] = parseInt(data[1], 10); } else { data.push(0); } if (data.length > 2) { data[2] = parseInt(data[2], 10); } else { data.push(0); } if (data.length > 3) { data[3] = parseInt(data[3], 10); } else { data.push(0); } $gameScreen.startTint(data, speed); }; OrangeTimeSystem.on('changeDayPeriod', $.onDayPeriodChange); var oldGamePlayer_performTransfer = Game_Player.prototype.performTransfer; Game_Player.prototype.performTransfer = function() { oldGamePlayer_performTransfer.call(this); $.updateTint(1); }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); if (command.toUpperCase() == 'UPDATE') { if (args.length >= 2 && args[0].toUpperCase() == 'SCREEN' && args[1].toUpperCase() == 'TINT') { var speed = 0; if (args.length >= 4 && args[2].toUpperCase() == 'IN') { speed = parseInt(args[3], 10); } $.updateTint(speed); } } }; })(OrangeDayAndNight); Imported["OrangeDayAndNight"] = 1.3;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Lighting * By Hudell - www.hudell.com * OrangeLighting.js * Version: 1.4 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Lighting system <OrangeLighting> * @author Hudell * * @param lightMaskSwitch * @desc When this switch is on, the lighting system will be activated * @default 0 * * @param opacityVariable * @desc The variable that defines the opacity of the black mask. If none is defined, the opacity will be 255. * @default 0 * * @param tintSpeed * @desc The speed in which the color will change. (4 = black to white in 1 second, 255 = instant) * @default 0.3 * * @param defaultMaskColor * @desc The default mask color * @default black * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ var Imported = Imported || {}; var Hudell = Hudell || {}; Hudell.OrangeLighting = Hudell.OrangeLighting || {}; (function(namespace) { "use strict"; namespace.addOns = {}; namespace._listeners = {}; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLighting>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLighting parameters."); } namespace.Parameters = parameters[0].parameters; namespace.Param = {}; namespace.Param.lightMaskSwitch = Number(namespace.Parameters.lightMaskSwitch || 0); namespace.Param.opacityVariable = Number(namespace.Parameters.opacityVariable || 0); namespace.Param.tintSpeed = Number(namespace.Parameters.tintSpeed || 0.3); namespace.Param.defaultMaskColor = namespace.Parameters.defaultMaskColor || "black"; namespace.enabled = true; Object.defineProperties(namespace, { dirty: { get: function() { return this._dirty; }, set: function(value) { this._dirty = value; }, configurable: true } }); namespace.isActive = function() { return this.enabled; }; function OrangeLightmask() { this.initialize.apply(this, arguments); } namespace.shouldShowLightMask = function(){ return namespace.Param.lightMaskSwitch === 0 || $gameSwitches.value(namespace.Param.lightMaskSwitch); }; namespace.on = function(eventName, callback) { if (this._listeners[eventName] === undefined) this._listeners[eventName] = []; this._listeners[eventName].push(callback); }; namespace.un = function(eventName, callback) { if (this._listeners[eventName] === undefined) return; for (var i = 0; i < this._listeners[eventName].length; i++) { if (this._listeners[eventName][i] == callback) { this._listeners[eventName][i] = undefined; return; } } }; namespace.runEvent = function(eventName, scope) { if (this._listeners[eventName] === undefined) return; if (scope === undefined) scope = this; for (var i = 0; i < this._listeners[eventName].length; i++) { var callback = this._listeners[eventName][i]; callback.call(scope); } }; namespace.Lightmask = OrangeLightmask; namespace.Lightmask.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); namespace.Lightmask.prototype.constructor = namespace.Lightmask; //Copied from http://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes namespace.colorNameToHex = function(color) { if (color.charAt('0') == '#') return color; var colors = {"aliceblue":"#f0f8ff","antiquewhite":"#faebd7","aqua":"#00ffff","aquamarine":"#7fffd4","azure":"#f0ffff", "beige":"#f5f5dc","bisque":"#ffe4c4","black":"#000000","blanchedalmond":"#ffebcd","blue":"#0000ff","blueviolet":"#8a2be2","brown":"#a52a2a","burlywood":"#deb887", "cadetblue":"#5f9ea0","chartreuse":"#7fff00","chocolate":"#d2691e","coral":"#ff7f50","cornflowerblue":"#6495ed","cornsilk":"#fff8dc","crimson":"#dc143c","cyan":"#00ffff", "darkblue":"#00008b","darkcyan":"#008b8b","darkgoldenrod":"#b8860b","darkgray":"#a9a9a9","darkgreen":"#006400","darkkhaki":"#bdb76b","darkmagenta":"#8b008b","darkolivegreen":"#556b2f", "darkorange":"#ff8c00","darkorchid":"#9932cc","darkred":"#8b0000","darksalmon":"#e9967a","darkseagreen":"#8fbc8f","darkslateblue":"#483d8b","darkslategray":"#2f4f4f","darkturquoise":"#00ced1", "darkviolet":"#9400d3","deeppink":"#ff1493","deepskyblue":"#00bfff","dimgray":"#696969","dodgerblue":"#1e90ff", "firebrick":"#b22222","floralwhite":"#fffaf0","forestgreen":"#228b22","fuchsia":"#ff00ff", "gainsboro":"#dcdcdc","ghostwhite":"#f8f8ff","gold":"#ffd700","goldenrod":"#daa520","gray":"#808080","green":"#008000","greenyellow":"#adff2f", "honeydew":"#f0fff0","hotpink":"#ff69b4", "indianred ":"#cd5c5c","indigo":"#4b0082","ivory":"#fffff0","khaki":"#f0e68c", "lavender":"#e6e6fa","lavenderblush":"#fff0f5","lawngreen":"#7cfc00","lemonchiffon":"#fffacd","lightblue":"#add8e6","lightcoral":"#f08080","lightcyan":"#e0ffff","lightgoldenrodyellow":"#fafad2", "lightgrey":"#d3d3d3","lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a","lightseagreen":"#20b2aa","lightskyblue":"#87cefa","lightslategray":"#778899","lightsteelblue":"#b0c4de", "lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32","linen":"#faf0e6", "magenta":"#ff00ff","maroon":"#800000","mediumaquamarine":"#66cdaa","mediumblue":"#0000cd","mediumorchid":"#ba55d3","mediumpurple":"#9370d8","mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee", "mediumspringgreen":"#00fa9a","mediumturquoise":"#48d1cc","mediumvioletred":"#c71585","midnightblue":"#191970","mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5", "navajowhite":"#ffdead","navy":"#000080", "oldlace":"#fdf5e6","olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500","orangered":"#ff4500","orchid":"#da70d6", "palegoldenrod":"#eee8aa","palegreen":"#98fb98","paleturquoise":"#afeeee","palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9","peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd","powderblue":"#b0e0e6","purple":"#800080", "red":"#ff0000","rosybrown":"#bc8f8f","royalblue":"#4169e1", "saddlebrown":"#8b4513","salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57","seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0","skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090","snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4", "tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347","turquoise":"#40e0d0", "violet":"#ee82ee", "wheat":"#f5deb3","white":"#ffffff","whitesmoke":"#f5f5f5", "yellow":"#ffff00","yellowgreen":"#9acd32"}; if (typeof colors[color.toLowerCase()] != 'undefined') return colors[color.toLowerCase()]; return false; }; namespace.hexToRgb = function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { red : parseInt(result[1], 16), green : parseInt(result[2], 16), blue : parseInt(result[3], 16) } : null; }; namespace.getCharacterPosition = function(character) { var pw = $gameMap.tileWidth(); var ph = $gameMap.tileHeight(); var dx = $gameMap.displayX(); var dy = $gameMap.displayY(); var px = character._realX; var py = character._realY; var pd = character._direction; var x1 = (pw / 2) + ((px - dx) * pw); var y1 = (ph / 2) + ((py - dy) * ph); return [x1, y1, pd]; }; (function($) { Object.defineProperties($, { width: { get: function() { return this._width; }, configurable: true }, height: { get: function() { return this._height; }, configurable: true }, sprites: { get: function() { return this._sprites; }, configurable: true }, currentMapId: { get: function() { return this._currentMapId; }, set: function(value) { this._currentMapId = value; }, configurable: true }, currentDisplayX: { get: function() { return this._currentDisplayX; }, set: function(value) { this._currentDisplayX = value; }, configurable: true }, currentDisplayY: { get: function() { return this._currentDisplayY; }, set: function(value) { this._currentDisplayY = value; }, configurable: true } }); $.initialize = function() { PIXI.DisplayObjectContainer.call(this); this._width = Graphics.width; this._height = Graphics.height; this._sprites = []; this.createMaskBitmap(); }; $.update = function() { this.updateMask(); }; $.createMaskBitmap = function() { this._maskBitmap = new Bitmap(Graphics.width, Graphics.height); }; $.maskColor = function() { return namespace.Param.defaultMaskColor; }; $.walkColor = function(newRGB, currentRGB, colorName, tintSpeed) { if (newRGB[colorName] < currentRGB[colorName]) { currentRGB[colorName] = currentRGB[colorName] - tintSpeed; if (newRGB[colorName] > currentRGB[colorName]) { currentRGB[colorName] = newRGB[colorName]; } } else if(newRGB[colorName] > currentRGB[colorName]) { currentRGB[colorName] = currentRGB[colorName] + tintSpeed; if (newRGB[colorName] < currentRGB[colorName]) { currentRGB[colorName] = newRGB[colorName]; } } newRGB[colorName] = newRGB[colorName].clamp(0, 255); }; $.refreshMaskColor = function() { var destinationColor = $.maskColor(); var newColor = destinationColor; if (namespace._lastMaskColor !== undefined && destinationColor !== namespace._lastMaskColor) { var currentColor = namespace._lastMaskColor; var currentRGB = namespace._currentRGB; if (!!currentRGB || currentColor.charAt(0) == '#') { newColor = namespace.colorNameToHex(destinationColor); if (newColor === false) { newColor = destinationColor; } if (currentRGB === undefined) { currentRGB = namespace.hexToRgb(currentColor); } var newRGB = namespace.hexToRgb(newColor); this.walkColor(newRGB, currentRGB, 'red', namespace.Param.tintSpeed); this.walkColor(newRGB, currentRGB, 'green', namespace.Param.tintSpeed); this.walkColor(newRGB, currentRGB, 'blue', namespace.Param.tintSpeed); newColor = '#' + ((1 << 24) + (Math.floor(currentRGB.red) << 16) + (Math.floor(currentRGB.green) << 8) + Math.floor(currentRGB.blue)).toString(16).slice(1); namespace._currentRGB = currentRGB; } } else { namespace._currentRGB = undefined; } namespace._lastMaskColor = newColor; }; $.refreshMask = function() { namespace.runEvent('beforeRefreshMask', this); this.popAllSprites(); if (namespace.isActive()) { namespace._showing = namespace.shouldShowLightMask(); if (namespace._showing) { namespace.runEvent('refreshMask', this); var backOpacity = 255; if (namespace.Param.opacityVariable > 0) { backOpacity = $gameVariables.value(namespace.Param.opacityVariable).clamp(0, 255); } //calculates what will be the new mask color this.refreshMaskColor(); namespace.runEvent('refreshMaskColor', this); namespace._lastOpacity = backOpacity; // Adds the mask sprite this.addSprite(0, 0, this._maskBitmap, backOpacity); this._maskBitmap.fillRect(0, 0, Graphics.width, Graphics.height, namespace._lastMaskColor); namespace.runEvent('afterRefreshMask', this); } } }; $.updateMask = function() { if (!namespace.isActive()){ if (this._sprites.length > 0) { namespace.dirty = true; } return; } var newId = 0; var newDisplayX = 0; var newDisplayY = 0; if ($gameMap !== undefined && $gameMap !== null) { newId = $gameMap._mapId; newDisplayX = $gameMap._displayX; newDisplayY = $gameMap._displayY; } if (newId !== this.currentMapId || newDisplayY !== this.currentDisplayY || newDisplayX || this.currentDisplayX) { namespace.dirty = true; } if (namespace.shouldShowLightMask() !== namespace._showing) { namespace.dirty = true; } if (namespace._lastMaskColor !== $.maskColor()) { namespace.dirty = true; } // if (namespace.Param.opacityVariable > 0) { // var backOpacity = $gameVariables.value(namespace.Param.opacityVariable).clamp(0, 255); // if (backOpacity !== namespace._lastOpacity) { // namespace.dirty = true; // } // } namespace.runEvent('updateMask', this); if (namespace.dirty) { this.refreshMask(); namespace.dirty = false; this.currentMapId = newId; this.currentDisplayX = newDisplayX; this.currentDisplayY = newDisplayY; } }; $.addSprite = function(x, y, bitmap, opacity, blendMode, rotation, anchorX, anchorY) { if (opacity === undefined) opacity = 255; if (blendMode === undefined) blendMode = 2; if (rotation === undefined) rotation = 0; if (anchorX === undefined) anchorX = 0; if (anchorY === undefined) anchorY = 0; var sprite = new Sprite(this.viewport); sprite.bitmap = bitmap; sprite.opacity = opacity; sprite.blendMode = blendMode; sprite.x = x; sprite.y = y; this._sprites.push(sprite); this.addChild(sprite); sprite.rotation = rotation; sprite.ax = anchorX; sprite.ay = anchorY; sprite.opacity = opacity; return sprite; }; $.popSprite = function() { var sprite = this._sprites.pop(); if (sprite) { this.removeChild(sprite); } return sprite; }; $.popAllSprites = function() { var sprite; while (this._sprites.length > 0) { sprite = this._sprites.pop(); if (sprite) { this.removeChild(sprite); } } }; })(namespace.Lightmask.prototype); (function($) { $.createLightmask = function() { this._lightmask = new namespace.Lightmask(); this.addChild(this._lightmask); }; // Creates the Lightmask before the weather layer namespace.Spriteset_Map_prototype_createWeather = $.createWeather; $.createWeather = function() { this.createLightmask(); namespace.Spriteset_Map_prototype_createWeather.call(this); }; })(Spriteset_Map.prototype); (function($){ $.radialgradientFillRect = function (x, y, startRadius, endRadius, color1, color2, flicker) { var context = this._context; var grad; var wait = Math.floor((Math.random() * 8) + 1); if (flicker === true && wait == 1) { var gradRnd = Math.floor((Math.random() * 7) + 1); var colorRnd = Math.floor((Math.random() * 10) - 5); var red = namespace.hexToRgb(color1).red; var green = namespace.hexToRgb(color1).green; var blue = namespace.hexToRgb(color1).blue; green = (green + colorRnd).clamp(0, 255); color1 = '#' + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1); endRadius -= gradRnd; } grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, color1); grad.addColorStop(1, color2); context.save(); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); context.restore(); this._setDirty(); }; $.makeFlashlightEffect = function(x, y, startRadius, endRadius, color1, color2, direction) { var context = this._context; var grad; context.save(); grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, '#999999'); grad.addColorStop(1, color2); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); for (var cone = 0; cone < 8; cone++) { startRadius = cone * 2; endRadius = cone * 12; switch(direction) { case 6 : x += cone * 6; break; case 4 : x -= cone * 6; break; case 2 : y += cone * 6; break; case 8 : y -= cone * 6; break; default : break; } grad = context.createRadialGradient(x, y, startRadius, x, y, endRadius); grad.addColorStop(0, color1); grad.addColorStop(1, color2); context.fillStyle = grad; context.fillRect(x - endRadius, y - endRadius, endRadius * 2, endRadius * 2); } context.restore(); this._setDirty(); }; })(Bitmap.prototype); namespace.clear = function() { this._currentRGB = undefined; this._lastMaskColor = undefined; this._lastOpacity = undefined; }; namespace.oldGameMap_setup = Game_Map.prototype.setup; Game_Map.prototype.setup = function(mapId) { namespace.oldGameMap_setup.call(this, mapId); namespace.clear(); }; })(Hudell.OrangeLighting); OrangeLighting = Hudell.OrangeLighting; Imported.OrangeLighting = 1.4;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange Lighting - Player Light * By Hudell - www.hudell.com * OrangeLightingPlayerLight.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Player Lights <OrangeLightingPlayerLight> * @author Hudell * * @param playerRadius * @desc The size of the light globe around the player * @default 40 * * @param playerColor * @desc The color of the light around the player * @default #FFFFFF * * @param playerFlicker * @desc Should the plugin flick the light around the player? * @default false * * @param flashlightSwitch * @desc When this switch is on, a flashlight will be added to the player. * @default 0 * * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ if (!Hudell || !Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.PlayerLight = {}; (function(playerLight){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLightingPlayerLight>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLightingPlayerLight parameters."); } playerLight.Parameters = parameters[0].parameters; playerLight.Param = {}; playerLight.Param.playerRadius = Number(playerLight.Parameters.playerRadius || 40); playerLight.Param.playerColor = playerLight.Parameters.playerColor || '#FFFFFF'; playerLight.Param.playerFlicker = (playerLight.Parameters.playerFlicker || "false").toUpperCase() === "TRUE"; playerLight.Param.flashlightSwitch = Number(playerLight.Parameters.flashlightSwitch || 0); playerLight.enabled = true; playerLight.shouldShowFlashlight = function(){ return playerLight.Param.flashlightSwitch > 0 && $gameSwitches.value(playerLight.Param.flashlightSwitch); }; playerLight.getPlayerPosition = function() { return lightSystem.getCharacterPosition($gamePlayer); }; //Refreshes the player's light playerLight.refresh = function() { if (!playerLight.enabled) return; lightSystem._showingFlashlight = playerLight.shouldShowFlashlight(); var canvas = this._maskBitmap.canvas; var ctx = canvas.getContext("2d"); ctx.globalCompositeOperation = 'lighter'; var positions = playerLight.getPlayerPosition(); if (playerLight.shouldShowFlashlight()) { this._maskBitmap.makeFlashlightEffect(positions[0], positions[1], 0, playerLight.Param.playerRadius, playerLight.Param.playerColor, 'black', positions[2]); } else { if (playerLight.Param.playerRadius < 100) { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 0, playerLight.Param.playerRadius, '#999999', 'black', playerLight.Param.playerFlicker); } else { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 20, playerLight.Param.playerRadius, playerLight.Param.playerColor, 'black', playerLight.Param.playerFlicker); } } ctx.globalCompositeOperation = 'source-over'; }; playerLight.update = function(){ if (!playerLight.enabled) return; if (playerLight.shouldShowFlashlight() !== lightSystem._showingFlashlight) { lightSystem.dirty = true; } if (playerLight.Param.playerFlicker && !playerLight.shouldShowFlashlight()) { lightSystem.dirty = true; } }; lightSystem.on('afterRefreshMask', playerLight.refresh); lightSystem.on('updateMask', playerLight.update); (function($) { playerLight.Game_Player_prototype_update = $.update; $.update = function(sceneActive) { var oldD = this._direction; var oldX = this._x; var oldY = this._y; playerLight.Game_Player_prototype_update.call(this, sceneActive); if (this.isMoving() || oldD !== this._direction || oldX !== this._x || oldY !== this._y) { lightSystem.dirty = true; } }; })(Game_Player.prototype); })(lightSystem.addOns.PlayerLight); })(Hudell.OrangeLighting); Imported["OrangeLighting.PlayerLight"] = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange Lighting - Event Light * By Hudell - www.hudell.com * OrangeLightingEventLight.js * Version: 1.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Event Lights <OrangeLightingEventLight> * @author Hudell * * @param eventRadius * @desc The size of the light globe around the event by default * @default 40 * * @param eventColor * @desc The color of the light around the event by default * @default #FFFFFF * * @param eventFlicker * @desc Should the plugin flick the light around the event by default? * @default false * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * * ============================================================================ * Notetags * ============================================================================ * * <light> * This notetag will enable a light globe around the event * * <light_radius:40> * This notetag will let you configure the radius of the light globe * * <light_color:#FFFFFF> * This notetag will let you configure the color of the light globe * * <light_flickle:true> * This notetag will let you configure if the light globle should flickle * * <flashlight> * This notetag will activate a flashlight on the event * * ============================================================================ * Script Calls * ============================================================================ * * this.enableLight(); * This script call will enable a light globe around the event * * this.disableLight(); * This script call will disable all light effects on the event * * this.enableFlashlight(); * This script call will activate a flashlight on the event * * this.disableFlashlight(); * This script call will deactivate the flashlight on the event, but keep other effects active. * * this.enableEventLight(eventId); * This script call will enable a light globe around the event * * this.disableEventLight(eventId); * This script call will disable all light effects on the event * * this.enableEventFlashlight(eventId); * This script call will activate a flashlight on the event * * this.disableEventFlashlight(eventId); * This script call will deactivate the flashlight on the event, but keep other effects active. * *=============================================================================*/ if (!Hudell || !Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.EventLight = {}; (function(eventLight){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeLightingEventLight>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeLightingEventLight parameters."); } eventLight.Parameters = parameters[0].parameters; eventLight.Param = {}; eventLight.Param.eventRadius = Number(eventLight.Parameters.eventRadius || 40); eventLight.Param.eventColor = eventLight.Parameters.eventColor || '#FFFFFF'; eventLight.Param.eventFlicker = (eventLight.Parameters.eventFlicker || "false").toUpperCase() === "TRUE"; eventLight.getEventPosition = function(event) { return lightSystem.getCharacterPosition(event); }; //Refreshes the event's light eventLight.refresh = function() { var events = $gameMap._events.filter(function(event){ return !!event && !!event.orangeLight; }); if (events.length === 0) return; var canvas = this._maskBitmap.canvas; var ctx = canvas.getContext("2d"); ctx.globalCompositeOperation = 'lighter'; for (var i = 0; i < events.length; i++) { var eventData = events[i]; var positions = lightSystem.getCharacterPosition(eventData); var radius = eventData.orangeLight.radius || eventLight.Param.eventRadius; var color = eventData.orangeLight.color || eventLight.Param.eventColor; var flicker = eventData.orangeLight.flicker || eventLight.Param.eventFlicker; var flashlight = eventData.orangeLight.flashlight || false; if (flashlight) { this._maskBitmap.makeFlashlightEffect(positions[0], positions[1], 0, radius, color, 'black', positions[2]); } else { if (radius < 100) { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 0, radius, '#999999', 'black', flicker); } else { this._maskBitmap.radialgradientFillRect(positions[0], positions[1], 20, radius, color, 'black', flicker); } } } ctx.globalCompositeOperation = 'source-over'; }; eventLight.update = function(){ }; lightSystem.on('afterRefreshMask', eventLight.refresh); lightSystem.on('updateMask', eventLight.update); (function($){ $.enableEventLight = function(eventId, flashlight, radius, color, flicker) { if (eventId > 0) { var eventData = $gameMap.event(eventId); if (eventData) { eventData.enableLight(flashlight, radius, color, flicker); } } }; $.disableEventLight = function(eventId) { if (eventId > 0) { var eventData = $gameMap.event(eventId); if (eventData) { eventData.disableLight(); } } }; $.enableEventFlashlight = function(eventId) { this.enableEventLight(eventId, true); }; $.disableEventFlashlight = function(eventId) { this.enableEventLight(eventId, false); }; $.enableLight = function(flashlight, radius, color, flicker) { this.enableEventLight(this._eventId, flashlight, radius, color, flicker); }; $.disableLight = function() { this.disableEventLight(this._eventId); }; $.enableFlashlight = function() { this.enableEventLight(this._eventId, true); }; $.disableFlashlight = function() { this.enableEventLight(this._eventId, false); }; })(Game_Interpreter.prototype); (function($) { $.enableLight = function(flashlight, radius, color, flicker) { this.orangeLight = { flashlight : flashlight, radius : radius, color : color, flicker : flicker }; lightSystem.dirty = true; }; $.disableLight = function() { this.orangeLight = undefined; lightSystem.dirty = true; }; $.enableFlashlight = function() { this.enableLight(true); }; $.disableFlashlight = function() { this.enableLight(false); }; eventLight.Game_Event_prototype_update = $.update; $.update = function(sceneActive) { var oldD = this._direction; var oldX = this._x; var oldY = this._y; eventLight.Game_Event_prototype_update.call(this, sceneActive); if (!this.orangeLight) return; if (this.isMoving() || oldD !== this._direction || oldX !== this._x || oldY !== this._y) { lightSystem.dirty = true; } }; $.checkNoteTags = function(){ if (!this.event().meta) return; var orangeLight = { flashlight : false, flicker : eventLight.Param.eventFlicker, radius : eventLight.Param.eventRadius, color : eventLight.Param.eventColor }; var add = false; if (this.event().meta.light_radius !== undefined) { add = true; orangeLight.radius = this.event().meta.light_radius; } if (this.event().meta.light_color !== undefined) { add = true; orangeLight.color = this.event().meta.light_color; } if (this.event().meta.light_flickle !== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flickle; } if (this.event().meta.light_flickler !== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flickler; } if (this.event().meta.light_flicker !== undefined) { add = true; orangeLight.flicker = this.event().meta.light_flicker; } if (this.event().meta.light) { add = true; } if (this.event().meta.flashlight) { add = true; orangeLight.flashlight = true; } if (add) { this.orangeLight = orangeLight; } else { this.orangeLight = undefined; } }; eventLight.Game_Event_prototype_initialize = $.initialize; $.initialize = function(mapId, eventId) { eventLight.Game_Event_prototype_initialize.call(this, mapId, eventId); this.checkNoteTags(); }; })(Game_Event.prototype); })(lightSystem.addOns.EventLight); })(Hudell.OrangeLighting); Imported["OrangeLighting.EventLight"] = 1.1;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange Lighting - Time System Lights * By Hudell - www.hudell.com * OrangeTimeSystemLighting.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Time System Lights <OrangeTimeSystemLighting> * @author Hudell * * @param hourColors * @desc A different color mask for each hour of the day. Requires OrangeTimeSystem. * @default #000000, #000000, #000000, #000000, #000000, #111111, #111111, #666666, #AAAAAA, #EEEEEE, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #EEEEEE, #AAAAAA, #776666, #441111, #000000, #000000, #000000 * * @param insideBuildingsHourColor * @desc A different color mask to use inside buildings, for each hour of the day. Requires OrangeTimeSystem. * @default #FFFFFF * * @help * ============================================================================ * Hudell's Plugins * ============================================================================ * * Check out my website: * http://hudell.com * *=============================================================================*/ if (!Hudell || !Hudell.OrangeLighting) { throw new Error("Couldn't find Hudell's OrangeLighting plugin. Please add it before this add-on."); } if (!OrangeTimeSystem) { throw new Error("Couldn't find Hudell's OrangeTimeSystem plugin. Please add it before this add-on."); } (function(lightSystem) { "use strict"; lightSystem.addOns.TimeSystemLights = {}; (function(timeSystemLights){ var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<OrangeTimeSystemLighting>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's OrangeTimeSystemLighting parameters."); } timeSystemLights.Parameters = parameters[0].parameters; timeSystemLights.Param = {}; timeSystemLights.Param.hourColors = (timeSystemLights.Parameters.hourColors || "").split(","); timeSystemLights.Param.insideBuildingsHourColor = (timeSystemLights.Parameters.insideBuildingsHourColor || "").split(","); (function(){ for (var i = 0; i < timeSystemLights.Param.hourColors.length; i++) { timeSystemLights.Param.hourColors[i] = timeSystemLights.Param.hourColors[i].trim(); } for (i = 0; i < timeSystemLights.Param.insideBuildingsHourColor.length; i++) { timeSystemLights.Param.insideBuildingsHourColor[i] = timeSystemLights.Param.insideBuildingsHourColor[i].trim(); } if (timeSystemLights.Param.hourColors.length === 0){ timeSystemLights.Param.hourColors.push('black'); } if (timeSystemLights.Param.insideBuildingsHourColor.length === 0){ timeSystemLights.Param.insideBuildingsHourColor.push('#FFFFFF'); } })(); (function($) { timeSystemLights.oldMaskColor = $.maskColor; $.maskColor = function() { var hour = OrangeTimeSystem.hour; if (OrangeTimeSystem.inside) { return timeSystemLights.Param.insideBuildingsHourColor[hour % timeSystemLights.Param.insideBuildingsHourColor.length]; } else { return timeSystemLights.Param.hourColors[hour % timeSystemLights.Param.hourColors.length]; } }; })(lightSystem.Lightmask.prototype); })(lightSystem.addOns.TimeSystemLights); })(Hudell.OrangeLighting); Imported["OrangeLighting.TimeSystemLights"] = 1.0;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Auto Avoid Obstacles * By Hudell - www.hudell.com * OrangeAutoAvoidObstacles.js * Version: 1.0 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Makes the player automatically Avoid small obstacles, by walking around them * * @param AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @param MaxOffset * @desc The max distance (in tiles) that the character is allowed to walk in a different direction to avoid an obstacle. * @default 0.75 * * @param RetainDirection * @desc If true, the character won't face the other direction when walking around an object. * @default true * * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on http://link.hudell.com/auto-avoid * *=============================================================================*/ var Imported = Imported || {}; if (Imported['MVCommons'] === undefined) { console.log('Download MVCommons: http://link.hudell.com/mvcommons'); throw new Error("This library needs MVCommons to work properly!"); } if (Imported['SuperOrangeMovement'] === undefined) { console.log('Download SuperOrangeMovement: http://link.hudell.com/super-orange-movement'); throw new Error("This library needs SuperOrangeMovement to work properly!"); } var OrangeAutoAvoidObstacles = OrangeAutoAvoidObstacles || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeAutoAvoidObstacles'); $.Param = $.Param || {}; $.Param.AvoidEvents = $.Param["AvoidEvents"] !== "false"; $.Param.OnlyWhenDashing = $.Param["OnlyWhenDashing"] === "true"; $.Param.DashingDelay = Number($.Param["DashingDelay"] || 0); $.Param.WalkingDelay = Number($.Param["WalkingDelay"] || 0); $.Param.MaxOffset = Number($.Param["MaxOffset"] || 0.75); $.Param.RetainDirection = $.Param["RetainDirection"] !== "false"; var avoidObstaclesDelay = 0; // Every time the player succesfully moves, reset the delay var oldGamePlayer_onBeforeMove = Game_Player.prototype.onBeforeMove; Game_Player.prototype.onBeforeMove = function() { if (this.isDashing()) { avoidObstaclesDelay = $.Param.DashingDelay; } else { avoidObstaclesDelay = $.Param.WalkingDelay; } if (oldGamePlayer_onBeforeMove !== undefined) { oldGamePlayer_onBeforeMove.call(this); } }; var oldGamePlayer_trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement; Game_Player.prototype.trySavingFailedMovement = function(direction) { if (oldGamePlayer_trySavingFailedMovement !== undefined) { if (oldGamePlayer_trySavingFailedMovement.call(this, direction)) { return true; } } if (avoidObstaclesDelay > 0) { avoidObstaclesDelay--; } if ($.Param.OnlyWhenDashing === true) { if (!this.isDashing()) { return false; } } if ($.Param.AvoidEvents !== true) { if (this.isTilesetPassable(this._x, this._y, direction)) { var x2 = $gameMap.roundFractionXWithDirection(this._x, direction, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(this._y, direction, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } } } if (this.tryToAvoid(direction, $.Param.MaxOffset)) { return true; } return false; }; Game_Player.prototype.tryToAvoid = function(direction, maxOffset) { if (avoidObstaclesDelay > 0) { return false; } var previousOffset = 0; var offset = this.myStepSize(); var tryDirection = function(xOffset, yOffset, movementDirection, faceDirection) { // Test if the player would be able to move on the faceDirection if they were at the offset position. If they could, then move towards that position for now. if (this.canPass((this._x + xOffset).fix(), (this._y + yOffset).fix(), faceDirection)) { this.executeMove(movementDirection); if ($.Param.RetainDirection) { this.setDirection(faceDirection); } return true; } return false; }; if (direction == Direction.LEFT || direction == Direction.RIGHT) { // If the player can't walk horizontally on the current position, but would be able to walk if he were a little higher or lower then move vertically instead // on the next iterations it will keep trying to move horizontaly again and it will eventually work before the offset is reached var downEnabled = true; var upEnabled = true; while (offset <= maxOffset) { if (downEnabled) { if (!this.canPass(this._x, (this._y + previousOffset).fix(), Direction.DOWN)) { downEnabled = false; } } if (upEnabled) { if (!this.canPass(this._x, (this._y - previousOffset).fix(), Direction.UP)) { upEnabled = false; } } if (downEnabled === true && tryDirection.call(this, 0, offset, Direction.DOWN, direction)) { return true; } if (upEnabled === true && tryDirection.call(this, 0, -offset, Direction.UP, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } else if (direction == Direction.UP || direction == Direction.DOWN) { // If the player can't walk vertically on the current position, but would be able to walk if he were a little left or right then move horizontally instead // on the next iterations it will keep trying to move vertically again and it will eventually work before the offset is reached var leftEnabled = true; var rightEnabled = true; while (offset <= maxOffset) { if (leftEnabled) { if (!this.canPass((this._x - previousOffset).fix(), this._y, Direction.LEFT)) { leftEnabled = false; } } if (rightEnabled) { if (!this.canPass((this._x + previousOffset).fix(), this._y, Direction.RIGHT)) { rightEnabled = false; } } if (rightEnabled === true && tryDirection.call(this, offset, 0, Direction.RIGHT, direction)) { return true; } if (leftEnabled === true && tryDirection.call(this, -offset, 0, Direction.LEFT, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } return false; }; })(OrangeAutoAvoidObstacles); PluginManager.register("OrangeAutoAvoidObstacles", "1.0.0", "Will make the player avoid small obstacles automatically", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-21");
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Super Movement * By Hudell - www.hudell.com * SuperOrangeMovementEx.js * Version: 1.5.2 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Movement Improvements: Diagonal Movement, Pixel Movement, Actor Hitbox Changer. <SuperOrangeMovementEx> * * @param Tile_Sections * @desc How many pieces do you want to break the tiles into? * @default 4 * * @param Diagonal_Movement * @desc Enable Diagonal Movement? * @default true * * @param FollowersDistance * @desc What's the distance (in tiles) that each party member should keep from the next one? * @default 0.5 * * @param TriggerAllAvailableEvents * @desc If true, the game may trigger multiple events when you press a button if there are more than one event in front of you. * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Check the plugin help for detailed explanation * @default false * * @param BlockRepeatedTouchEvents * @desc If false, any touch triggered event will be executed after every step that the player takes inside that tile. * @default true * * @param IgnoreEmptyEvents * @desc If true, the game won't try to trigger events that have no commands * @default true * * @param DisablePixelMovementForMouseRoutes * @desc CAUTION: Check the plugin help for info on disabling this * @default true * * @param CustomPathfinding * @desc Change this to false if you don't want to use OrangePathfinding * @default true * * #param DiagonalPathfinding * #desc Determines if the player can walk diagonally on generated routes * #default true * * @param EnableAutoAvoid * @desc Set this to false to disable the AutoAvoid feature * @default true * * @param AutoAvoid_AvoidEvents * @desc Set this to true if you want the player to avoid events. * @default false * * @param AutoAvoid_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AutoAvoid_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AutoAvoid_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @param AutoAvoid_MaxOffset * @desc The max distance (in tiles) that the character is allowed to walk in a different direction to avoid an obstacle. * @default 0.75 * * @param AutoAvoid_RetainDirection * @desc If true, the character won't face the other direction when walking around an object. * @default true * * @param EnableAutoAvoidDiagonal * @desc Set this to false to disable the AutoAvoid diagonally feature * @default false * * @param AvDiagonal_AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param AvDiagonal_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AvDiagonal_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AvDiagonal_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * * @author Hudell * * * @help * ============================================================================ * Latest Version * ============================================================================ * Get the latest version of this script on * http://link.hudell.com/super-orange-movement * * ============================================================================ * Params * ============================================================================ * * TriggerTouchEventsAfterTeleport: * If you're using pixel movement and you teleport the player * to a tile with a touch triggered event, that event will be * triggered on the first step the player takes. * If you want that to happen, change this to true. * * * DisablePixelMovementForMouseRoutes: * If true, the pixel movement will be disabled when you assign a * fixed move route to the player; * ATTENTION: * If you turn this to false, the player character may get stuck when * controlled with a mouse * *=============================================================================*/ /*:pt * @plugindesc Melhorias no movimento: Movimentação Diagonal, Movimentação por Pixel, MudanΓ§a na caixa de colisΓ£o dos personagens. <SuperOrangeMovementEx> * * @param Tile_Sections * @desc Em quantos pedaΓ§os os tiles deverΓ£o ser quebrados? * @default 4 * * @param Diagonal_Movement * @desc Habilitar movimentação diagonal? * @default true * * @param FollowersDistance * @desc Qual a distΓ’ncia (em tiles) que cada membro do grupo deve manter um do outro? * @default 0.5 * * @param TriggerAllAvailableEvents * @desc Se false, o jogo impedirΓ‘ que mais de um evento seja disparado quando vocΓͺ pressionar Enter na frente de dois eventos * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Clique no botΓ£o ajuda do plugin para uma explicação detalhada * @default false * * @param BlockRepeatedTouchEvents * @desc Se false, qualquer evento touch serΓ‘ executado depois de cada passo do jogador. Se true, apenas ao entrar no tile. * @default true * * @param IgnoreEmptyEvents * @desc Se true, o jogo nΓ£o tentarΓ‘ disparar eventos que nΓ£o possuem comandos, pulando para o prΓ³ximo evento disponΓ­vel * @default true * * @param DisablePixelMovementForMouseRoutes * @desc CUIDADO: Clique no botΓ£o ajuda para mais informaçáes sobre este parametro * @default true * * @param CustomPathfinding * @desc Troque este parametro para false para desativar meu pathfinding personalizado * @default true * * #param DiagonalPathfinding * #desc Determina se o jogador pode andar diagonalmente em rotas geradas * #default true * * @param EnableAutoAvoid * @desc Set this to false to disable the AutoAvoid feature * @default true * * @param AutoAvoid_AvoidEvents * @desc Set this to true if you want the player to avoid events. * @default false * * @param AutoAvoid_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AutoAvoid_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AutoAvoid_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @param AutoAvoid_MaxOffset * @desc The max distance (in tiles) that the character is allowed to walk in a different direction to avoid an obstacle. * @default 0.75 * * @param AutoAvoid_RetainDirection * @desc If true, the character won't face the other direction when walking around an object. * @default true * * @param EnableAutoAvoidDiagonal * @desc Set this to false to disable the AutoAvoid diagonally feature * @default false * * @param AvDiagonal_AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param AvDiagonal_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AvDiagonal_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AvDiagonal_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * @author Hudell * * * @help * ============================================================================ * Última VersΓ£o * ============================================================================ * Baixe a ΓΊltima versΓ£o do script em * http://link.hudell.com/super-orange-movement * * ============================================================================ * Parametros * ============================================================================ * * TriggerTouchEventsAfterTeleport: * Se vocΓͺ estiver usando movimentação por pixel e teletransportar o jogador * para um tile onde hΓ‘ um evento touch, o evento serΓ‘ * disparado no primeiro passo que o jogador der. * Se vocΓͺ quer que isso aconteΓ§a, mude isto para true. * * * DisablePixelMovementForMouseRoutes: * Se true, a movimentação por pixel serΓ‘ desativada quando vocΓͺ usa uma * rota de movimento ou clica em algum ponto do mapa com o mouse. * ATENÇÃO: * Se vocΓͺ mudar isto para false, o personagem do jogador poderΓ‘ ficar preso * quando controlado com o mouse. * *=============================================================================*/ /*:fr * @plugindesc AmΓ©lioration des dΓ©placements : dΓ©placement en diagonale, dΓ©placement au pixel prΓ¨s et adaptation de la hitbox du personnage <SuperOrangeMovementEx> * * @param Tile_Sections * @desc En combien de sous-divisions voulez-vous diviser un tile ? * @default 4 * * @param Diagonal_Movement * @desc Autoriser le mouvement en diagonale ? * @default true * * @param FollowersDistance * @desc Quelle est la distance (en tiles) que doivent conserver chaque personnage du groupe entre eux ? (mode chenille) * @default 0.5 * * @param TriggerAllAvailableEvents * @desc Si true, le jeu pourra dΓ©clencher plusieurs Γ©vΓ©nements quand vous appuyez sur une touche s'il y a plus d'un Γ©vΓ©nement en face de vous. * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Voir la section Aide du plugin pour les explications dΓ©taillΓ©es. * @default false * * @param BlockRepeatedTouchEvents * @desc Si false, tout Γ©vΓ©nement activΓ© par l'appui d'une touche sera activΓ© aprΓ¨s chaque pas que le personnage fera sur le tile de l'Γ©vΓ©nement. * @default true * * @param IgnoreEmptyEvents * @desc Si true, le jeu n'essaiera pas de dΓ©clencher les Γ©vΓ©nements qui n'ont pas de commandes. * @default true * * @param DisablePixelMovementForMouseRoutes * @desc ATTENTION ! Lire attentivement la section Aide avant de dΓ©sactiver cette option (dΓ©sactiver = false). * @default true * * @param CustomPathfinding * @desc Set this to false to disable my custom pathfinding * @default true * * #param DiagonalPathfinding * #desc Determines if the player can walk diagonally on generated routes * #default true * * @param EnableAutoAvoid * @desc Set this to false to disable the AutoAvoid feature * @default true * * @param AutoAvoid_AvoidEvents * @desc Set this to true if you want the player to avoid events. * @default false * * @param AutoAvoid_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AutoAvoid_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AutoAvoid_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @param AutoAvoid_MaxOffset * @desc The max distance (in tiles) that the character is allowed to walk in a different direction to avoid an obstacle. * @default 0.75 * * @param AutoAvoid_RetainDirection * @desc If true, the character won't face the other direction when walking around an object. * @default true * * @param EnableAutoAvoidDiagonal * @desc Set this to false to disable the AutoAvoid Diagonally feature * @default false * * @param AvDiagonal_AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param AvDiagonal_OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param AvDiagonal_DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param AvDiagonal_WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @author Hudell * * * @help * ============================================================================ * DerniΓ¨re version * ============================================================================ * RΓ©cupΓ©rez la derniΓ¨re version du plugin sur : * http://link.hudell.com/super-orange-movement * * ============================================================================ * Explications dΓ©taillΓ©es des paramΓ¨tres * ============================================================================ * * TriggerTouchEventsAfterTeleport : * Si vous utilisez le mouvement au pixel prΓ¨s et que vous tΓ©lΓ©portez le personnage * sur un tile contenant un Γ©vΓ©nement activΓ© par appui sur une touche, * cet Γ©vΓ©nement sera dΓ©clenchΓ© au premier pas que le personnage fera. * Si vous voulez que le plugin autorise cela, changez ceci pour true. * * * DisablePixelMovementForMouseRoutes : * Si true, le mouvement au pixel prΓ¨s sera dΓ©sactivΓ© quand * vous assignerez une route prΓ©dΓ©finie au peersonnage. * ATTENTION : * En revanche, si vous changez ceci pour false, le personnage * pourra restΓ© bloquΓ© quand il sera contrΓ΄lΓ© Γ  la souris. * *=============================================================================*/ var Imported = Imported || {}; if (Imported["SuperOrangeMovement"]) { if (Utils.isOptionValid('test')) { alert("You've got both SuperOrangeMovement and SuperOrangeMovementEx on the same project. SuperOrangeMovementEx will be ignored."); } throw new Error("You've got both SuperOrangeMovement and SuperOrangeMovementEx on the same project. SuperOrangeMovementEx will be ignored."); } if (Imported['MVCommons'] === undefined) { var MVC = MVC || {}; (function($) { $.defaultGetter = function(name) {return function() {return this['_' + name];};}; $.defaultSetter = function(name) {return function(value) {var prop = '_' + name;if ((!this[prop]) || this[prop] !== value) {this[prop] = value;if (this._refresh) {this._refresh();}}};}; $.accessor = function(value, name /* , setter, getter */ ) {Object.defineProperty(value, name, {get: arguments.length > 3 ? arguments[3] : $.defaultGetter(name),set: arguments.length > 2 ? arguments[2] : $.defaultSetter(name),configurable: true});}; $.reader = function(obj, name /*, getter */ ) {Object.defineProperty(obj, name, {get: arguments.length > 2 ? arguments[2] : defaultGetter(name),configurable: true});}; $.getProp = function(meta, propName) {if (meta === undefined) return undefined;if (meta[propName] !== undefined) return meta[propName];for (var key in meta) {if (key.toLowerCase() == propName.toLowerCase()) {return meta[key];}}return undefined;}; })(MVC); Number.prototype.fix = function() {return (parseFloat(this.toPrecision(12)));}; Number.prototype.floor = function() {return Math.floor(this.fix());}; Number.prototype.ceil = function() {return Math.ceil(this.fix());}; Number.prototype.abs = function() {return Math.abs(this);}; } var SuperOrangeMovementEx = SuperOrangeMovementEx || {}; SuperOrangeMovementEx.VERSION = 0.1; // Useful Direction Constants var Direction = { UP: 8, DOWN: 2, LEFT: 4, RIGHT: 6, UP_LEFT: 7, UP_RIGHT: 9, DOWN_LEFT: 1, DOWN_RIGHT: 3, goesUp: function(d) { return [7, 8, 9].indexOf(d) >= 0; }, goesDown: function(d) { return [1, 2, 3].indexOf(d) >= 0; }, goesLeft: function(d) { return [1, 4, 7].indexOf(d) >= 0; }, goesRight: function(d) { return [3, 6, 9].indexOf(d) >= 0; }, joinDirections: function(dir1, dir2) { if (dir1 == Direction.UP || dir2 == Direction.UP) { if (dir1 == Direction.LEFT || dir2 == Direction.LEFT) { return Direction.UP_LEFT; } else if (dir1 == Direction.RIGHT || dir2 == Direction.RIGHT) { return Direction.UP_RIGHT; } } else if (dir1 == Direction.DOWN || dir2 == Direction.DOWN) { if (dir1 == Direction.LEFT || dir2 == Direction.LEFT) { return Direction.DOWN_LEFT; } else if (dir1 == Direction.RIGHT || dir2 == Direction.RIGHT) { return Direction.DOWN_RIGHT; } } if (dir1 >= 1 && dir1 <= 9 && dir1 != 5) { return dir1; } else { return dir2; } }, getButtonName: function(direction, defaultValue) { switch (direction) { case Direction.UP: return 'up'; case Direction.DOWN: return 'down'; case Direction.LEFT: return 'left'; case Direction.RIGHT: return 'right'; default: break; } if (defaultValue === undefined) { defaultValue = ''; } return defaultValue; } }; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<SuperOrangeMovementEx>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's SuperOrangeMovementEx parameters."); } $.Parameters = parameters[0].parameters; $.Param = $.Param || {}; $.Param.Tile_Sections = Number($.Parameters["Tile_Sections"] || 4); $.Param.Diagonal_Movement = $.Parameters["Diagonal_Movement"] !== "false"; $.Param.IgnoreEmptyEvents = $.Parameters["IgnoreEmptyEvents"] !== "false"; $.Param.DisablePixelMovementForMouseRoutes = $.Parameters["DisablePixelMovementForMouseRoutes"] !== "false"; $.Param.CustomPathfinding = $.Parameters["CustomPathfinding"] !== "false"; $.Param.DiagonalPathfinding = false; // $.Param.DiagonalPathfinding = $.Parameters["DiagonalPathfinding"] !== "false"; $.Param.BlockRepeatedTouchEvents = $.Parameters["BlockRepeatedTouchEvents"] !== "false"; $.Param.FollowersDistance = Number($.Parameters["FollowersDistance"] || 0.5); $.Param.TriggerAllAvailableEvents = $.Parameters["TriggerAllAvailableEvents"] === "true"; $.Param.TriggerTouchEventsAfterTeleport = $.Parameters["TriggerTouchEventsAfterTeleport"] === "true"; $.Param.EnableAutoAvoidDiagonal = $.Parameters["EnableAutoAvoidDiagonal"] !== "false"; $.Param.AvDiagonal_AvoidEvents = $.Parameters["AvDiagonal_AvoidEvents"] !== "false"; $.Param.AvDiagonal_OnlyWhenDashing = $.Parameters["AvDiagonal_OnlyWhenDashing"] === "true"; $.Param.AvDiagonal_DashingDelay = Number($.Parameters["AvDiagonal_DashingDelay"] || 0); $.Param.AvDiagonal_WalkingDelay = Number($.Parameters["AvDiagonal_WalkingDelay"] || 0); $.Param.EnableAutoAvoid = $.Parameters["EnableAutoAvoid"] !== "false"; $.Param.AutoAvoid_AvoidEvents = $.Parameters["AutoAvoid_AvoidEvents"] === "true"; $.Param.AutoAvoid_OnlyWhenDashing = $.Parameters["AutoAvoid_OnlyWhenDashing"] === "true"; $.Param.AutoAvoid_DashingDelay = Number($.Parameters["AutoAvoid_DashingDelay"] || 0); $.Param.AutoAvoid_WalkingDelay = Number($.Parameters["AutoAvoid_WalkingDelay"] || 0); $.Param.AutoAvoid_MaxOffset = Number($.Parameters["AutoAvoid_MaxOffset"] || 0.75); $.Param.AutoAvoid_RetainDirection = $.Parameters["AutoAvoid_RetainDirection"] !== "false"; if ($.Param.Tile_Sections === undefined || parseInt($.Param.Tile_Sections, 10) <= 0) { throw new Error("SuperOrangeMovementEx: The Tile_Sections param is invalid."); } $.Param.Step_Size = (1 / $.Param.Tile_Sections).fix(); $._checkedTiles = []; // The insignificantValue is used to decrease from the 'right' and 'bottom' positions of the hitboxes, so that those position do not "flow" to the next integer value // Example: Left = 10, Top = 15, Right = 10.999999, Bottom = 15.999999 instead of Right = 11 and Bottom = 16 var insignificantValue = 0.000001; MVC.reader(Game_CharacterBase.prototype, 'enableFractionalMovement', function() { return false; }); Game_Player.prototype.actor = function() { if ($gameParty._actors.length > 0) { return $gameActors.actor($gameParty._actors[0]); } else { return undefined; } }; Game_Vehicle.prototype.actor = function() { return undefined; }; Game_Vehicle.prototype.check_vehicle_passage = function(x, y) { if (this.isBoat()) { return $gameMap.isBoatPassable(x, y); } if (this.isShip()) { return $gameMap.isShipPassable(x, y); } return this.isAirship(); }; Game_Vehicle.prototype.isLandOk = function(x, y, d) { if (this.isAirship()) { if (!$gameMap.isAirshipLandOk(x, y)) { return false; } if ($gameMap.eventsXy(x, y).length > 0) { return false; } } else { var x2 = $gameMap.roundXWithDirection(x.floor(), d); var y2 = $gameMap.roundYWithDirection(y.floor(), d); if (!$gameMap.isValid(x2, y2)) { return false; } if (!$gameMap.isPassable(x2, y2, this.reverseDir(d))) { return false; } if (this.isCollidedWithCharacters(x2, y2)) { return false; } } return true; }; Game_Character.prototype.roundXWithDirection = function(x, direction) { return $gameMap.roundXWithDirection(x, direction); }; Game_Character.prototype.roundYWithDirection = function(y, direction) { return $gameMap.roundYWithDirection(y, direction); }; var addPropertiesToCharacter = function(character) { // X position of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxX', function(value) { this._hitboxX = value; this._canClearHitboxX = false; }, function() { if (this._hitboxX === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxX'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxX = size; } else { this._hitboxX = 0; } this._canClearHitboxX = true; } else { this._hitboxX = 0; this._canClearHitboxX = false; } } return this._hitboxX; }); // Y position of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxY', function(value) { this._hitboxY = value; this._canClearHitboxY = false; }, function() { if (this._hitboxY === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxY'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxY = size; } else { this._hitboxY = 0; } this._canClearHitboxY = true; } else { this._hitboxY = 0; this._canClearHitboxY = false; } } return this._hitboxY; }); // Width of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxWidth', function(value) { this._hitboxWidth = value; this._canClearHitboxWidth = false; }, function() { if (this._hitboxWidth === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxWidth'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxWidth = size; } else { this._hitboxWidth = $gameMap.tileWidth(); } this._canClearHitboxWidth = true; } else { this._hitboxWidth = $gameMap.tileWidth(); this._canClearHitboxWidth = false; } } return this._hitboxWidth; }); // Height of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxHeight', function(value) { this._hitboxHeight = value; this._canClearHitboxHeight = false; }, function() { if (this._hitboxHeight === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxHeight'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxHeight = size; } else { this._hitboxHeight = $gameMap.tileHeight(); } this._canClearHitboxHeight = true; } else { this._hitboxHeight = $gameMap.tileHeight(); this._canClearHitboxHeight = false; } } return this._hitboxHeight; }); // X position of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxXSize', function() { return (this.hitboxX / $gameMap.tileWidth()).fix(); }); // Y position of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxYSize', function() { return (this.hitboxY / $gameMap.tileHeight()).fix(); }); // Width of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxWidthSize', function() { return (this.hitboxWidth / $gameMap.tileWidth()).fix(); }); // Height of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxHeightSize', function() { return (this.hitboxHeight / $gameMap.tileHeight()).fix(); }); // Gets the top Y position adjusted with the hitbox MVC.reader(character.prototype, 'top', function() { return (this._y + this.hitboxYSize).fix(); }); // Gets the left X position adjusted with the hitbox MVC.reader(character.prototype, 'left', function() { return (this._x + this.hitboxXSize).fix(); }); // Gets the right X position adjusted with the hitbox MVC.reader(character.prototype, 'right', function() { return (this._x + this.hitboxXSize + this.hitboxWidthSize - insignificantValue).fix(); }); // Gets the bottom Y position adjusted with the hitbox MVC.reader(character.prototype, 'bottom', function() { return (this._y + this.hitboxYSize + this.hitboxHeightSize - insignificantValue).fix(); }); }; var addOrangeMovementToCharacter = function(character) { // Adds the hitbox properties to this character addPropertiesToCharacter(character); // Activates Fractional Movement on this character MVC.reader(Game_CharacterBase.prototype, 'enableFractionalMovement', function() { return true; }); // Gets the real _x position of the character MVC.reader(character.prototype, 'floatX', function() { return this._x; }); // Gets the real _y position of the character MVC.reader(character.prototype, 'floatY', function() { return this._y; }); // Gets the Y position of the character as an approximated integer MVC.reader(character.prototype, 'tileY', function() { var diff = this._y - this._y.floor(); if (diff < 0.5) { return this._y.floor(); } else { return this._y.ceil(); } }); // Gets the X position of the character as an approximated integer MVC.reader(character.prototype, 'tileX', function() { var diff = this._x - this._x.floor(); if (diff < 0.5) { return this._x.floor(); } else { return this._x.ceil(); } }); character.prototype.deltaXFrom = function(x) { return $gameMap.deltaX(this._x, x); }; character.prototype.deltaYFrom = function(y) { return $gameMap.deltaY(this._y, y); }; character.prototype.roundXWithDirection = function(x, direction) { return $gameMap.roundFractionXWithDirection(x, direction, this.myStepSize()); }; character.prototype.roundYWithDirection = function(y, direction) { return $gameMap.roundFractionYWithDirection(y, direction, this.myStepSize()); }; // Method that checks if the character can move in a specified direction character.prototype.canGoTo = function(x, y, d) { switch (d) { case Direction.UP: return this.canGoUp(x, y); case Direction.DOWN: return this.canGoDown(x, y); case Direction.LEFT: return this.canGoLeft(x, y); case Direction.RIGHT: return this.canGoRight(x, y); default: return false; } }; character.prototype.checkUpPassage = function(newX, theY, destinationY) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(newX, theY.floor()) && vehicle.check_vehicle_passage(newX, destinationY.floor()); } } if (!$gameMap.isPassable(newX, theY.ceil(), Direction.UP)) { return false; } if (!$gameMap.isPassable(newX, destinationY.floor(), Direction.DOWN)) { return false; } return null; }; // Method that checks if the character can move up character.prototype.canGoUp = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variable endX hold the right position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); // destinationY is the top position where the player is moving to, considering the hitbox var destinationY = (theY - $.Param.Step_Size).fix(); // Run the collission check for every X tile the character is touching for (var newX = theX.floor(); newX <= endX.floor(); newX++) { if (this.checkUpPassage(newX, theY, destinationY) === false) { return false; } } return true; }; character.prototype.checkDownPassage = function(newX, endY, destinationEndY) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(newX, endY.floor()) && vehicle.check_vehicle_passage(newX, destinationEndY.floor()); } } if (destinationEndY.floor() > endY.floor()) { if (!$gameMap.isPassable(newX, endY.floor(), Direction.DOWN)) { return false; } } if (!$gameMap.isPassable(newX, destinationEndY.floor(), Direction.UP)) { return false; } return null; }; // Method that checks if the character can move down character.prototype.canGoDown = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variables endX and endY hold the right and bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); var endY = (theY + this.hitboxHeightSize - insignificantValue).fix(); // destinationY is the top position where the player is moving to, considering the hitbox var destinationY = (theY + $.Param.Step_Size).fix(); // destinationEndY is the bottom position where the player is moving to, considering the hitbox var destinationEndY = (endY + $.Param.Step_Size).fix(); // Run the collission check for every X tile the character is touching for (var newX = theX.floor(); newX <= endX.floor(); newX++) { if (this.checkDownPassage(newX, endY, destinationEndY) === false) { return false; } } return true; }; character.prototype.checkLeftPassage = function(theX, newY, destinationX) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(theX.floor(), newY) && vehicle.check_vehicle_passage(destinationX.floor(), newY); } } if (!$gameMap.isPassable(theX.ceil(), newY, Direction.LEFT)) { return false; } if (!$gameMap.isPassable(destinationX.floor(), newY, Direction.RIGHT)) { return false; } return null; }; // Method that checks if the character can move left character.prototype.canGoLeft = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = x + this.hitboxXSize; var theY = y + this.hitboxYSize; // Variable endY hold the bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endY = theY + this.hitboxHeightSize - insignificantValue; // destinationX is the left position where the player is moving to, considering the hitbox var destinationX = theX - $.Param.Step_Size; // Run the collission check for every Y tile the character is touching for (var newY = theY.floor(); newY <= endY.floor(); newY++) { if (this.checkLeftPassage(theX, newY, destinationX) === false) { return false; } } return true; }; character.prototype.checkRightPassage = function(endX, newY, destinationEndX) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(endX.floor(), newY) && vehicle.check_vehicle_passage(destinationEndX.floor(), newY); } } if (destinationEndX.floor() > endX.floor()) { if (!$gameMap.isPassable(endX.floor(), newY, Direction.RIGHT)) { return false; } } if (!$gameMap.isPassable(destinationEndX.floor(), newY, Direction.LEFT)) { return false; } return null; }; // Method that checks if the character can move right character.prototype.canGoRight = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variables endX and endY hold the right and bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); var endY = (theY + this.hitboxHeightSize - insignificantValue).fix(); // destinationX is the left position where the player is moving to, considering the hitbox var destinationX = (theX + $.Param.Step_Size).fix(); // destinationEndX is the right position where the player is moving to, considering the hitbox var destinationEndX = (endX + $.Param.Step_Size).fix(); // Run the collission check for every Y tile the character is touching for (var newY = theY.floor(); newY <= endY.floor(); newY++) { if (this.checkRightPassage(endX, newY, destinationEndX) === false) { return false; } } return true; }; character.prototype.myStepSize = function() { if (this._moveRoute !== undefined && this._moveRoute !== null) { return 1; } else { return $.Param.Step_Size; } }; character.prototype.isTilesetPassable = function(x, y, d) { var x2 = $gameMap.roundFractionXWithDirection(x, d, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, d, this.myStepSize()); if (!$gameMap.isValid(x2, y2)) { return false; } if (this.isThrough() || this.isDebugThrough()) { return true; } if (!this.isMapPassable(x, y, d)) { return false; } if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return true; } } if (!this.isMapPassable(x2, y2, this.reverseDir(d))) { return false; } return true; }; // Replaces the original canPass method to consider the step size when getting the new x and Y position character.prototype.canPass = function(x, y, d) { if (!this.isTilesetPassable(x, y, d)) { return false; } if (this.isThrough() || this.isDebugThrough()) { return true; } var x2 = $gameMap.roundFractionXWithDirection(x, d, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, d, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } return true; }; // Replaces the original canPassDiagonally method to consider the step size when getting the new x and Y position character.prototype.canPassDiagonally = function(x, y, horz, vert) { var x2 = $gameMap.roundFractionXWithDirection(x, horz, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, vert, this.myStepSize()); if (this.canPass(x, y, vert) && this.canPass(x, y, horz) && this.canPass(x, y2, horz) && this.canPass(x2, y, vert)) { return true; } return false; }; // Replaces the original isMapPassable method, changing the way the collision is checked to consider fractional position character.prototype.isMapPassable = function(x, y, d) { if (Direction.goesUp(d)) { if (!this.canGoUp(x, y)) { return false; } } else if (Direction.goesDown(d)) { if (!this.canGoDown(x, y)) { return false; } } if (Direction.goesLeft(d)) { if (!this.canGoLeft(x, y)) { return false; } } else if (Direction.goesRight(d)) { if (!this.canGoRight(x, y)) { return false; } } return true; }; character.prototype.isTouchingTile = function(x, y) { if (!(x >= this.left.floor() && x <= this.right.floor())) { return false; } if (!(y >= this.top.floor() && y <= this.bottom.floor())) { return false; } return true; }; character.prototype.pos = function(x, y) { return this.isTouchingTile(x, y); }; // Run the callback method for all tiles touched by the character on the informed position character.prototype.runForAllPositions = function(x, y, callback) { var first_x = (x + this.hitboxXSize).floor(); var last_x = (x + this.hitboxXSize + this.hitboxWidthSize - insignificantValue).floor(); var first_y = (y + this.hitboxYSize).floor(); var last_y = (y + this.hitboxYSize + this.hitboxHeightSize - insignificantValue).floor(); for (var newX = first_x; newX <= last_x; newX++) { for (var newY = first_y; newY <= last_y; newY++) { if (callback.call(this, newX, newY) === true) { return true; } } } return false; }; // Replaces the method that checks if the position would collide with an event, because fractional positions should test more than one tile character.prototype.isCollidedWithEvents = function(x, y) { return this.runForAllPositions(x, y, function(block_x, block_y) { //If the player is "inside" it, then this event won't be considered, //because if it did, the player would be locked on it //this shouldn't be possible on normal conditions. if (this.isTouchingTile(block_x, block_y)) { return false; } var events = $gameMap.eventsXyNt(block_x, block_y); return events.some(function(event) { return event.isNormalPriority(); }); }); }; character.prototype.isCollidedWithVehicles = function(x, y) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined || vehicle !== null) { return false; } } return this.runForAllPositions(x, y, function(block_x, block_y) { return $gameMap.boat().posNt(block_x, block_y) || $gameMap.ship().posNt(block_x, block_y); }); }; // Replaces the original moveStraight method, changing the calculation of the new position to consider the step_size character.prototype.moveStraight = function(d) { this.setMovementSuccess(this.canPass(this._x, this._y, d)); if (this.isMovementSucceeded()) { this.setDirection(d); this._x = $gameMap.roundFractionXWithDirection(this._x, d, this.myStepSize()); this._y = $gameMap.roundFractionYWithDirection(this._y, d, this.myStepSize()); this._realX = $gameMap.fractionXWithDirection(this._x, this.reverseDir(d), this.myStepSize()); this._realY = $gameMap.fractionYWithDirection(this._y, this.reverseDir(d), this.myStepSize()); this.increaseSteps(); } else { this.setDirection(d); this.checkEventTriggerTouchFront(d); } }; // Replaces the original moveDiagonally method, changing the calculation of the new position to consider the step_size character.prototype.moveDiagonally = function(horz, vert) { this.setMovementSuccess(this.canPassDiagonally(this._x, this._y, horz, vert)); if (this.isMovementSucceeded()) { this._x = $gameMap.roundFractionXWithDirection(this._x, horz, this.myStepSize()); this._y = $gameMap.roundFractionYWithDirection(this._y, vert, this.myStepSize()); this._realX = $gameMap.fractionXWithDirection(this._x, this.reverseDir(horz), this.myStepSize()); this._realY = $gameMap.fractionYWithDirection(this._y, this.reverseDir(vert), this.myStepSize()); this.increaseSteps(); } if (this._direction === this.reverseDir(horz)) { this.setDirection(horz); } if (this._direction === this.reverseDir(vert)) { this.setDirection(vert); } }; }; addOrangeMovementToCharacter(Game_Player); addOrangeMovementToCharacter(Game_Follower); addOrangeMovementToCharacter(Game_Vehicle); var oldGamePlayer_moveStraight = Game_Player.prototype.moveStraight; var oldGamePlayer_moveDiagonally = Game_Player.prototype.moveDiagonally; Game_Player.prototype.moveStraight = function(d) { if (this.isMovementSucceeded()) { this._followers.updateMove(); } oldGamePlayer_moveStraight.call(this, d); }; Game_Player.prototype.moveDiagonally = function(horz, vert) { if (this.isMovementSucceeded()) { this._followers.updateMove(); } oldGamePlayer_moveDiagonally.call(this, horz, vert); }; Game_Player.prototype.triggerTouchAction = function() { if ($gameTemp.isDestinationValid()) { var direction = this.direction(); var x1 = this.x; var y1 = this.y; var x2 = $gameMap.roundFractionXWithDirection(x1, direction); var y2 = $gameMap.roundFractionYWithDirection(y1, direction); var x3 = $gameMap.roundFractionXWithDirection(x2, direction); var y3 = $gameMap.roundFractionYWithDirection(y2, direction); var destX = $gameTemp.destinationX(); var destY = $gameTemp.destinationY(); if ((x1.floor() === destX || x1.ceil() === destX) && (y1.floor() === destY || y1.ceil() === destY)) { return this.triggerTouchActionD1(x1, y1); } else if ((x2.floor() === destX || x2.ceil() === destX) && (y2.floor() === destY || y2.ceil() === destY)) { return this.triggerTouchActionD2(x2, y2); } else if ((x3.floor() === destX || x3.ceil() === destX) && (y3.floor() === destY || y3.ceil() === destY)) { return this.triggerTouchActionD3(x2, y2); } } return false; }; Game_Player.prototype.forceMoveForward = function() { this.setThrough(true); for (var i = 0; i < $.Param.Tile_Sections; i++) { this.moveForward(); } this.setThrough(false); }; var oldGameActor_basicFloorDamage = Game_Actor.prototype.basicFloorDamage; Game_Actor.prototype.basicFloorDamage = function() { return oldGameActor_basicFloorDamage.call(this) / $.Param.Tile_Sections; }; Game_Map.prototype.isAirshipLandOk = function(x, y) { var first_x = x.floor(); var last_x = x.ceil(); var first_y = y.floor(); var last_y = y.ceil(); for (var newX = first_x; newX <= last_x; newX++) { for (var newY = first_y; newY <= last_y; newY++) { if (!this.checkPassage(newX, newY, 0x800) || !this.checkPassage(newX, newY, 0x0f)) { return false; } } } return true; }; Game_Map.prototype.xWithDirection = function(x, d) { if (Direction.goesLeft(d)) { return x - 1; } else if (Direction.goesRight(d)) { return x + 1; } else { return x; } }; Game_Map.prototype.yWithDirection = function(y, d) { if (Direction.goesDown(d)) { return y + 1; } else if (Direction.goesUp(d)) { return y - 1; } else { return y; } }; Game_Map.prototype.checkLayeredTilesFlags = function(x, y, bit) { var flags = this.tilesetFlags(); for (var newX = x.floor(); newX <= x.ceil(); newX++) { for (var newY = y.floor(); newY <= y.ceil(); newY++) { var result = this.layeredTiles(newX, newY).some(function(tileId) { return (flags[tileId] & bit) !== 0; }); if (result) return result; } } return false; }; // This method adds or subtracts the step_size to an X position, based on the direction Game_Map.prototype.fractionXWithDirection = function(x, d, stepSize) { if (stepSize === undefined) { stepSize = $.Param.Step_Size; } if (Direction.goesLeft(d)) { return x - stepSize; } else if (Direction.goesRight(d)) { return x + stepSize; } else { return x; } }; // This method adds or subtracts the step_size to a Y position, based on the direction Game_Map.prototype.fractionYWithDirection = function(y, d, stepSize) { if (stepSize === undefined) { stepSize = $.Param.Step_Size; } if (Direction.goesDown(d)) { return y + stepSize; } else if (Direction.goesUp(d)) { return y - stepSize; } else { return y; } }; Game_Map.prototype.isValid = function(x, y) { return x >= 0 && x.ceil() < this.width() && y >= 0 && y.ceil() < this.height(); }; // When using horizontally looped maps, this method gets the real X position Game_Map.prototype.roundFractionXWithDirection = function(x, d, stepSize) { return this.roundX(this.fractionXWithDirection(x, d, stepSize)); }; // When using vertically looped maps, this method gets the real Y position Game_Map.prototype.roundFractionYWithDirection = function(y, d, stepSize) { return this.roundY(this.fractionYWithDirection(y, d, stepSize)); }; // Create two methods that can be overriden by add-ons Game_Player.prototype.onBeforeMove = Game_Player.prototype.onBeforeMove || function() {}; Game_Player.prototype.trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement || function(direction) { return false; }; // Replaces the old startMapEvent method to check for events on all tiles touched by the player // Calls the original method inside a loop, unless BlockRepeatedTouchEvents or IgnoreEmptyEvents is true var oldGamePlayer_startMapEvent = Game_Player.prototype.startMapEvent; Game_Player.prototype.startMapEvent = function(x, y, triggers, normal) { if ($gameMap.isEventRunning()) { return; } this.runForAllPositions(x, y, function(block_x, block_y) { // unless it is configured to run all available events, quit the loop if there's an event running if (!$.Param.TriggerAllAvailableEvents) { if ($gameMap.isEventRunning()) { return; } } if ($.Param.BlockRepeatedTouchEvents === true || $.Param.IgnoreEmptyEvents === true) { this.doActualStartMapEvent(block_x, block_y, triggers, normal); } else { oldGamePlayer_startMapEvent.call(this, block_x, block_y, triggers, normal); } }); }; // New method, replaces the original startMapEvent code when BlockRepeatedTouchEvents or IgnoreEmptyEvents is true Game_Player.prototype.doActualStartMapEvent = function(x, y, triggers, normal) { if ($.isTileChecked(x, y)) { return; } $gameMap.eventsXy(x, y).forEach(function(event) { if (!event._erased) { if (event.isTriggerIn(triggers) && event.isNormalPriority() === normal && event.hasAnythingToRun()) { if ($.Param.BlockRepeatedTouchEvents === true && event.isTriggerIn([1, 2])) { $.markTileAsChecked(event.x, event.y); } event.start(); } } }); }; Game_Event.prototype.hasAnythingToRun = function() { if ($.Param.IgnoreEmptyEvents !== true) { return true; } for (var idx in this.list()) { var command = this.list()[idx]; // Comments if (command.code == 108 || command.code == 408) { continue; } // Label if (command.code == 118) { continue; } // End of List if (Number(command.code) === 0) { continue; } return true; } return false; }; $.isTileChecked = function(x, y) { return $._checkedTiles.some(function(tile) { if (tile.x != x) { return false; } if (tile.y != y) { return false; } return true; }); }; $.markTileAsChecked = function(x, y) { $._checkedTiles.push({ x: x, y: y }); }; $.clearCheckedTiles = function() { var newList = []; $._checkedTiles.forEach(function(tile) { if ($gamePlayer.isTouchingTile(tile.x, tile.y)) { newList.push(tile); } }); $._checkedTiles = newList; }; // Small trick used so the game doesn't abuse of the pathfinding script Game_Player.prototype.determineDirectionToDestination = function() { var x = $gameTemp.destinationX(); var y = $gameTemp.destinationY(); if ($.Param.DisablePixelMovementForMouseRoutes !== false) { var horzDirection = undefined; var vertDirection = undefined; if (this._x.floor() < this._x) { if (this.direction() == Direction.LEFT || this.direction() == Direction.RIGHT) { horzDirection = this.direction(); } else { if (this._x.floor() - x >= 1) { horzDirection = Direction.LEFT; } else if (x - this._x.floor() >= 1) { horzDirection = Direction.RIGHT; } } } if (this._y.floor() < this._y) { if (this.direction() == Direction.UP || this.direction() == Direction.DOWN) { vertDirection = this.direction(); } else { if (this._y.floor() - y >= 1) { vertDirection = Direction.UP; } else if (y - this._y.floor() >= 1) { vertDirection = Direction.DOWN; } } } if (horzDirection !== undefined && vertDirection !== undefined) { return Direction.joinDirections(horzDirection, vertDirection); } if (horzDirection !== undefined) { return horzDirection; } if (vertDirection !== undefined) { return vertDirection; } } return this.findDirectionTo(x, y); }; if ($.Param.CustomPathfinding !== false) { Game_Character.prototype.getDirectionNode = function(start, goalX, goalY) { var searchLimit = this.searchLimit(); var mapWidth = $gameMap.width(); var nodeList = []; var openList = []; var closedList = []; var best = start; if (this.x === goalX && this.y === goalY) { return undefined; } nodeList.push(start); openList.push(start.y * mapWidth + start.x); while (nodeList.length > 0) { var bestIndex = 0; for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].f < nodeList[bestIndex].f) { bestIndex = i; } } var current = nodeList[bestIndex]; var x1 = current.x; var y1 = current.y; var pos1 = y1 * mapWidth + x1; var g1 = current.g; nodeList.splice(bestIndex, 1); openList.splice(openList.indexOf(pos1), 1); closedList.push(pos1); if (current.x === goalX && current.y === goalY) { best = current; // goaled = true; break; } if (g1 >= searchLimit) { continue; } // var allDirections = []; // if ($.Param.DiagonalPathfinding !== false) { // allDirections.push(Direction.DOWN_LEFT); // allDirections.push(Direction.DOWN_RIGHT); // allDirections.push(Direction.UP_LEFT); // allDirections.push(Direction.UP_RIGHT); // } // allDirections.push(Direction.LEFT); // allDirections.push(Direction.RIGHT); // allDirections.push(Direction.DOWN); // allDirections.push(Direction.UP); // allDirections.forEach(function(direction){ for (var j = 0; j < 4; j++) { var direction = 2 + j * 2; var x2, y2; if ($.Param.DisablePixelMovementForMouseRoutes !== false) { x2 = $gameMap.roundXWithDirection(x1, direction); y2 = $gameMap.roundYWithDirection(y1, direction); } else { x2 = this.roundXWithDirection(x1, direction); y2 = this.roundYWithDirection(y1, direction); } var pos2 = y2 * mapWidth + x2; if (closedList.contains(pos2)) { // return; continue; } if (x1.floor() == goalX && y1.floor() == goalY) { break; } if (!this.canPass(x1, y1, direction)) { // return; continue; } var g2 = g1; if ($.Param.DisablePixelMovementForMouseRoutes !== false) { g2 += 1; } else { g2 += 1 / $.Param.Tile_Sections; } var index2 = openList.indexOf(pos2); if (index2 < 0 || g2 < nodeList[index2].g) { var neighbor; if (index2 >= 0) { neighbor = nodeList[index2]; } else { neighbor = {}; nodeList.push(neighbor); openList.push(pos2); } neighbor.parent = current; neighbor.x = x2; neighbor.y = y2; neighbor.g = g2; neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY); if (!best || neighbor.f - neighbor.g < best.f - best.g) { best = neighbor; } } }//.bind(this)); } return best; }; Game_Character.prototype.clearCachedNode = function() { this.setCachedNode(); }; Game_Character.prototype.setCachedNode = function(node, goalX, goalY) { this._cachedNode = node; this._cachedGoalX = goalX; this._cachedGoalY = goalY; }; Game_Character.prototype.findDirectionTo = function(goalX, goalY) { if (this.x === goalX && this.y === goalY) { return 0; } if (this._cachedGoalX !== goalX || this._cachedGoalY !== goalY) { this.clearCachedNode(); } var node = this._cachedNode; var start = {}; start.parent = null; start.x = this.x; start.y = this.y; start.g = 0; start.f = $gameMap.distance(start.x, start.y, goalX, goalY); var canRetry = true; if (node === undefined) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } canRetry = false; } if (node.x !== start.x || node.y !== start.y) { while (node.parent && (node.parent.x !== start.x || node.parent.y !== start.y)) { node = node.parent; } if (!node.parent) { // console.log('missing parent. Retrying'); this.clearCachedNode(); if (canRetry) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } } } } var deltaX1 = $gameMap.deltaX(node.x, start.x); var deltaY1 = $gameMap.deltaY(node.y, start.y); if ($.Param.DiagonalPathfinding !== false) { if (deltaY1 > 0 && deltaX1 > 0) { return Direction.DOWN_RIGHT; } else if (deltaY1 > 0 && deltaX1 < 0) { return Direction.DOWN_LEFT; } else if (deltaY1 < 0 && deltaX1 < 0) { return Direction.UP_LEFT; } else if (deltaY1 < 0 && deltaX1 > 0) { return Direction.UP_RIGHT; } } if (deltaY1 > 0) { return 2; } else if (deltaX1 < 0) { return 4; } else if (deltaX1 > 0) { return 6; } else if (deltaY1 < 0) { return 8; } var deltaX2 = this.deltaXFrom(goalX); var deltaY2 = this.deltaYFrom(goalY); var direction = 0; if (Math.abs(deltaX2) > Math.abs(deltaY2)) { direction = deltaX2 > 0 ? 4 : 6; } else if (deltaY2 !== 0) { direction = deltaY2 > 0 ? 8 : 2; } if (direction > 0) { if (!this.canPass(this._x, this._y, direction)) { this.clearCachedNode(); direction = 0; } } return direction; }; } // If the player is holding two direction buttons, Input.dir4 will give you one of them and this method will give you the other one Game_Player.prototype.getAlternativeDirection = function(direction, diagonal_d) { if (direction != diagonal_d) { switch (diagonal_d) { case Direction.UP_LEFT: return direction == Direction.UP ? Direction.LEFT : Direction.UP; case Direction.UP_RIGHT: return direction == Direction.UP ? Direction.RIGHT : Direction.UP; case Direction.DOWN_LEFT: return direction == Direction.DOWN ? Direction.LEFT : Direction.DOWN; case Direction.DOWN_RIGHT: return direction == Direction.DOWN ? Direction.RIGHT : Direction.DOWN; default: break; } } return direction; }; // Replaces the moveByInput method to add all of the plugins functionality Game_Player.prototype.moveByInput = function() { if (this.isMoving() || !this.canMove()) { return; } var button = 'down'; var direction = Input.dir4; var diagonal_d = Input.dir8; var alternative_d = direction; // If there's a directional button pressed, clear the mouse destination if (direction > 0) { $gameTemp.clearDestination(); } // If there's a valid mouse destination, pick the direction from it else if ($gameTemp.isDestinationValid()) { direction = this.determineDirectionToDestination(); diagonal_d = direction; } // If the player is pressing two direction buttons and the direction picked by dir4 is unavailable, try the other non-diagonal direction alternative_d = this.getAlternativeDirection(direction, diagonal_d); button = Direction.getButtonName(direction, button); $.clearCheckedTiles(); if (direction === 0) { return; } if (this.canPass(this._x, this._y, direction) || (direction != alternative_d && this.canPass(this._x, this._y, alternative_d))) { this.onBeforeMove(); // If diagonal movement is active, try it first if ($.Param.Diagonal_Movement) { this.executeMove(diagonal_d); if (this.isMovementSucceeded()) { return; } } this.executeMove(direction); if (!this.isMovementSucceeded()) { this.executeMove(alternative_d); } } else { // If the movement failed, call this method to let add-ons try too if (this.trySavingFailedMovement(direction)) { return; } if (this._direction != direction) { this.setDirection(direction); this.checkEventTriggerTouchFront(); } } }; Game_Player.prototype.executeMove = function(direction) { switch (direction) { case Direction.UP: case Direction.DOWN: case Direction.LEFT: case Direction.RIGHT: this.moveStraight(direction); break; case Direction.UP_LEFT: this.moveDiagonally(Direction.LEFT, Direction.UP); break; case Direction.UP_RIGHT: this.moveDiagonally(Direction.RIGHT, Direction.UP); break; case Direction.DOWN_LEFT: this.moveDiagonally(Direction.LEFT, Direction.DOWN); break; case Direction.DOWN_RIGHT: this.moveDiagonally(Direction.RIGHT, Direction.DOWN); break; default: break; } }; // alias the updateNonmoving method from the Game_Player class to check // if there's any event to trigger var oldGamePlayer_updateNonmoving = Game_Player.prototype.updateNonmoving; Game_Player.prototype.updateNonmoving = function(wasMoving) { oldGamePlayer_updateNonmoving.call(this, wasMoving); // If the player was moving or it's pressing an arrow key if (wasMoving || Input.dir4 !== 0) { // Doesn't trigger anything if there's already something running if (!$gameMap.isEventRunning()) { this.checkEventTriggerThere([1, 2]); // Setups the starting event if there's any. if ($gameMap.setupStartingEvent()) { return; } } } }; // Replaces checkEventTriggerThere to work with pixel movement Game_Player.prototype.checkEventTriggerThere = function(triggers) { if (this.canStartLocalEvents()) { var direction = this.direction(); var x1 = this._x; var y1 = this._y; var x2 = $gameMap.roundFractionXWithDirection(x1, direction); var y2 = $gameMap.roundFractionYWithDirection(y1, direction); this.startMapEvent(x2, y2, triggers, true); if (!$gameMap.isAnyEventStarting() && $gameMap.isCounter(x2, y2)) { var x3 = $gameMap.roundFractionXWithDirection(x2, direction); var y3 = $gameMap.roundFractionYWithDirection(y2, direction); this.startMapEvent(x3, y3, triggers, true); } } }; // ------------------------------------------------ // With Great Movement, comes Great Responsibility // ------------------------------------------------ // Changes the logic used to turn towards the player, because the old one didn't work well with pixel movement Game_Character.prototype.turnTowardPlayer = function() { var sx = this.deltaXFrom($gamePlayer.floatX); var sy = this.deltaYFrom($gamePlayer.floatY); if (sx.abs() < 1 && sy.abs() < 1) { this.setDirection(10 - $gamePlayer.direction); } else { if (sx.abs() > sy.abs()) { this.setDirection(sx > 0 ? 4 : 6); } else if (sy !== 0) { this.setDirection(sy > 0 ? 8 : 2); } } }; // Changes the logic used to turn away from the player, because the old one didn't work well with pixel movement Game_Character.prototype.turnAwayFromPlayer = function() { var sx = this.deltaXFrom($gamePlayer.floatX); var sy = this.deltaYFrom($gamePlayer.floatY); if (sx.abs() < 1 && sy.abs() < 1) { this.setDirection($gamePlayer.direction); } else { if (sx.abs() > sy.abs()) { this.setDirection(sx > 0 ? 7 : 4); } else if (sy !== 0) { this.setDirection(sy > 0 ? 2 : 8); } } }; // Changes the logic used to chase characters, because the old one didn't work well with pixel movement // Also adds the FollowersDistance param. Game_Follower.prototype.chaseCharacter = function(character) { if (!this.isMoving()) { var ideal_x = character.floatX; var ideal_y = character.floatY; switch (character.direction()) { case Direction.DOWN: ideal_y -= $.Param.FollowersDistance; break; case Direction.LEFT: ideal_x += $.Param.FollowersDistance; break; case Direction.RIGHT: ideal_x -= $.Param.FollowersDistance; break; case Direction.UP: ideal_y += $.Param.FollowersDistance; break; default: break; } var sx = this.deltaXFrom(ideal_x); var sy = this.deltaYFrom(ideal_y); if (sx.abs() >= $.Param.Step_Size && sy.abs() >= $.Param.Step_Size) { this.moveDiagonally(sx > 0 ? Direction.LEFT : Direction.RIGHT, sy > 0 ? Direction.UP : Direction.DOWN); } else if (sx.abs() >= $.Param.Step_Size) { this.moveStraight(sx > 0 ? Direction.LEFT : Direction.RIGHT); } else if (sy.abs() >= $.Param.Step_Size) { this.moveStraight(sy > 0 ? Direction.UP : Direction.DOWN); } this.setMoveSpeed($gamePlayer.realMoveSpeed()); } }; if ($.Param.BlockRepeatedTouchEvents === true) { // Overrides command201 to pick the tile where the player was teleported to and add it to the list of tiles that shouldn't trigger events until the player leaves it. var oldGameInterpreter_command201 = Game_Interpreter.prototype.command201; Game_Interpreter.prototype.command201 = function() { oldGameInterpreter_command201.call(this); if ($gameParty.inBattle()) { return; } $.clearCheckedTiles(); if (!$.Param.TriggerTouchEventsAfterTeleport) { $.markTileAsChecked($gamePlayer.x, $gamePlayer.y); } }; } if ($.Param.EnableAutoAvoidDiagonal) { var avoidObstacleDiagonallysDelay = 0; // Every time the player succesfully moves, reset the delay var oldGamePlayer_onBeforeMove = Game_Player.prototype.onBeforeMove; Game_Player.prototype.onBeforeMove = function() { if (this.isDashing()) { avoidObstacleDiagonallysDelay = $.Param.AvDiagonal_DashingDelay; } else { avoidObstacleDiagonallysDelay = $.Param.AvDiagonal_WalkingDelay; } if (oldGamePlayer_onBeforeMove !== undefined) { oldGamePlayer_onBeforeMove.call(this); } }; var oldGamePlayer_trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement; Game_Player.prototype.trySavingFailedMovement = function(direction) { if (oldGamePlayer_trySavingFailedMovement !== undefined) { if (oldGamePlayer_trySavingFailedMovement.call(this, direction)) { return true; } } if (avoidObstacleDiagonallysDelay > 0) { avoidObstacleDiagonallysDelay--; } if ($.Param.AvDiagonal_OnlyWhenDashing === true) { if (!this.isDashing()) { return false; } } if ($.Param.AvDiagonal_AvoidEvents !== true) { if (this.isTilesetPassable(this._x, this._y, direction)) { var x2 = $gameMap.roundFractionXWithDirection(this._x, direction, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(this._y, direction, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } } } if (this.tryToAvoidDiagonally(direction)) { return true; } return false; }; Game_Player.prototype.tryToAvoidDiagonally = function(direction) { if (avoidObstacleDiagonallysDelay > 0) { return false; } if (direction == Direction.LEFT || direction == Direction.RIGHT) { if (this.canPassDiagonally(this._x, this._y, direction, Direction.DOWN)) { this.executeMove(direction - 3); return true; } else if (this.canPassDiagonally(this._x, this._y, direction, Direction.UP)) { this.executeMove(direction + 3); return true; } } else if (direction == Direction.UP || direction == Direction.DOWN) { if (this.canPassDiagonally(this._x, this._y, Direction.LEFT, direction)) { this.executeMove(direction - 1); return true; } else if (this.canPassDiagonally(this._x, this._y, Direction.RIGHT, direction)) { this.executeMove(direction + 1); return true; } } return false; }; } if ($.Param.EnableAutoAvoid) { var avoidObstaclesDelay = 0; // Every time the player succesfully moves, reset the delay var oldGamePlayer_onBeforeMove2 = Game_Player.prototype.onBeforeMove; Game_Player.prototype.onBeforeMove = function() { if (this.isDashing()) { avoidObstaclesDelay = $.Param.AutoAvoid_DashingDelay; } else { avoidObstaclesDelay = $.Param.AutoAvoid_WalkingDelay; } if (oldGamePlayer_onBeforeMove2 !== undefined) { oldGamePlayer_onBeforeMove2.call(this); } }; var oldGamePlayer_trySavingFailedMovement2 = Game_Player.prototype.trySavingFailedMovement; Game_Player.prototype.trySavingFailedMovement = function(direction) { if (oldGamePlayer_trySavingFailedMovement2 !== undefined) { if (oldGamePlayer_trySavingFailedMovement2.call(this, direction)) { return true; } } if (avoidObstaclesDelay > 0) { avoidObstaclesDelay--; } if ($.Param.AutoAvoid_OnlyWhenDashing === true) { if (!this.isDashing()) { return false; } } if ($.Param.AutoAvoid_AvoidEvents !== true) { if (this.isTilesetPassable(this._x, this._y, direction)) { var x2 = $gameMap.roundFractionXWithDirection(this._x, direction, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(this._y, direction, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } } } if (this.tryToAvoid(direction, $.Param.AutoAvoid_MaxOffset)) { return true; } return false; }; Game_Player.prototype.tryToAvoid = function(direction, maxOffset) { if (avoidObstaclesDelay > 0) { return false; } var previousOffset = 0; var offset = this.myStepSize(); var tryDirection = function(xOffset, yOffset, movementDirection, faceDirection) { // Test if the player would be able to move on the faceDirection if they were at the offset position. If they could, then move towards that position for now. if (this.canPass((this._x + xOffset).fix(), (this._y + yOffset).fix(), faceDirection)) { this.executeMove(movementDirection); if ($.Param.AutoAvoid_RetainDirection) { this.setDirection(faceDirection); } return true; } return false; }; if (direction == Direction.LEFT || direction == Direction.RIGHT) { // If the player can't walk horizontally on the current position, but would be able to walk if he were a little higher or lower then move vertically instead // on the next iterations it will keep trying to move horizontaly again and it will eventually work before the offset is reached var downEnabled = true; var upEnabled = true; while (offset <= maxOffset) { if (downEnabled) { if (!this.canPass(this._x, (this._y + previousOffset).fix(), Direction.DOWN)) { downEnabled = false; } } if (upEnabled) { if (!this.canPass(this._x, (this._y - previousOffset).fix(), Direction.UP)) { upEnabled = false; } } if (downEnabled === true && tryDirection.call(this, 0, offset, Direction.DOWN, direction)) { return true; } if (upEnabled === true && tryDirection.call(this, 0, -offset, Direction.UP, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } else if (direction == Direction.UP || direction == Direction.DOWN) { // If the player can't walk vertically on the current position, but would be able to walk if he were a little left or right then move horizontally instead // on the next iterations it will keep trying to move vertically again and it will eventually work before the offset is reached var leftEnabled = true; var rightEnabled = true; while (offset <= maxOffset) { if (leftEnabled) { if (!this.canPass((this._x - previousOffset).fix(), this._y, Direction.LEFT)) { leftEnabled = false; } } if (rightEnabled) { if (!this.canPass((this._x + previousOffset).fix(), this._y, Direction.RIGHT)) { rightEnabled = false; } } if (rightEnabled === true && tryDirection.call(this, offset, 0, Direction.RIGHT, direction)) { return true; } if (leftEnabled === true && tryDirection.call(this, -offset, 0, Direction.LEFT, direction)) { return true; } previousOffset = offset; offset += this.myStepSize(); } } return false; }; } })(SuperOrangeMovementEx); Imported.SuperOrangeMovementEx = 1.5;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Super Movement * By Hudell - www.hudell.com * SuperOrangeMovement.js * Version: 1.5.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Movement Improvements: Diagonal Movement, Pixel Movement, Actor Hitbox Changer. <SuperOrangeMovement> * * @param Tile_Sections * @desc How many pieces do you want to break the tiles into? * @default 4 * * @param Diagonal_Movement * @desc Enable Diagonal Movement? * @default true * * @param FollowersDistance * @desc What's the distance (in tiles) that each party member should keep from the next one? * @default 0.5 * * @param TriggerAllAvailableEvents * @desc If true, the game may trigger multiple events when you press a button if there are more than one event in front of you. * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Check the plugin help for detailed explanation * @default false * * @param BlockRepeatedTouchEvents * @desc If false, any touch triggered event will be executed after every step that the player takes inside that tile. * @default true * * @param IgnoreEmptyEvents * @desc If true, the game won't try to trigger events that have no commands * @default true * * @param DisablePixelMovementForMouseRoutes * @desc CAUTION: Check the plugin help for info on disabling this * @default true * * @param CustomPathfinding * @desc Change this to false if you don't want to use OrangePathfinding * @default true * * @author Hudell * * * @help * ============================================================================ * Latest Version * ============================================================================ * Get the latest version of this script on * http://link.hudell.com/super-orange-movement * * ============================================================================ * Params * ============================================================================ * * TriggerTouchEventsAfterTeleport: * If you're using pixel movement and you teleport the player * to a tile with a touch triggered event, that event will be * triggered on the first step the player takes. * If you want that to happen, change this to true. * * * DisablePixelMovementForMouseRoutes: * If true, the pixel movement will be disabled when you assign a * fixed move route to the player; * ATTENTION: * If you turn this to false, the player character may get stuck when * controlled with a mouse * *=============================================================================*/ /*:pt * @plugindesc Melhorias no movimento: Movimentação Diagonal, Movimentação por Pixel, MudanΓ§a na caixa de colisΓ£o dos personagens. <SuperOrangeMovement> * * @param Tile_Sections * @desc Em quantos pedaΓ§os os tiles deverΓ£o ser quebrados? * @default 4 * * @param Diagonal_Movement * @desc Habilitar movimentação diagonal? * @default true * * @param FollowersDistance * @desc Qual a distΓ’ncia (em tiles) que cada membro do grupo deve manter um do outro? * @default 0.5 * * @param TriggerAllAvailableEvents * @desc Se false, o jogo impedirΓ‘ que mais de um evento seja disparado quando vocΓͺ pressionar Enter na frente de dois eventos * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Clique no botΓ£o ajuda do plugin para uma explicação detalhada * @default false * * @param BlockRepeatedTouchEvents * @desc Se false, qualquer evento touch serΓ‘ executado depois de cada passo do jogador. Se true, apenas ao entrar no tile. * @default true * * @param IgnoreEmptyEvents * @desc Se true, o jogo nΓ£o tentarΓ‘ disparar eventos que nΓ£o possuem comandos, pulando para o prΓ³ximo evento disponΓ­vel * @default true * * @param DisablePixelMovementForMouseRoutes * @desc CUIDADO: Clique no botΓ£o ajuda para mais informaçáes sobre este parametro * @default true * * @param CustomPathfinding * @desc Troque este parametro para false para desativar meu pathfinding personalizado * @default true * * @author Hudell * * * @help * ============================================================================ * Última VersΓ£o * ============================================================================ * Baixe a ΓΊltima versΓ£o do script em * http://link.hudell.com/super-orange-movement * * ============================================================================ * Parametros * ============================================================================ * * TriggerTouchEventsAfterTeleport: * Se vocΓͺ estiver usando movimentação por pixel e teletransportar o jogador * para um tile onde hΓ‘ um evento touch, o evento serΓ‘ * disparado no primeiro passo que o jogador der. * Se vocΓͺ quer que isso aconteΓ§a, mude isto para true. * * * DisablePixelMovementForMouseRoutes: * Se true, a movimentação por pixel serΓ‘ desativada quando vocΓͺ usa uma * rota de movimento ou clica em algum ponto do mapa com o mouse. * ATENÇÃO: * Se vocΓͺ mudar isto para false, o personagem do jogador poderΓ‘ ficar preso * quando controlado com o mouse. * *=============================================================================*/ /*:fr * @plugindesc AmΓ©lioration des dΓ©placements : dΓ©placement en diagonale, dΓ©placement au pixel prΓ¨s et adaptation de la hitbox du personnage <SuperOrangeMovement> * * @param Tile_Sections * @desc En combien de sous-divisions voulez-vous diviser un tile ? * @default 4 * * @param Diagonal_Movement * @desc Autoriser le mouvement en diagonale ? * @default true * * @param FollowersDistance * @desc Quelle est la distance (en tiles) que doivent conserver chaque personnage du groupe entre eux ? (mode chenille) * @default 0.5 * * @param TriggerAllAvailableEvents * @desc Si true, le jeu pourra dΓ©clencher plusieurs Γ©vΓ©nements quand vous appuyez sur une touche s'il y a plus d'un Γ©vΓ©nement en face de vous. * @default false * * @param TriggerTouchEventsAfterTeleport * @desc Voir la section Aide du plugin pour les explications dΓ©taillΓ©es. * @default false * * @param BlockRepeatedTouchEvents * @desc Si false, tout Γ©vΓ©nement activΓ© par l'appui d'une touche sera activΓ© aprΓ¨s chaque pas que le personnage fera sur le tile de l'Γ©vΓ©nement. * @default true * * @param IgnoreEmptyEvents * @desc Si true, le jeu n'essaiera pas de dΓ©clencher les Γ©vΓ©nements qui n'ont pas de commandes. * @default true * * @param DisablePixelMovementForMouseRoutes * @desc ATTENTION ! Lire attentivement la section Aide avant de dΓ©sactiver cette option (dΓ©sactiver = false). * @default true * * @param CustomPathfinding * @desc Set this to false to disable my custom pathfinding * @default true * * @author Hudell * * * @help * ============================================================================ * DerniΓ¨re version * ============================================================================ * RΓ©cupΓ©rez la derniΓ¨re version du plugin sur : * http://link.hudell.com/super-orange-movement * * ============================================================================ * Explications dΓ©taillΓ©es des paramΓ¨tres * ============================================================================ * * TriggerTouchEventsAfterTeleport : * Si vous utilisez le mouvement au pixel prΓ¨s et que vous tΓ©lΓ©portez le personnage * sur un tile contenant un Γ©vΓ©nement activΓ© par appui sur une touche, * cet Γ©vΓ©nement sera dΓ©clenchΓ© au premier pas que le personnage fera. * Si vous voulez que le plugin autorise cela, changez ceci pour true. * * * DisablePixelMovementForMouseRoutes : * Si true, le mouvement au pixel prΓ¨s sera dΓ©sactivΓ© quand * vous assignerez une route prΓ©dΓ©finie au peersonnage. * ATTENTION : * En revanche, si vous changez ceci pour false, le personnage * pourra restΓ© bloquΓ© quand il sera contrΓ΄lΓ© Γ  la souris. * *=============================================================================*/ var Imported = Imported || {}; if (Imported["SuperOrangeMovementEx"]) { if (Utils.isOptionValid('test')) { alert("You've got both SuperOrangeMovement and SuperOrangeMovementEx on the same project. SuperOrangeMovement will be ignored."); } throw new Error("You've got both SuperOrangeMovement and SuperOrangeMovementEx on the same project. SuperOrangeMovement will be ignored."); } if (Imported['MVCommons'] === undefined) { var MVC = {}; (function($){ $.defaultGetter = function(name) { return function () { return this['_' + name]; }; }; $.defaultSetter = function(name) { return function (value) { var prop = '_' + name; if ((!this[prop]) || this[prop] !== value) { this[prop] = value; if (this._refresh) { this._refresh(); } } }; }; $.accessor = function(value, name /* , setter, getter */) { Object.defineProperty(value, name, { get: arguments.length > 3 ? arguments[3] : $.defaultGetter(name), set: arguments.length > 2 ? arguments[2] : $.defaultSetter(name), configurable: true });}; $.reader = function(obj, name /*, getter */) {Object.defineProperty(obj, name, {get: arguments.length > 2 ? arguments[2] : defaultGetter(name), configurable: true});}; $.getProp = function(meta, propName){if (meta === undefined) return undefined;if (meta[propName] !== undefined) return meta[propName];for (var key in meta) {if (key.toLowerCase() == propName.toLowerCase()) {return meta[key];}}return undefined;}; })(MVC); Number.prototype.fix = function() { return (parseFloat(this.toPrecision(12))); }; Number.prototype.floor = function() { return Math.floor(this.fix()); }; Number.prototype.ceil = function() { return Math.ceil(this.fix()); }; Number.prototype.abs = function() { return Math.abs(this); }; if (Utils.isOptionValid('test')) { console.log('MVC not found, SuperOrangeMovement will be using essentials (copied from MVC 1.2.1).'); } } var SuperOrangeMovement = SuperOrangeMovement || {}; SuperOrangeMovement.VERSION = 0.1; // Useful Direction Constants var Direction = { UP: 8, DOWN: 2, LEFT: 4, RIGHT: 6, UP_LEFT: 7, UP_RIGHT: 9, DOWN_LEFT: 1, DOWN_RIGHT: 3, goesUp: function(d) { return [7, 8, 9].indexOf(d) >= 0; }, goesDown: function(d) { return [1, 2, 3].indexOf(d) >= 0; }, goesLeft: function(d) { return [1, 4, 7].indexOf(d) >= 0; }, goesRight: function(d) { return [3, 6, 9].indexOf(d) >= 0; }, joinDirections: function(dir1, dir2) { if (dir1 == Direction.UP || dir2 == Direction.UP) { if (dir1 == Direction.LEFT || dir2 == Direction.LEFT) { return Direction.UP_LEFT; } else if (dir1 == Direction.RIGHT || dir2 == Direction.RIGHT) { return Direction.UP_RIGHT; } } else if (dir1 == Direction.DOWN || dir2 == Direction.DOWN) { if (dir1 == Direction.LEFT || dir2 == Direction.LEFT) { return Direction.DOWN_LEFT; } else if (dir1 == Direction.RIGHT || dir2 == Direction.RIGHT) { return Direction.DOWN_RIGHT; } } if (dir1 >= 1 && dir1 <= 9 && dir1 != 5) { return dir1; } else { return dir2; } }, getButtonName: function(direction, defaultValue) { switch (direction) { case Direction.UP: return 'up'; case Direction.DOWN: return 'down'; case Direction.LEFT: return 'left'; case Direction.RIGHT: return 'right'; default: break; } if (defaultValue === undefined) { defaultValue = ''; } return defaultValue; } }; (function($) { "use strict"; var parameters = $plugins.filter(function(plugin) { return plugin.description.contains('<SuperOrangeMovement>'); }); if (parameters.length === 0) { throw new Error("Couldn't find Hudell's SuperOrangeMovement parameters."); } $.Parameters = parameters[0].parameters; $.Param = $.Param || {}; $.Param.Tile_Sections = Number($.Parameters["Tile_Sections"] || 4); $.Param.Diagonal_Movement = $.Parameters["Diagonal_Movement"] !== "false"; $.Param.IgnoreEmptyEvents = $.Parameters["IgnoreEmptyEvents"] !== "false"; $.Param.DisablePixelMovementForMouseRoutes = $.Parameters["DisablePixelMovementForMouseRoutes"] !== "false"; $.Param.BlockRepeatedTouchEvents = $.Parameters["BlockRepeatedTouchEvents"] !== "false"; $.Param.FollowersDistance = Number($.Parameters["FollowersDistance"] || 0.5); $.Param.TriggerAllAvailableEvents = $.Parameters["TriggerAllAvailableEvents"] === "true"; $.Param.TriggerTouchEventsAfterTeleport = $.Parameters["TriggerTouchEventsAfterTeleport"] === "true"; $.Param.CustomPathfinding = $.Parameters["CustomPathfinding"] !== "false"; $.Param.DiagonalPathfinding = false; if ($.Param.Tile_Sections === undefined || parseInt($.Param.Tile_Sections, 10) <= 0) { throw new Error("SuperOrangeMovement: The Tile_Sections param is invalid."); } $.Param.Step_Size = (1 / $.Param.Tile_Sections).fix(); $._checkedTiles = []; // The insignificantValue is used to decrease from the 'right' and 'bottom' positions of the hitboxes, so that those position do not "flow" to the next integer value // Example: Left = 10, Top = 15, Right = 10.999999, Bottom = 15.999999 instead of Right = 11 and Bottom = 16 var insignificantValue = 0.000001; MVC.reader(Game_CharacterBase.prototype, 'enableFractionalMovement', function() { return false; }); Game_Player.prototype.actor = function() { if ($gameParty._actors.length > 0) { return $gameActors.actor($gameParty._actors[0]); } else { return undefined; } }; Game_Vehicle.prototype.actor = function() { return undefined; }; Game_Vehicle.prototype.check_vehicle_passage = function(x, y) { if (this.isBoat()) { return $gameMap.isBoatPassable(x, y); } if (this.isShip()) { return $gameMap.isShipPassable(x, y); } return this.isAirship(); }; Game_Vehicle.prototype.isLandOk = function(x, y, d) { if (this.isAirship()) { if (!$gameMap.isAirshipLandOk(x, y)) { return false; } if ($gameMap.eventsXy(x, y).length > 0) { return false; } } else { var x2 = $gameMap.roundXWithDirection(x.floor(), d); var y2 = $gameMap.roundYWithDirection(y.floor(), d); if (!$gameMap.isValid(x2, y2)) { return false; } if (!$gameMap.isPassable(x2, y2, this.reverseDir(d))) { return false; } if (this.isCollidedWithCharacters(x2, y2)) { return false; } } return true; }; Game_Character.prototype.roundXWithDirection = function(x, direction) { return $gameMap.roundXWithDirection(x, direction); }; Game_Character.prototype.roundYWithDirection = function(y, direction) { return $gameMap.roundYWithDirection(y, direction); }; var addPropertiesToCharacter = function(character) { // X position of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxX', function(value) { this._hitboxX = value; this._canClearHitboxX = false; }, function() { if (this._hitboxX === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxX'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxX = size; } else { this._hitboxX = 0; } this._canClearHitboxX = true; } else { this._hitboxX = 0; this._canClearHitboxX = false; } } return this._hitboxX; }); // Y position of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxY', function(value) { this._hitboxY = value; this._canClearHitboxY = false; }, function() { if (this._hitboxY === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxY'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxY = size; } else { this._hitboxY = 0; } this._canClearHitboxY = true; } else { this._hitboxY = 0; this._canClearHitboxY = false; } } return this._hitboxY; }); // Width of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxWidth', function(value) { this._hitboxWidth = value; this._canClearHitboxWidth = false; }, function() { if (this._hitboxWidth === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxWidth'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxWidth = size; } else { this._hitboxWidth = $gameMap.tileWidth(); } this._canClearHitboxWidth = true; } else { this._hitboxWidth = $gameMap.tileWidth(); this._canClearHitboxWidth = false; } } return this._hitboxWidth; }); // Height of the character hitbox (in pixels) MVC.accessor(character.prototype, 'hitboxHeight', function(value) { this._hitboxHeight = value; this._canClearHitboxHeight = false; }, function() { if (this._hitboxHeight === undefined) { var actor = this.actor(); if (actor !== undefined) { var size = MVC.getProp(actor.actor().meta, 'hitboxHeight'); if (size !== undefined) { size = parseInt(size, 10); } if (typeof(size) == "number") { this._hitboxHeight = size; } else { this._hitboxHeight = $gameMap.tileHeight(); } this._canClearHitboxHeight = true; } else { this._hitboxHeight = $gameMap.tileHeight(); this._canClearHitboxHeight = false; } } return this._hitboxHeight; }); // X position of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxXSize', function() { return (this.hitboxX / $gameMap.tileWidth()).fix(); }); // Y position of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxYSize', function() { return (this.hitboxY / $gameMap.tileHeight()).fix(); }); // Width of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxWidthSize', function() { return (this.hitboxWidth / $gameMap.tileWidth()).fix(); }); // Height of the character hitbox (in tiles) MVC.reader(character.prototype, 'hitboxHeightSize', function() { return (this.hitboxHeight / $gameMap.tileHeight()).fix(); }); // Gets the top Y position adjusted with the hitbox MVC.reader(character.prototype, 'top', function() { return (this._y + this.hitboxYSize).fix(); }); // Gets the left X position adjusted with the hitbox MVC.reader(character.prototype, 'left', function() { return (this._x + this.hitboxXSize).fix(); }); // Gets the right X position adjusted with the hitbox MVC.reader(character.prototype, 'right', function() { return (this._x + this.hitboxXSize + this.hitboxWidthSize - insignificantValue).fix(); }); // Gets the bottom Y position adjusted with the hitbox MVC.reader(character.prototype, 'bottom', function() { return (this._y + this.hitboxYSize + this.hitboxHeightSize - insignificantValue).fix(); }); }; var addOrangeMovementToCharacter = function(character) { // Adds the hitbox properties to this character addPropertiesToCharacter(character); // Activates Fractional Movement on this character MVC.reader(Game_CharacterBase.prototype, 'enableFractionalMovement', function() { return true; }); // Gets the real _x position of the character MVC.reader(character.prototype, 'floatX', function() { return this._x; }); // Gets the real _y position of the character MVC.reader(character.prototype, 'floatY', function() { return this._y; }); // Gets the Y position of the character as an approximated integer MVC.reader(character.prototype, 'tileY', function() { var diff = this._y - this._y.floor(); if (diff < 0.5) { return this._y.floor(); } else { return this._y.ceil(); } }); // Gets the X position of the character as an approximated integer MVC.reader(character.prototype, 'tileX', function() { var diff = this._x - this._x.floor(); if (diff < 0.5) { return this._x.floor(); } else { return this._x.ceil(); } }); // MVC.reader(character.prototype, 'x', function() { // return this.tileX; // }); // MVC.reader(character.prototype, 'y', function() { // return this.tileY; // }); character.prototype.deltaXFrom = function(x) { return $gameMap.deltaX(this._x, x); }; character.prototype.deltaYFrom = function(y) { return $gameMap.deltaY(this._y, y); }; character.prototype.roundXWithDirection = function(x, direction) { return $gameMap.roundFractionXWithDirection(x, direction, this.myStepSize()); }; character.prototype.roundYWithDirection = function(y, direction) { return $gameMap.roundFractionYWithDirection(y, direction, this.myStepSize()); }; // Method that checks if the character can move in a specified direction character.prototype.canGoTo = function(x, y, d) { switch (d) { case Direction.UP: return this.canGoUp(x, y); case Direction.DOWN: return this.canGoDown(x, y); case Direction.LEFT: return this.canGoLeft(x, y); case Direction.RIGHT: return this.canGoRight(x, y); default: return false; } }; character.prototype.checkUpPassage = function(newX, theY, destinationY) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(newX, theY.floor()) && vehicle.check_vehicle_passage(newX, destinationY.floor()); } } if (!$gameMap.isPassable(newX, theY.ceil(), Direction.UP)) { return false; } if (!$gameMap.isPassable(newX, destinationY.floor(), Direction.DOWN)) { return false; } return null; }; // Method that checks if the character can move up character.prototype.canGoUp = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variable endX hold the right position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); // destinationY is the top position where the player is moving to, considering the hitbox var destinationY = (theY - $.Param.Step_Size).fix(); // Run the collission check for every X tile the character is touching for (var newX = theX.floor(); newX <= endX.floor(); newX++) { if (this.checkUpPassage(newX, theY, destinationY) === false) { return false; } } return true; }; character.prototype.checkDownPassage = function(newX, endY, destinationEndY) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(newX, endY.floor()) && vehicle.check_vehicle_passage(newX, destinationEndY.floor()); } } if (destinationEndY.floor() > endY.floor()) { if (!$gameMap.isPassable(newX, endY.floor(), Direction.DOWN)) { return false; } } if (!$gameMap.isPassable(newX, destinationEndY.floor(), Direction.UP)) { return false; } return null; }; // Method that checks if the character can move down character.prototype.canGoDown = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variables endX and endY hold the right and bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); var endY = (theY + this.hitboxHeightSize - insignificantValue).fix(); // destinationY is the top position where the player is moving to, considering the hitbox var destinationY = (theY + $.Param.Step_Size).fix(); // destinationEndY is the bottom position where the player is moving to, considering the hitbox var destinationEndY = (endY + $.Param.Step_Size).fix(); // Run the collission check for every X tile the character is touching for (var newX = theX.floor(); newX <= endX.floor(); newX++) { if (this.checkDownPassage(newX, endY, destinationEndY) === false) { return false; } } return true; }; character.prototype.checkLeftPassage = function(theX, newY, destination_x) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(theX.floor(), newY) && vehicle.check_vehicle_passage(destination_x.floor(), newY); } } if (!$gameMap.isPassable(theX.ceil(), newY, Direction.LEFT)) { return false; } if (!$gameMap.isPassable(destination_x.floor(), newY, Direction.RIGHT)) { return false; } return null; }; // Method that checks if the character can move left character.prototype.canGoLeft = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = x + this.hitboxXSize; var theY = y + this.hitboxYSize; // Variable endY hold the bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endY = theY + this.hitboxHeightSize - insignificantValue; // destination_x is the left position where the player is moving to, considering the hitbox var destination_x = theX - $.Param.Step_Size; // Run the collission check for every Y tile the character is touching for (var newY = theY.floor(); newY <= endY.floor(); newY++) { if (this.checkLeftPassage(theX, newY, destination_x) === false) { return false; } } return true; }; character.prototype.checkRightPassage = function(endX, newY, destinationEndX) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return vehicle.check_vehicle_passage(endX.floor(), newY) && vehicle.check_vehicle_passage(destinationEndX.floor(), newY); } } if (destinationEndX.floor() > endX.floor()) { if (!$gameMap.isPassable(endX.floor(), newY, Direction.RIGHT)) { return false; } } if (!$gameMap.isPassable(destinationEndX.floor(), newY, Direction.LEFT)) { return false; } return null; }; // Method that checks if the character can move right character.prototype.canGoRight = function(x, y) { // Variables theX and theY hold the true position, considering the hitbox configuration var theX = (x + this.hitboxXSize).fix(); var theY = (y + this.hitboxYSize).fix(); // Variables endX and endY hold the right and bottom position, considering the hitbox configuration // The script decreases an insignificant value from it to ensure that this position doesn't pass to the next integer value unless the character is actually on the next tile. var endX = (theX + this.hitboxWidthSize - insignificantValue).fix(); var endY = (theY + this.hitboxHeightSize - insignificantValue).fix(); // destination_x is the left position where the player is moving to, considering the hitbox var destination_x = (theX + $.Param.Step_Size).fix(); // destinationEndX is the right position where the player is moving to, considering the hitbox var destinationEndX = (endX + $.Param.Step_Size).fix(); // Run the collission check for every Y tile the character is touching for (var newY = theY.floor(); newY <= endY.floor(); newY++) { if (this.checkRightPassage(endX, newY, destinationEndX) === false) { return false; } } return true; }; character.prototype.myStepSize = function() { if (this._moveRoute !== undefined && this._moveRoute !== null) { return 1; } else { return $.Param.Step_Size; } }; character.prototype.isTilesetPassable = function(x, y, d) { var x2 = $gameMap.roundFractionXWithDirection(x, d, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, d, this.myStepSize()); if (!$gameMap.isValid(x2, y2)) { return false; } if (this.isThrough() || this.isDebugThrough()) { return true; } if (!this.isMapPassable(x, y, d)) { return false; } if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined && vehicle !== null) { return true; } } if (!this.isMapPassable(x2, y2, this.reverseDir(d))) { return false; } return true; }; // Replaces the original canPass method to consider the step size when getting the new x and Y position character.prototype.canPass = function(x, y, d) { if (!this.isTilesetPassable(x, y, d)) { return false; } if (this.isThrough() || this.isDebugThrough()) { return true; } var x2 = $gameMap.roundFractionXWithDirection(x, d, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, d, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } return true; }; // Replaces the original canPassDiagonally method to consider the step size when getting the new x and Y position character.prototype.canPassDiagonally = function(x, y, horz, vert) { var x2 = $gameMap.roundFractionXWithDirection(x, horz, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(y, vert, this.myStepSize()); if (this.canPass(x, y, vert) && this.canPass(x, y, horz) && this.canPass(x, y2, horz) && this.canPass(x2, y, vert)) { return true; } return false; }; // Replaces the original isMapPassable method, changing the way the collision is checked to consider fractional position character.prototype.isMapPassable = function(x, y, d) { if (Direction.goesUp(d)) { if (!this.canGoUp(x, y)) { return false; } } else if (Direction.goesDown(d)) { if (!this.canGoDown(x, y)) { return false; } } if (Direction.goesLeft(d)) { if (!this.canGoLeft(x, y)) { return false; } } else if (Direction.goesRight(d)) { if (!this.canGoRight(x, y)) { return false; } } return true; }; character.prototype.isTouchingTile = function(x, y) { if (!(x >= this.left.floor() && x <= this.right.floor())) { return false; } if (!(y >= this.top.floor() && y <= this.bottom.floor())) { return false; } return true; }; character.prototype.pos = function(x, y) { return this.isTouchingTile(x, y); }; // Run the callback method for all tiles touched by the character on the informed position character.prototype.runForAllPositions = function(x, y, callback) { var first_x = (x + this.hitboxXSize).floor(); var last_x = (x + this.hitboxXSize + this.hitboxWidthSize - insignificantValue).floor(); var first_y = (y + this.hitboxYSize).floor(); var last_y = (y + this.hitboxYSize + this.hitboxHeightSize - insignificantValue).floor(); for (var newX = first_x; newX <= last_x; newX++) { for (var newY = first_y; newY <= last_y; newY++) { if (callback.call(this, newX, newY) === true) { return true; } } } return false; }; // Replaces the method that checks if the position would collide with an event, because fractional positions should test more than one tile character.prototype.isCollidedWithEvents = function(x, y) { return this.runForAllPositions(x, y, function(block_x, block_y) { //If the player is "inside" it, then this event won't be considered, //because if it did, the player would be locked on it //this shouldn't be possible on normal conditions. if (this.isTouchingTile(block_x, block_y)) { return false; } var events = $gameMap.eventsXyNt(block_x, block_y); return events.some(function(event) { return event.isNormalPriority(); }); }); }; character.prototype.isCollidedWithVehicles = function(x, y) { if (this instanceof Game_Player) { var vehicle = this.vehicle(); if (vehicle !== undefined || vehicle !== null) { return false; } } return this.runForAllPositions(x, y, function(block_x, block_y) { return $gameMap.boat().posNt(block_x, block_y) || $gameMap.ship().posNt(block_x, block_y); }); }; // Replaces the original moveStraight method, changing the calculation of the new position to consider the step_size character.prototype.moveStraight = function(d) { this.setMovementSuccess(this.canPass(this._x, this._y, d)); if (this.isMovementSucceeded()) { this.setDirection(d); this._x = $gameMap.roundFractionXWithDirection(this._x, d, this.myStepSize()); this._y = $gameMap.roundFractionYWithDirection(this._y, d, this.myStepSize()); this._realX = $gameMap.fractionXWithDirection(this._x, this.reverseDir(d), this.myStepSize()); this._realY = $gameMap.fractionYWithDirection(this._y, this.reverseDir(d), this.myStepSize()); this.increaseSteps(); } else { this.setDirection(d); this.checkEventTriggerTouchFront(d); } }; // Replaces the original moveDiagonally method, changing the calculation of the new position to consider the step_size character.prototype.moveDiagonally = function(horz, vert) { this.setMovementSuccess(this.canPassDiagonally(this._x, this._y, horz, vert)); if (this.isMovementSucceeded()) { this._x = $gameMap.roundFractionXWithDirection(this._x, horz, this.myStepSize()); this._y = $gameMap.roundFractionYWithDirection(this._y, vert, this.myStepSize()); this._realX = $gameMap.fractionXWithDirection(this._x, this.reverseDir(horz), this.myStepSize()); this._realY = $gameMap.fractionYWithDirection(this._y, this.reverseDir(vert), this.myStepSize()); this.increaseSteps(); } if (this._direction === this.reverseDir(horz)) { this.setDirection(horz); } if (this._direction === this.reverseDir(vert)) { this.setDirection(vert); } }; }; addOrangeMovementToCharacter(Game_Player); addOrangeMovementToCharacter(Game_Follower); addOrangeMovementToCharacter(Game_Vehicle); var oldGamePlayer_moveStraight = Game_Player.prototype.moveStraight; var oldGamePlayer_moveDiagonally = Game_Player.prototype.moveDiagonally; Game_Player.prototype.moveStraight = function(d) { if (this.isMovementSucceeded()) { this._followers.updateMove(); } oldGamePlayer_moveStraight.call(this, d); }; Game_Player.prototype.moveDiagonally = function(horz, vert) { if (this.isMovementSucceeded()) { this._followers.updateMove(); } oldGamePlayer_moveDiagonally.call(this, horz, vert); }; Game_Player.prototype.triggerTouchAction = function() { if ($gameTemp.isDestinationValid()) { var direction = this.direction(); var x1 = this.x; var y1 = this.y; var x2 = $gameMap.roundFractionXWithDirection(x1, direction); var y2 = $gameMap.roundFractionYWithDirection(y1, direction); var x3 = $gameMap.roundFractionXWithDirection(x2, direction); var y3 = $gameMap.roundFractionYWithDirection(y2, direction); var destX = $gameTemp.destinationX(); var destY = $gameTemp.destinationY(); if ((x1.floor() === destX || x1.ceil() === destX) && (y1.floor() === destY || y1.ceil() === destY)) { return this.triggerTouchActionD1(x1, y1); } else if ((x2.floor() === destX || x2.ceil() === destX) && (y2.floor() === destY || y2.ceil() === destY)) { return this.triggerTouchActionD2(x2, y2); } else if ((x3.floor() === destX || x3.ceil() === destX) && (y3.floor() === destY || y3.ceil() === destY)) { return this.triggerTouchActionD3(x2, y2); } } return false; }; Game_Player.prototype.forceMoveForward = function() { this.setThrough(true); for (var i = 0; i < $.Param.Tile_Sections; i++) { this.moveForward(); } this.setThrough(false); }; var oldGameActor_basicFloorDamage = Game_Actor.prototype.basicFloorDamage; Game_Actor.prototype.basicFloorDamage = function() { return oldGameActor_basicFloorDamage.call(this) / $.Param.Tile_Sections; }; Game_Map.prototype.isAirshipLandOk = function(x, y) { var first_x = x.floor(); var last_x = x.ceil(); var first_y = y.floor(); var last_y = y.ceil(); for (var newX = first_x; newX <= last_x; newX++) { for (var newY = first_y; newY <= last_y; newY++) { if (!this.checkPassage(newX, newY, 0x800) || !this.checkPassage(newX, newY, 0x0f)) { return false; } } } return true; }; Game_Map.prototype.xWithDirection = function(x, d) { if (Direction.goesLeft(d)) { return x - 1; } else if (Direction.goesRight(d)) { return x + 1; } else { return x; } }; Game_Map.prototype.yWithDirection = function(y, d) { if (Direction.goesDown(d)) { return y + 1; } else if (Direction.goesUp(d)) { return y - 1; } else { return y; } }; Game_Map.prototype.checkLayeredTilesFlags = function(x, y, bit) { var flags = this.tilesetFlags(); for (var newX = x.floor(); newX <= x.ceil(); newX++) { for (var newY = y.floor(); newY <= y.ceil(); newY++) { var result = this.layeredTiles(newX, newY).some(function(tileId) { return (flags[tileId] & bit) !== 0; }); if (result) return result; } } return false; }; // This method adds or subtracts the step_size to an X position, based on the direction Game_Map.prototype.fractionXWithDirection = function(x, d, stepSize) { if (stepSize === undefined) { stepSize = $.Param.Step_Size; } if (Direction.goesLeft(d)) { return x - stepSize; } else if (Direction.goesRight(d)) { return x + stepSize; } else { return x; } }; // This method adds or subtracts the step_size to a Y position, based on the direction Game_Map.prototype.fractionYWithDirection = function(y, d, stepSize) { if (stepSize === undefined) { stepSize = $.Param.Step_Size; } if (Direction.goesDown(d)) { return y + stepSize; } else if (Direction.goesUp(d)) { return y - stepSize; } else { return y; } }; Game_Map.prototype.isValid = function(x, y) { return x >= 0 && x.ceil() < this.width() && y >= 0 && y.ceil() < this.height(); }; // When using horizontally looped maps, this method gets the real X position Game_Map.prototype.roundFractionXWithDirection = function(x, d, stepSize) { return this.roundX(this.fractionXWithDirection(x, d, stepSize)); }; // When using vertically looped maps, this method gets the real Y position Game_Map.prototype.roundFractionYWithDirection = function(y, d, stepSize) { return this.roundY(this.fractionYWithDirection(y, d, stepSize)); }; // Create two methods that can be overriden by add-ons Game_Player.prototype.onBeforeMove = Game_Player.prototype.onBeforeMove || function() {}; Game_Player.prototype.trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement || function(direction) { return false; }; // Replaces the old startMapEvent method to check for events on all tiles touched by the player // Calls the original method inside a loop, unless BlockRepeatedTouchEvents or IgnoreEmptyEvents is true var oldGamePlayer_startMapEvent = Game_Player.prototype.startMapEvent; Game_Player.prototype.startMapEvent = function(x, y, triggers, normal) { if ($gameMap.isEventRunning()) { return; } this.runForAllPositions(x, y, function(block_x, block_y) { // unless it is configured to run all available events, quit the loop if there's an event running if (!$.Param.TriggerAllAvailableEvents) { if ($gameMap.isEventRunning()) { return; } } if ($.Param.BlockRepeatedTouchEvents === true || $.Param.IgnoreEmptyEvents === true) { this.doActualStartMapEvent(block_x, block_y, triggers, normal); } else { oldGamePlayer_startMapEvent.call(this, block_x, block_y, triggers, normal); } }); }; // New method, replaces the original startMapEvent code when BlockRepeatedTouchEvents or IgnoreEmptyEvents is true Game_Player.prototype.doActualStartMapEvent = function(x, y, triggers, normal) { if ($.isTileChecked(x, y)) { return; } $gameMap.eventsXy(x, y).forEach(function(event) { if (!event._erased) { if (event.isTriggerIn(triggers) && event.isNormalPriority() === normal && event.hasAnythingToRun()) { if ($.Param.BlockRepeatedTouchEvents === true && event.isTriggerIn([1, 2])) { $.markTileAsChecked(event.x, event.y); } event.start(); } } }); }; Game_Event.prototype.hasAnythingToRun = function() { if ($.Param.IgnoreEmptyEvents !== true) { return true; } for (var idx in this.list()) { var command = this.list()[idx]; // Comments if (command.code == 108 || command.code == 408) { continue; } // Label if (command.code == 118) { continue; } // End of List if (Number(command.code) === 0) { continue; } return true; } return false; }; $.isTileChecked = function(x, y) { return $._checkedTiles.some(function(tile) { if (tile.x != x) { return false; } if (tile.y != y) { return false; } return true; }); }; $.markTileAsChecked = function(x, y) { $._checkedTiles.push({ x: x, y: y }); }; $.clearCheckedTiles = function() { var newList = []; $._checkedTiles.forEach(function(tile) { if ($gamePlayer.isTouchingTile(tile.x, tile.y)) { newList.push(tile); } }); $._checkedTiles = newList; }; // Small trick used so the game doesn't abuse of the pathfinding script Game_Player.prototype.determineDirectionToDestination = function() { var x = $gameTemp.destinationX(); var y = $gameTemp.destinationY(); if ($.Param.DisablePixelMovementForMouseRoutes !== false) { var horzDirection = undefined; var vertDirection = undefined; if (this._x.floor() < this._x) { if (this.direction() == Direction.LEFT || this.direction() == Direction.RIGHT) { horzDirection = this.direction(); } else { if (this._x.floor() - x >= 1) { horzDirection = Direction.LEFT; } else if (x - this._x.floor() >= 1) { horzDirection = Direction.RIGHT; } } } if (this._y.floor() < this._y) { if (this.direction() == Direction.UP || this.direction() == Direction.DOWN) { vertDirection = this.direction(); } else { if (this._y.floor() - y >= 1) { vertDirection = Direction.UP; } else if (y - this._y.floor() >= 1) { vertDirection = Direction.DOWN; } } } if (horzDirection !== undefined && vertDirection !== undefined) { return Direction.joinDirections(horzDirection, vertDirection); } if (horzDirection !== undefined) { return horzDirection; } if (vertDirection !== undefined) { return vertDirection; } } return this.findDirectionTo(x, y); }; if ($.Param.CustomPathfinding !== false) { Game_Character.prototype.getDirectionNode = function(start, goalX, goalY) { var searchLimit = this.searchLimit(); var mapWidth = $gameMap.width(); var nodeList = []; var openList = []; var closedList = []; var best = start; if (this.x === goalX && this.y === goalY) { return undefined; } nodeList.push(start); openList.push(start.y * mapWidth + start.x); while (nodeList.length > 0) { var bestIndex = 0; for (var i = 0; i < nodeList.length; i++) { if (nodeList[i].f < nodeList[bestIndex].f) { bestIndex = i; } } var current = nodeList[bestIndex]; var x1 = current.x; var y1 = current.y; var pos1 = y1 * mapWidth + x1; var g1 = current.g; nodeList.splice(bestIndex, 1); openList.splice(openList.indexOf(pos1), 1); closedList.push(pos1); if (current.x === goalX && current.y === goalY) { best = current; // goaled = true; break; } if (g1 >= searchLimit) { continue; } // var allDirections = []; // if ($.Param.DiagonalPathfinding !== false) { // allDirections.push(Direction.DOWN_LEFT); // allDirections.push(Direction.DOWN_RIGHT); // allDirections.push(Direction.UP_LEFT); // allDirections.push(Direction.UP_RIGHT); // } // allDirections.push(Direction.LEFT); // allDirections.push(Direction.RIGHT); // allDirections.push(Direction.DOWN); // allDirections.push(Direction.UP); // allDirections.forEach(function(direction){ for (var j = 0; j < 4; j++) { var direction = 2 + j * 2; var x2, y2; if ($.Param.DisablePixelMovementForMouseRoutes !== false) { x2 = $gameMap.roundXWithDirection(x1, direction); y2 = $gameMap.roundYWithDirection(y1, direction); } else { x2 = this.roundXWithDirection(x1, direction); y2 = this.roundYWithDirection(y1, direction); } var pos2 = y2 * mapWidth + x2; if (closedList.contains(pos2)) { // return; continue; } if (x1.floor() == goalX && y1.floor() == goalY) { break; } if (!this.canPass(x1, y1, direction)) { // return; continue; } var g2 = g1; if ($.Param.DisablePixelMovementForMouseRoutes !== false) { g2 += 1; } else { g2 += 1 / $.Param.Tile_Sections; } var index2 = openList.indexOf(pos2); if (index2 < 0 || g2 < nodeList[index2].g) { var neighbor; if (index2 >= 0) { neighbor = nodeList[index2]; } else { neighbor = {}; nodeList.push(neighbor); openList.push(pos2); } neighbor.parent = current; neighbor.x = x2; neighbor.y = y2; neighbor.g = g2; neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY); if (!best || neighbor.f - neighbor.g < best.f - best.g) { best = neighbor; } } }//.bind(this)); } return best; }; Game_Character.prototype.clearCachedNode = function() { this.setCachedNode(); }; Game_Character.prototype.setCachedNode = function(node, goalX, goalY) { this._cachedNode = node; this._cachedGoalX = goalX; this._cachedGoalY = goalY; }; Game_Character.prototype.findDirectionTo = function(goalX, goalY) { if (this.x === goalX && this.y === goalY) { return 0; } if (this._cachedGoalX !== goalX || this._cachedGoalY !== goalY) { this.clearCachedNode(); } var node = this._cachedNode; var start = {}; start.parent = null; start.x = this.x; start.y = this.y; start.g = 0; start.f = $gameMap.distance(start.x, start.y, goalX, goalY); var canRetry = true; if (node === undefined) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } canRetry = false; } if (node.x !== start.x || node.y !== start.y) { while (node.parent && (node.parent.x !== start.x || node.parent.y !== start.y)) { node = node.parent; } if (!node.parent) { // console.log('missing parent. Retrying'); this.clearCachedNode(); if (canRetry) { node = this.getDirectionNode(start, goalX, goalY); this.setCachedNode(node, goalX, goalY); if (node === undefined) { return 0; } } } } var deltaX1 = $gameMap.deltaX(node.x, start.x); var deltaY1 = $gameMap.deltaY(node.y, start.y); if ($.Param.DiagonalPathfinding !== false) { if (deltaY1 > 0 && deltaX1 > 0) { return Direction.DOWN_RIGHT; } else if (deltaY1 > 0 && deltaX1 < 0) { return Direction.DOWN_LEFT; } else if (deltaY1 < 0 && deltaX1 < 0) { return Direction.UP_LEFT; } else if (deltaY1 < 0 && deltaX1 > 0) { return Direction.UP_RIGHT; } } if (deltaY1 > 0) { return 2; } else if (deltaX1 < 0) { return 4; } else if (deltaX1 > 0) { return 6; } else if (deltaY1 < 0) { return 8; } var deltaX2 = this.deltaXFrom(goalX); var deltaY2 = this.deltaYFrom(goalY); var direction = 0; if (Math.abs(deltaX2) > Math.abs(deltaY2)) { direction = deltaX2 > 0 ? 4 : 6; } else if (deltaY2 !== 0) { direction = deltaY2 > 0 ? 8 : 2; } if (direction > 0) { if (!this.canPass(this._x, this._y, direction)) { this.clearCachedNode(); direction = 0; } } return direction; }; } // If the player is holding two direction buttons, Input.dir4 will give you one of them and this method will give you the other one Game_Player.prototype.getAlternativeDirection = function(direction, diagonal_d) { if (direction != diagonal_d) { switch (diagonal_d) { case Direction.UP_LEFT: return direction == Direction.UP ? Direction.LEFT : Direction.UP; case Direction.UP_RIGHT: return direction == Direction.UP ? Direction.RIGHT : Direction.UP; case Direction.DOWN_LEFT: return direction == Direction.DOWN ? Direction.LEFT : Direction.DOWN; case Direction.DOWN_RIGHT: return direction == Direction.DOWN ? Direction.RIGHT : Direction.DOWN; default: break; } } return direction; }; // Replaces the moveByInput method to add all of the plugins functionality Game_Player.prototype.moveByInput = function() { if (this.isMoving() || !this.canMove()) { return; } var button = 'down'; var direction = Input.dir4; var diagonal_d = Input.dir8; var alternative_d = direction; // If there's a directional button pressed, clear the mouse destination if (direction > 0) { $gameTemp.clearDestination(); } // If there's a valid mouse destination, pick the direction from it else if ($gameTemp.isDestinationValid()) { direction = this.determineDirectionToDestination(); diagonal_d = direction; } // If the player is pressing two direction buttons and the direction picked by dir4 is unavailable, try the other non-diagonal direction alternative_d = this.getAlternativeDirection(direction, diagonal_d); button = Direction.getButtonName(direction, button); $.clearCheckedTiles(); if (direction === 0) { return; } if (this.canPass(this._x, this._y, direction) || (direction != alternative_d && this.canPass(this._x, this._y, alternative_d))) { this.onBeforeMove(); // If diagonal movement is active, try it first if ($.Param.Diagonal_Movement) { this.executeMove(diagonal_d); if (this.isMovementSucceeded()) { return; } } this.executeMove(direction); if (!this.isMovementSucceeded()) { this.executeMove(alternative_d); } } else { // If the movement failed, call this method to let add-ons try too if (this.trySavingFailedMovement(direction)) { return; } if (this._direction != direction) { this.setDirection(direction); this.checkEventTriggerTouchFront(); } } }; Game_Player.prototype.executeMove = function(direction) { switch (direction) { case Direction.UP: case Direction.DOWN: case Direction.LEFT: case Direction.RIGHT: this.moveStraight(direction); break; case Direction.UP_LEFT: this.moveDiagonally(Direction.LEFT, Direction.UP); break; case Direction.UP_RIGHT: this.moveDiagonally(Direction.RIGHT, Direction.UP); break; case Direction.DOWN_LEFT: this.moveDiagonally(Direction.LEFT, Direction.DOWN); break; case Direction.DOWN_RIGHT: this.moveDiagonally(Direction.RIGHT, Direction.DOWN); break; default: break; } }; // alias the updateNonmoving method from the Game_Player class to check // if there's any event to trigger var oldGamePlayer_updateNonmoving = Game_Player.prototype.updateNonmoving; Game_Player.prototype.updateNonmoving = function(wasMoving) { oldGamePlayer_updateNonmoving.call(this, wasMoving); // If the player was moving or it's pressing an arrow key if (wasMoving || Input.dir4 !== 0) { // Doesn't trigger anything if there's already something running if (!$gameMap.isEventRunning()) { this.checkEventTriggerThere([1, 2]); // Setups the starting event if there's any. if ($gameMap.setupStartingEvent()) { return; } } } }; // Replaces checkEventTriggerThere to work with pixel movement Game_Player.prototype.checkEventTriggerThere = function(triggers) { if (this.canStartLocalEvents()) { var direction = this.direction(); var x1 = this._x; var y1 = this._y; var x2 = $gameMap.roundFractionXWithDirection(x1, direction); var y2 = $gameMap.roundFractionYWithDirection(y1, direction); this.startMapEvent(x2, y2, triggers, true); if (!$gameMap.isAnyEventStarting() && $gameMap.isCounter(x2, y2)) { var x3 = $gameMap.roundFractionXWithDirection(x2, direction); var y3 = $gameMap.roundFractionYWithDirection(y2, direction); this.startMapEvent(x3, y3, triggers, true); } } }; // ------------------------------------------------ // With Great Movement, comes Great Responsibility // ------------------------------------------------ // Changes the logic used to turn towards the player, because the old one didn't work well with pixel movement Game_Character.prototype.turnTowardPlayer = function() { var sx = this.deltaXFrom($gamePlayer.floatX); var sy = this.deltaYFrom($gamePlayer.floatY); if (sx.abs() < 1 && sy.abs() < 1) { this.setDirection(10 - $gamePlayer.direction); } else { if (sx.abs() > sy.abs()) { this.setDirection(sx > 0 ? 4 : 6); } else if (sy !== 0) { this.setDirection(sy > 0 ? 8 : 2); } } }; // Changes the logic used to turn away from the player, because the old one didn't work well with pixel movement Game_Character.prototype.turnAwayFromPlayer = function() { var sx = this.deltaXFrom($gamePlayer.floatX); var sy = this.deltaYFrom($gamePlayer.floatY); if (sx.abs() < 1 && sy.abs() < 1) { this.setDirection($gamePlayer.direction); } else { if (sx.abs() > sy.abs()) { this.setDirection(sx > 0 ? 7 : 4); } else if (sy !== 0) { this.setDirection(sy > 0 ? 2 : 8); } } }; // Changes the logic used to chase characters, because the old one didn't work well with pixel movement // Also adds the FollowersDistance param. Game_Follower.prototype.chaseCharacter = function(character) { if (!this.isMoving()) { var ideal_x = character.floatX; var ideal_y = character.floatY; switch (character.direction()) { case Direction.DOWN: ideal_y -= $.Param.FollowersDistance; break; case Direction.LEFT: ideal_x += $.Param.FollowersDistance; break; case Direction.RIGHT: ideal_x -= $.Param.FollowersDistance; break; case Direction.UP: ideal_y += $.Param.FollowersDistance; break; default: break; } var sx = this.deltaXFrom(ideal_x); var sy = this.deltaYFrom(ideal_y); if (sx.abs() >= $.Param.Step_Size && sy.abs() >= $.Param.Step_Size) { this.moveDiagonally(sx > 0 ? Direction.LEFT : Direction.RIGHT, sy > 0 ? Direction.UP : Direction.DOWN); } else if (sx.abs() >= $.Param.Step_Size) { this.moveStraight(sx > 0 ? Direction.LEFT : Direction.RIGHT); } else if (sy.abs() >= $.Param.Step_Size) { this.moveStraight(sy > 0 ? Direction.UP : Direction.DOWN); } this.setMoveSpeed($gamePlayer.realMoveSpeed()); } }; if ($.Param.BlockRepeatedTouchEvents === true) { // Overrides command201 to pick the tile where the player was teleported to and add it to the list of tiles that shouldn't trigger events until the player leaves it. var oldGameInterpreter_command201 = Game_Interpreter.prototype.command201; Game_Interpreter.prototype.command201 = function() { oldGameInterpreter_command201.call(this); if ($gameParty.inBattle()) { return; } $.clearCheckedTiles(); if (!$.Param.TriggerTouchEventsAfterTeleport) { $.markTileAsChecked($gamePlayer.x, $gamePlayer.y); } }; } })(SuperOrangeMovement); Imported.SuperOrangeMovement = 1.5;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Auto Avoid Obstacles Diagonally * By Hudell - www.hudell.com * OrangeAutoAvoidObstaclesDiagonally.js * Version: 1.0.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc Makes the player automatically Avoid small obstacles, by diagonally * * @param AvoidEvents * @desc Set this to false if you don't want the player to avoid events. * @default true * * @param OnlyWhenDashing * @desc Set this to true to only avoid obstacles when the player is dashing. * @default false * * @param DashingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when dashing. Set this to a number of frames. * @default 0 * * @param WalkingDelay * @desc Makes the character wait a little before trying to avoid an obstacle when walking. Set this to a number of frames. * @default 0 * * @author Hudell * * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/auto-avoid-diagonal * *=============================================================================*/ var Imported = Imported || {}; if (Imported['MVCommons'] === undefined) { console.log('Download MVCommons: http://link.hudell.com/mvcommons'); throw new Error("This library needs MVCommons to work properly!"); } if (Imported['SuperOrangeMovement'] === undefined) { console.log('Download SuperOrangeMovement: http://link.hudell.com/super-orange-movement'); throw new Error("This library needs SuperOrangeMovement to work properly!"); } var OrangeAutoAvoidObstaclesDiagonally = OrangeAutoAvoidObstaclesDiagonally || {}; (function($) { "use strict"; $.Parameters = PluginManager.parameters('OrangeAutoAvoidObstaclesDiagonally'); $.Param = $.Param || {}; $.Param.AvoidEvents = $.Param["AvoidEvents"] !== "false"; $.Param.OnlyWhenDashing = $.Param["OnlyWhenDashing"] === "true"; $.Param.DashingDelay = Number($.Param["DashingDelay"] || 0); $.Param.WalkingDelay = Number($.Param["WalkingDelay"] || 0); var avoidObstaclesDelay = 0; // Every time the player succesfully moves, reset the delay var oldGamePlayer_onBeforeMove = Game_Player.prototype.onBeforeMove; Game_Player.prototype.onBeforeMove = function() { if (this.isDashing()) { avoidObstaclesDelay = $.Param.DashingDelay; } else { avoidObstaclesDelay = $.Param.WalkingDelay; } if (oldGamePlayer_onBeforeMove !== undefined) { oldGamePlayer_onBeforeMove.call(this); } }; var oldGamePlayer_trySavingFailedMovement = Game_Player.prototype.trySavingFailedMovement; Game_Player.prototype.trySavingFailedMovement = function(direction) { if (oldGamePlayer_trySavingFailedMovement !== undefined) { if (oldGamePlayer_trySavingFailedMovement.call(this, direction)) { return true; } } if (avoidObstaclesDelay > 0) { avoidObstaclesDelay--; } if ($.Param.OnlyWhenDashing === true) { if (!this.isDashing()) { return false; } } if ($.Param.AvoidEvents !== true) { if (this.isTilesetPassable(this._x, this._y, direction)) { var x2 = $gameMap.roundFractionXWithDirection(this._x, direction, this.myStepSize()); var y2 = $gameMap.roundFractionYWithDirection(this._y, direction, this.myStepSize()); if (this.isCollidedWithCharacters(x2, y2)) { return false; } } } if (this.tryToAvoidDigonally(direction)) { return true; } return false; }; Game_Player.prototype.tryToAvoidDiagonally = function(direction) { if (avoidObstaclesDelay > 0) { return false; } if (direction == Direction.LEFT || direction == Direction.RIGHT) { if (this.canPassDiagonally(this._x, this._y, direction, Direction.DOWN)) { this.executeMove(direction - 3); return true; } else if (this.canPassDiagonally(this._x, this._y, direction, Direction.UP)) { this.executeMove(direction + 3); return true; } } else if (direction == Direction.UP || direction == Direction.DOWN) { if (this.canPassDiagonally(this._x, this._y, Direction.LEFT, direction)) { this.executeMove(direction - 1); return true; } else if (this.canPassDiagonally(this._x, this._y, Direction.RIGHT, direction)) { this.executeMove(direction + 1); return true; } } return false; }; })(OrangeAutoAvoidObstaclesDiagonally); PluginManager.register("OrangeAutoAvoidObstaclesDiagonally", "1.0.1", "Will make the player avoid small obstacles automatically by walking diagonally around them", { email: "[email protected]", name: "Hudell", website: "http://www.hudell.com" }, "2015-10-21");
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Custom Event Creator * By Hudell - www.hudell.com * OrangeCustomEventCreator.js * Version: 1.2.1 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin Will let you create virtual events with script calls * * @author Hudell * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://link.hudell.com/custom-event-creator * *=============================================================================*/ var Imported = Imported || {}; if (Imported.MVCommons === undefined) { var MVC = MVC || {}; (function($){ $.defaultGetter = function(name) { return function () { return this['_' + name]; }; }; $.defaultSetter = function(name) { return function (value) { var prop = '_' + name; if ((!this[prop]) || this[prop] !== value) { this[prop] = value; if (this._refresh) { this._refresh(); } } }; }; $.accessor = function(value, name /* , setter, getter */) { Object.defineProperty(value, name, { get: arguments.length > 3 ? arguments[3] : $.defaultGetter(name), set: arguments.length > 2 ? arguments[2] : $.defaultSetter(name), configurable: true });}; $.reader = function(obj, name /*, getter */) { Object.defineProperty(obj, name, { get: arguments.length > 2 ? arguments[2] : defaultGetter(name), configurable: true }); }; })(MVC); } if (Imported.OrangeCustomEvents === undefined) { console.log('Download OrangeCustomEvents: http://link.hudell.com/custom-events'); throw new Error("This library needs OrangeCustomEvents to work!"); } var OrangeCustomEventCreator = OrangeCustomEventCreator || {}; function CustomEventData() { this.initialize.apply(this, arguments); } function CustomEventData_Page() { this.initialize.apply(this, arguments); } function CustomEventData_Page_Image() { this.initialize.apply(this, arguments); } function CustomEventData_Page_Condition() { this.initialize.apply(this, arguments); } function CustomEventData_Page_MoveRoute() { this.initialize.apply(this, arguments); } var EventTriggers = { ACTION_BUTTON: 0, PLAYER_TOUCH: 1, EVENT_TOUCH: 2, AUTORUN: 3, PARALLEL: 4 }; var EventPriorities = { UNDER_PLAYER: 0, NORMAL: 1, OVER_PLAYER: 2 }; (function($) { "use strict"; //----------------------------------------------. //----------------------------------------------| // CUSTOM CLASSES | //----------------------------------------------| //----------------------------------------------| //---------------------------------------------- // CustomEventData //---------------------------------------------- (function(prot) { MVC.accessor(prot, 'pages'); MVC.accessor(prot, 'id'); MVC.accessor(prot, 'name'); MVC.accessor(prot, 'note'); MVC.accessor(prot, 'x'); MVC.accessor(prot, 'y'); MVC.reader(prot, 'page', function() { return this.pages[this._pageIndex]; }); prot.initialize = function(id) { this.id = id; this.x = 0; this.y = 0; this.name = "Custom Event"; this.pages = [new CustomEventData_Page()]; this._pageIndex = 0; }; prot.addPage = function(page) { this.pages.push(page); return this.pages[this.pages.length - 1]; }; prot.changePage = function(pageIndex) { this._pageIndex = pageIndex; while (this.pages.length < pageIndex) { this.pages.push(new CustomEventData_Page()); } }; prot.addCommand = function(command) { this.page.addCommand(command); }; prot.endPage = function() { this.page.end(); }; prot.endAllPages = function() { for (var i = 0; i < this.pages.length; i++) { this.pages[i].end(); } }; })(CustomEventData.prototype); //---------------------------------------------- // CustomEventData_Page //---------------------------------------------- (function(prot) { MVC.accessor(prot, 'conditions'); MVC.accessor(prot, 'directionFix'); MVC.accessor(prot, 'image'); MVC.accessor(prot, 'list'); MVC.accessor(prot, 'moveFrequency'); MVC.accessor(prot, 'moveRoute'); MVC.accessor(prot, 'moveSpeed'); MVC.accessor(prot, 'moveType'); MVC.accessor(prot, 'priorityType'); MVC.accessor(prot, 'stepAnime'); MVC.accessor(prot, 'through'); MVC.accessor(prot, 'trigger'); MVC.accessor(prot, 'walkAnime'); prot.initialize = function() { this.conditions = new CustomEventData_Page_Condition(); this.directionFix = false; this.image = new CustomEventData_Page_Image(); this.list = [{ code: 0, indent: 0, parameters: [] }]; this.moveFrequency = 3; this.moveRoute = new CustomEventData_Page_MoveRoute(); this.moveSpeed = 3; this.moveType = 0; this.priorityType = 1; this.stepAnime = true; this.through = false; this.trigger = 0; this.walkAnime = true; this._indent = -1; }; prot.addCommand = function(command) { if (command instanceof Array) { for (var i = 0; i < command.length; i++) { this.addCommand(command[i]); } } else { // When you add a command on the page for the first time, the script will remove the auto-added "end" command. Make sure to add your own or call .end(). if (this.list.length == 1 && this.list[0].code === 0) { this.list = []; this._indent = 0; } command.indent = this._indent; this.list.push(command); if (command.code === 0) { this._indent -= 1; } } }; prot.increaseIndent = function() { this._indent += 1; }; prot.end = function() { while (this._indent >= 0) { this.addCommand({ code: 0 }); } }; prot.callScriptOrCommonEvent = function(scriptOrCommonEventId) { var commandCode = undefined; if (scriptOrCommonEventId !== undefined) { if (typeof(scriptOrCommonEventId) == "number") { commandCode = 117; } else if (typeof(scriptOrCommonEventId) == "string") { commandCode = 355; } } if (commandCode !== undefined) { this.addCommand({ code: commandCode, parameters: [scriptOrCommonEventId] }); } }; })(CustomEventData_Page.prototype); //---------------------------------------------- // CustomEventData_Page_Image //---------------------------------------------- (function(prot) { MVC.accessor(prot, 'characterIndex'); MVC.accessor(prot, 'characterName'); MVC.accessor(prot, 'direction'); MVC.accessor(prot, 'pattern'); MVC.accessor(prot, 'tileId'); prot.initialize = function() { this.characterIndex = 0; this.characterName = ''; this.direction = 2; this.pattern = 1; this.tileId = 0; }; })(CustomEventData_Page_Image.prototype); //---------------------------------------------- // CustomEventData_Page_Condition //---------------------------------------------- (function(prot) { MVC.accessor(prot, 'actorId'); MVC.accessor(prot, 'actorValid'); MVC.accessor(prot, 'itemId'); MVC.accessor(prot, 'itemValid'); MVC.accessor(prot, 'selfSwitchCh'); MVC.accessor(prot, 'selfSwitchValid'); MVC.accessor(prot, 'switch1Id'); MVC.accessor(prot, 'switch1Valid'); MVC.accessor(prot, 'switch2Id'); MVC.accessor(prot, 'switch2Valid'); MVC.accessor(prot, 'variableId'); MVC.accessor(prot, 'variableValid'); MVC.accessor(prot, 'variableValue'); prot.initialize = function() { this.actorId = 1; this.actorValid = false; this.itemId = 1; this.itemValid = false; this.selfSwitchCh = 'A'; this.selfSwitchValid = false; this.switch1Id = 1; this.switch1Valid = false; this.switch2Id = 1; this.switch2Valid = false; this.variableId = 1; this.variableValid = false; this.variableValue = 0; }; prot.clearConditions = function() { this.actorValid = false; this.itemValid = false; this.selfSwitchValid = false; this.switch1Valid = false; this.switch2Valid = false; this.variableValid = false; }; prot.addActorCondition = function(actorId) { this.actorId = actorId; this.actorValid = true; }; prot.addItemCondition = function(itemId) { this.itemId = itemId; this.itemValid = true; }; prot.addSelfSwitchCondition = function(selfSwitchCh) { this.selfSwitchCh = selfSwitchCh; this.selfSwitchValid = true; }; prot.addSwitch1Condition = function(switchId) { this.switch1Id = switchId; this.switch1Valid = true; }; prot.addSwitch2Condition = function(switchId) { this.switch2Id = switchId; this.switch2Valid = true; }; prot.addVariableCondition = function(variableId, value) { this.variableId = variableId; this.variableValue = value; this.variableValid = true; }; })(CustomEventData_Page_Condition.prototype); //---------------------------------------------- // CustomEventData_MoveRoute //---------------------------------------------- (function(prot) { MVC.accessor(prot, 'repeat'); MVC.accessor(prot, 'skippable'); MVC.accessor(prot, 'wait'); MVC.accessor(prot, 'list'); prot.initialize = function() { this.repeat = true; this.skippable = false; this.wait = false; this.list = [{ code: 0, parameters: [] }]; }; })(CustomEventData_Page_MoveRoute.prototype); //----------------------------------------------. //----------------------------------------------| // PRIVATE METHODS | //----------------------------------------------| //----------------------------------------------| function createActorAt(actorId, x, y, d, scriptOrCommonEventId, temporary) { return this.createNormalEventAt($gameActors.actor(actorId).characterName(), $gameActors.actor(actorId).characterIndex(), x, y, d, scriptOrCommonEventId, temporary); } function createNormalEventAt(characterName, characterIndex, x, y, d, scriptOrCommonEventId, temporary) { var eventData = new CustomEventData(); eventData.page.image.direction = d; eventData.page.image.characterName = characterName; eventData.page.image.characterIndex = characterIndex; eventData.page.callScriptOrCommonEvent(scriptOrCommonEventId); return $gameMap.addEventAt(eventData, x, y, temporary); } function createTriggerEventAt(x, y, scriptOrCommonEventId, temporary) { var eventData = new CustomEventData(); eventData.page.trigger = EventTriggers.PLAYER_TOUCH; eventData.page.priorityType = EventPriorities.UNDER_PLAYER; eventData.page.callScriptOrCommonEvent(scriptOrCommonEventId); return $gameMap.addEventAt(eventData, x, y, temporary); } function createTeleportEventAt(x, y, newMapId, newX, newY, newDirection, fadeType, temporary) { var eventData = new CustomEventData(); eventData.page.trigger = EventTriggers.PLAYER_TOUCH; eventData.page.priorityType = EventPriorities.UNDER_PLAYER; if (newDirection === undefined) { newDirection = $gamePlayer.direction(); } if (fadeType === undefined) { fadeType = 0; } eventData.page.addCommand({ code: 201, parameters: [0, newMapId, newX, newY, newDirection, fadeType] }); return $gameMap.addEventAt(eventData, x, y, temporary); } function createParallelProcess(scriptOrCommonEventId, temporary, autoErase) { var eventData = new CustomEventData(); eventData.page.trigger = EventTriggers.PARALLEL; eventData.page.priorityType = EventPriorities.UNDER_PLAYER; eventData.page.callScriptOrCommonEvent(scriptOrCommonEventId); if (autoErase === true) { eventData.page.addCommand({ code: 214 }); } return $gameMap.addEventAt(eventData, temporary); } //----------------------------------------------. //----------------------------------------------| // PUBLIC METHODS | //----------------------------------------------| //----------------------------------------------| var oldGameMap_addEvent = Game_Map.prototype.addEvent; Game_Map.prototype.addEvent = function(eventData, temporary, index) { // Makes sure that all pages have all the "end" commands they need if (eventData instanceof CustomEventData) { eventData.endAllPages(); } return oldGameMap_addEvent.call(this, eventData, temporary, index); }; //----------------------------------------------. //----------------------------------------------| // EXPORT SECTION | //----------------------------------------------| //----------------------------------------------| Game_Map.prototype.createActorAt = createActorAt; $.createActorAt = createActorAt; Game_Map.prototype.createNormalEventAt = createNormalEventAt; $.createNormalEventAt = createNormalEventAt; Game_Map.prototype.createTriggerEventAt = createTriggerEventAt; $.createTriggerEventAt = createTriggerEventAt; Game_Map.prototype.createTeleportEventAt = createTeleportEventAt; $.createTeleportEventAt = createTeleportEventAt; Game_Map.prototype.createParallelProcess = createParallelProcess; $.createParallelProcess = createParallelProcess; })(OrangeCustomEventCreator); Imported.OrangeCustomEventCreator = 1.2;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
/*============================================================================= * Orange - Custom Event * By Hudell - www.hudell.com * OrangeCustomEvents.js * Version: 1.9 * Free for commercial and non commercial use. *=============================================================================*/ /*: * @plugindesc This plugin Will let you add or copy events to the current map * * @author Hudell * @help * ============================================================================ * Latest Version * ============================================================================ * * Get the latest version of this script on * http://download.hudell.com/OrangeCustomEvents.js * *=============================================================================*/ var Imported = Imported || {}; if (Imported.MVCommons === undefined) { var MVCommons = {}; (function($){ $.ajaxLoadFileAsync = function(filePath, mimeType, onLoad, onError){ mimeType = mimeType || "application/json"; var xhr = new XMLHttpRequest(); var name = '$' + filePath.replace(/^.*(\\|\/|\:)/, '').replace(/\..*/, ''); xhr.open('GET', filePath); if (mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(mimeType); } if(onLoad === undefined){ onLoad = function(xhr, filePath, name) { if (xhr.status < 400) { window[name] = JSON.parse(xhr.responseText); DataManager.onLoad(window[name]); } }; } if(onError === undefined) { onError = function() { DataManager._errorUrl = DataManager._errorUrl || filePath; }; } xhr.onload = function() { onLoad.call(this, xhr, filePath, name); }; xhr.onerror = onError; window[name] = null; xhr.send(); }; })(MVCommons); } var OrangeCustomEvents = OrangeCustomEvents || {}; function Game_Custom_Event() { this.initialize.apply(this, arguments); } Game_Custom_Event.prototype = Object.create(Game_Event.prototype); Game_Custom_Event.prototype.constructor = Game_Custom_Event; (function($) { "use strict"; //----------------------------------------------. //----------------------------------------------| // PROTECTED METHODS | //----------------------------------------------| //----------------------------------------------| $.getAnotherMapData = function(mapId, callback) { var variableName = '$Map%1'.format(mapId.padZero(3)); var filename = 'data/Map%1.json'.format(mapId.padZero(3)); var onLoad = function(xhr, filePath, name) { if (xhr.status < 400) { window[name] = JSON.parse(xhr.responseText); DataManager.onLoad(window[name]); callback(); } }; if (window[variableName] === undefined || window[variableName] === null) { MVCommons.ajaxLoadFileAsync(filename, undefined, onLoad); } else { callback(); } }; //----------------------------------------------. //----------------------------------------------| // PUBLIC METHODS | //----------------------------------------------| //----------------------------------------------| //---------------------------------------------- // Game_Custom_Event //---------------------------------------------- Game_Custom_Event.prototype.initialize = function(mapId, eventId, eventData) { this._eventData = eventData; Game_Event.prototype.initialize.call(this, mapId, eventId); }; Game_Custom_Event.prototype.event = function() { return this._eventData; }; Game_Custom_Event.prototype.revive = function(data) { return new Game_Custom_Event(data.mapId, data.id, data.eventData); }; //---------------------------------------------- // Game_System //---------------------------------------------- Game_System.prototype.clearSelfSwitches = function(mapId, eventId) { var switches = ["A", "B", "C", "D"]; switches.forEach(function(switchId) { var key = [mapId, eventId, switchId]; $gameSelfSwitches.setValue(key, false); }); }; Game_System.prototype.initCustomEvents = function(mapId) { if (this._customEvents === undefined) { this._customEvents = {}; } if (this._customEvents[mapId] === undefined) { this._customEvents[mapId] = {}; } }; Game_System.prototype.addCustomEvent = function(mapId, event) { this.initCustomEvents(mapId); this.clearSelfSwitches(mapId, event.id); this._customEvents[mapId][event.id] = event; return event; }; Game_System.prototype.removeCustomEvent = function(mapId, eventId) { this.initCustomEvents(mapId); this.clearSelfSwitches(mapId, eventId); delete this._customEvents[mapId][eventId]; }; Game_System.prototype.clearCustomEvents = function(mapId) { this.initCustomEvents(); this._customEvents[mapId] = {}; }; Game_System.prototype.getCustomEvents = function(mapId) { this.initCustomEvents(); return this._customEvents[mapId]; }; //---------------------------------------------- // Game_Map //---------------------------------------------- Game_Map.prototype.getIndexForNewEvent = function() { var index = 1; while (index < this._events.length && !!this._events[index]) { index++; } return index; }; Game_Map.prototype.addEvent = function(eventData, temporary, index) { if (temporary === undefined) { temporary = false; } if (index === undefined) { index = this.getIndexForNewEvent(); } eventData.id = index; var gameEvent = new Game_Custom_Event(this._mapId, index, eventData); $gameSystem.clearSelfSwitches(this._mapId, index); this._events[index] = gameEvent; if (SceneManager._scene instanceof Scene_Map) { var sprite = new Sprite_Character(gameEvent); SceneManager._scene._spriteset._characterSprites.push(sprite); SceneManager._scene._spriteset._tilemap.addChild(sprite); } if (temporary === false) { $gameSystem.addCustomEvent(this._mapId, eventData); } return gameEvent; }; var oldGameMap_setupEvents = Game_Map.prototype.setupEvents; Game_Map.prototype.setupEvents = function() { oldGameMap_setupEvents.call(this); var customEvents = $gameSystem.getCustomEvents(this._mapId); for (var eventId in customEvents) { if (customEvents[eventId] === undefined) continue; var newEventId = this.getIndexForNewEvent(); customEvents[eventId].eventId = newEventId; this._events[newEventId] = new Game_Custom_Event(this._mapId, newEventId, customEvents[eventId]); } }; Game_Map.prototype.addEventAt = function(eventData, x, y, temporary, index) { eventData.x = x; eventData.y = y; return this.addEvent(eventData, temporary, index); }; Game_Map.prototype.spawnEvent = function(eventData, tileList, temporary) { for (var i = 0; i < tileList.length; i++) { var newEventData = JsonEx.makeDeepCopy(eventData); newEventData.x = tileList[i].x; newEventData.y = tileList[i].y; this.addEvent(newEventData, temporary); } }; Game_Map.prototype.getEventData = function(eventIdOrigin) { var event = $dataMap.events[eventIdOrigin]; if (event === undefined) return undefined; return JsonEx.makeDeepCopy(event); }; Game_Map.prototype.getEventDataFrom = function(mapIdOrigin, eventIdOrigin, callback) { $.getAnotherMapData(mapIdOrigin, function() { var variableName = '$Map%1'.format(mapIdOrigin.padZero(3)); if (window[variableName] === undefined || window[variableName] === null) return; var event = window[variableName].events[eventIdOrigin]; if (event === undefined) return; var eventData = JsonEx.makeDeepCopy(event); if (eventData.note) { DataManager.extractMetadata(eventData); } callback.call(this, eventData); }); }; Game_Map.prototype.copyEvent = function(eventIdOrigin, x, y, temporary, newIndex) { var eventData = this.getEventData(eventIdOrigin); if (eventData) { $gameMap.addEventAt(eventData, x, y, temporary, newIndex); } }; Game_Map.prototype.getRegionTileList = function(regionId) { var tileList = []; for (var x = 0; x < $gameMap.width(); x++) { for (var y = 0; y < $gameMap.height(); y++) { if ($gameMap.eventsXy(x, y).length === 0) { if ($gameMap.regionId(x, y) == regionId) { tileList.push({x : x, y : y}); } } } } return tileList; }; Game_Map.prototype.getRandomRegionTile = function(regionId) { var tileList = this.getRegionTileList(regionId); if (tileList.length > 0) { var index = Math.randomInt(tileList.length); return tileList[index]; } return undefined; }; Game_Map.prototype.copyEventToRegion = function(eventIdOrigin, regionId, temporary, newIndex) { var tile = this.getRandomRegionTile(regionId); if (tile !== undefined) { this.copyEvent(eventIdOrigin, tile.x, tile.y, temporary, newIndex); } }; Game_Map.prototype.copyEventFrom = function(mapIdOrigin, eventIdOrigin, x, y, temporary, newIndex, callback) { this.getEventDataFrom(mapIdOrigin, eventIdOrigin, function(eventData) { var event = $gameMap.addEventAt(eventData, x, y, temporary, newIndex); if (!!callback) { callback.call(this, event); } }); }; Game_Map.prototype.copyEventFromMapToRegion = function(mapIdOrigin, eventIdOrigin, regionId, temporary, newIndex, callback) { var tile = this.getRandomRegionTile(regionId); if (tile !== undefined) { this.copyEventFrom(mapIdOrigin, eventIdOrigin, tile.x, tile.y, temporary, newIndex, callback); } }; Game_Map.prototype.spawnMapEvent = function(eventIdOrigin, regionId, temporary) { var eventData = this.getEventData(eventIdOrigin); var tileList = this.getRegionTileList(regionId); if (eventData && tileList) { this.spawnEvent(eventData, tileList, temporary); } }; Game_Map.prototype.spawnMapEventFrom = function(mapIdOrigin, eventIdOrigin, regionId, temporary) { var tileList = this.getRegionTileList(regionId); if (tileList.length > 0) { this.getEventDataFrom(mapIdOrigin, eventIdOrigin, function(eventData) { $gameMap.spawnEvent(eventData, tileList, temporary); }); } }; Game_Interpreter.prototype.getNumericValue = function(stringValue) { if (stringValue.substr(0, 1) == '[' && stringValue.substr(-1) == ']') { var variableId = parseInt(stringValue.substr(1, stringValue.length - 2), 10); if (variableId > 0) { return $gameVariables.value(variableId); } return 0; } else { return parseInt(stringValue, 10); } }; Game_Interpreter.prototype.checkCopyCommands = function(command, args) { if (args.length < 2) return; if (command.toUpperCase() !== 'COPY' && command.toUpperCase() !== 'SPAWN') return; if (args[0].toUpperCase() !== "EVENT") return; var eventIdOrigin = this.getNumericValue(args[1]); var mapIdOrigin = $gameMap.mapId(); var isPosition = true; var x = 0; var y = 0; var regionId = 0; var temporary = true; var hasPosition = false; var userIndex; if (eventIdOrigin <= 0) return; var nextIndex = 2; if (args.length >= nextIndex + 3) { if (args[nextIndex].toUpperCase() == 'FROM' && args[nextIndex + 1].toUpperCase() == 'MAP') { mapIdOrigin = this.getNumericValue(args[nextIndex + 2]); nextIndex += 3; } } if (args.length > nextIndex && args[nextIndex].toUpperCase() == 'HERE') { isPosition = true; hasPosition = true; x = this.character(0).x; y = this.character(0).y; nextIndex++; } else if (args.length > nextIndex) { if (args[nextIndex].toUpperCase() !== 'TO' && args[nextIndex].toUpperCase() !== 'ON') { console.error('OrangeCustomEvents', 'Invalid destination', command, args); return; } nextIndex++; if (args.length > nextIndex && args[nextIndex].toUpperCase() == 'REGION') { isPosition = false; nextIndex++; } else if (args.length > nextIndex && args[nextIndex].toUpperCase() == 'POSITION') { isPosition = true; nextIndex++; } } else { console.error('OrangeCustomEvents', 'Incomplete command', command, args); return; } if (isPosition) { if (!hasPosition) { if (args.length > nextIndex && args[nextIndex].toUpperCase() == 'PLAYER') { x = $gamePlayer.x; y = $gamePlayer.y; nextIndex++; } else if (args.length >= nextIndex + 2) { x = this.getNumericValue(args[nextIndex]); y = this.getNumericValue(args[nextIndex + 1]); nextIndex += 2; } else { console.error('OrangeCustomEvents', 'What position?', command, args); } } } else { if (args.length > nextIndex) { regionId = this.getNumericValue(args[nextIndex]); nextIndex++; } else { console.error('OrangeCustomEvents', 'What region?', command, args); } } if (args.length > nextIndex + 2) { if (args[nextIndex].toUpperCase().startsWith('WITH') && args[nextIndex + 1].toUpperCase().startsWith('ID')) { userIndex = this.getNumericValue(args[nextIndex + 2]); nextIndex += 3; } } if (args.length > nextIndex) { if (args[nextIndex].toUpperCase().startsWith('TEMP')) { temporary = true; nextIndex++; } else if (args[nextIndex].toUpperCase() == 'SAVE') { temporary = false; nextIndex++; } } if (isPosition) { if (mapIdOrigin == $gameMap.mapId()) { $gameMap.copyEvent(eventIdOrigin, x, y, temporary, userIndex); } else { $gameMap.copyEventFrom(mapIdOrigin, eventIdOrigin, x, y, temporary, userIndex); } } else { if (command.toUpperCase() === 'COPY') { if (mapIdOrigin == $gameMap.mapId()) { $gameMap.copyEventToRegion(eventIdOrigin, regionId, temporary, userIndex); } else { $gameMap.copyEventFromMapToRegion(mapIdOrigin, eventIdOrigin, regionId, temporary, userIndex); } } else if (command.toUpperCase() === 'SPAWN') { if (mapIdOrigin == $gameMap.mapId()) { $gameMap.spawnMapEvent(eventIdOrigin, regionId, temporary); } else { $gameMap.spawnMapEventFrom(mapIdOrigin, eventIdOrigin, regionId, temporary); } } } }; Game_Interpreter.prototype.checkDeleteCommand = function(command, args) { if (args.length != 2) return; if (command.toUpperCase() !== 'DELETE') return; if (args[0].toUpperCase() !== "THIS") return; if (args[1].toUpperCase() !== "EVENT") return; $gameSystem.removeCustomEvent(this._mapId, this._eventId); this.command214(); }; var oldGameInterpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { oldGameInterpreter_pluginCommand.call(this, command, args); this.checkCopyCommands(command, args); this.checkDeleteCommand(command, args); }; })(OrangeCustomEvents); Imported.OrangeCustomEvents = 1.9;
{ "repo_name": "Hudell/mv-plugins", "stars": "70", "repo_language": "JavaScript", "file_name": "OrangeCustomEvents.js", "mime_type": "text/plain" }
# Awesome Software for Image Coloring [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) A curated list of awesome AI-powered image coloring frameworks, libraries and software. Inspired by `josephmisiti/awesome-machine-learning`. It's a good idea to explore the GitHub topic as well - [Topic "Image colorization"](https://github.com/topics/image-colorization). In comparison to the awesome list `MarkMoHR/Awesome-Image-Colorization` (which focuses on research papers), I focus on practical open-source software. ## Considerations Most of the software runs in `Python`, and requires some kind of an AI frameworks (e.g. `Tensorflow`) - which means you may need a GPU with a configured `CUDA` toolkit to run it in a reasonable time. ## Frameworks and libraries ### :snake: Python #### Tensorflow * [Automatic Image Colorization](https://github.com/Armour/Automatic-Image-Colorization) - Automatic Image Colorization using TensorFlow based on Residual Encoder Network http://tinyclouds.org/colorize/ * [Image Colorization using Convolutional Networks](https://github.com/shekkizh/Colorization.tensorflow) - Image colorization using CNNs in tensorflow. * [Image and video colorizer](https://github.com/PrimozGodec/ImageColorization) - Image and video colorizer is package for automatic image and video colorization. Models are already trained. * [PIC - Probabilistic Image Colorization](https://github.com/ameroyer/PIC) - Probabilistic Image Colorization https://arxiv.org/abs/1705.04258 * [Photo Coloring Using End2end CNN based Model!](https://github.com/AbdelrahmanRadwan/photo-coloring) - A Deep Learning based coloring tool, which can color a black-white or gray picture. #### Tensorflow with GANs * [Image Colorization with Generative Adversarial Networks](https://github.com/ImagingLab/Colorizing-with-GANs) - Grayscale Image Colorization with Generative Adversarial Networks. https://arxiv.org/abs/1803.05400 * [Image-colorization-using-CycleGAN](https://github.com/ArkaJU/Image-Colorization-CycleGAN) - Colorization of grayscale images using CycleGAN in TensorFlow. #### Keras * [Coloring Black and White photos with Neural Networks](https://github.com/emilwallner/Coloring-greyscale-images) - Coloring black and white images with deep learning. * [JadeBlue96](https://github.com/JadeBlue96/Image-Colorization-of-Historical-Paintings) - Recolorizing grayscaled historical paintings and photos with Deep Learning using an Autoencoder CNN. * [Image-Coloring](https://github.com/aman-chauhan/Image-Coloring) - Deep Neural Net for coloring grayscale images using local and global image features * [Image-Colorization](https://github.com/thevarunsharma/Image-Colorization) - Automatic Image Colorization using a Convolutional Network (U-Net) #### Fast.AI * [DeOldify](https://github.com/jantic/DeOldify) - A Deep Learning based project for colorizing and restoring old images. #### Caffee * [Colorful Image Colorization](https://github.com/richzhang/colorization) - Automatic colorization using deep neural networks. "Colorful Image Colorization." In ECCV, 2016. http://richzhang.github.io/colorization/ * [Interactive Deep Colorization](https://github.com/junyanz/interactive-deep-colorization) - Deep learning software for colorizing black and white images with a few clicks. https://richzhang.github.io/ideepcolor/ #### PyTorch * [Interactive Deep Colorization in PyTorch](https://github.com/richzhang/colorization-pytorch) - PyTorch reimplementation of Interactive Deep Colorization https://richzhang.github.io/ideepcolor/ * [Automatic Image Colorization](https://github.com/kainoj/colnet) - Automatic Image Colorization with Simultaneous Classification – based on "Let there be Color!". * [Image colorization with GANs](https://github.com/karoly-hars/GAN_image_colorizing) - Image colorization with generative adversarial networks on the CIFAR10 dataset. * [Colorful Image Colorization PyTorch](https://github.com/Time0o/pytorch-colorful-colorization) - A from-scratch PyTorch implementation of "Colorful Image Colorization" by Zhang et al. created for the Deep Learning in Data Science course at KTH Stockholm. * [Colorful Image Colorization](https://github.com/Epiphqny/Colorization) - Pytorch implementation of the paper Colorful Image Colorization https://arxiv.org/abs/1603.08511 * [Square-Images-Colorization](https://github.com/done1892/Square-Images-Colorization) - Colorization algorithms for images depicting cities squares ### C++ * [Beyond Landscapes: An Exemplar-based Image colorization method](https://github.com/saulo-p/Exemplar-Image-Colorization) - Exemplar-based Image Colorization method based on superpixel segmentation and classification. ### C# * [StyleTransfer-Colorization-SuperResolution](https://github.com/ColorfulSoft/StyleTransfer-Colorization-SuperResolution) - Demonstration implementations of neural network image processing algorithms. ## Language-based colorization * [SketchySceneColorization](https://github.com/SketchyScene/SketchySceneColorization) - Language-based Colorization of Scene Sketches. (SIGGRAPH Asia 2019) https://sketchyscene.github.io/SketchySceneColorization/ ## Implementations / apps ### iOS * [Colorizer iOS](https://github.com/alex011235/Colorizer-iOS) - Transform grayscale photos to color photos in iOS ## :books: Relevant knowledge, books and papers * [Awesome-Image-Colorization](https://github.com/MarkMoHR/Awesome-Image-Colorization) - A collection of Deep Learning based Image Colorization and Video Colorization papers. * [Build a Photo Restoration App with Python](https://www.youtube.com/watch?v=xgQpalRRW3A) - YouTube tutorial from AssemblyAI on how to build a photo restoration app with Python and Flask. ## :dark_sunglasses: Related awesome lists * [Awesome Machine Learning](https://github.com/josephmisiti/awesome-machine-learning) - A curated list of awesome Machine Learning frameworks, libraries and software. * [Awesome Deep Learning](https://github.com/ChristosChristofidis/awesome-deep-learning) - A curated list of awesome Deep Learning tutorials, projects and communities. * [Awesome Deep Vision](https://github.com/kjw0612/awesome-deep-vision) - A curated list of deep learning resources for computer vision.
{ "repo_name": "oskar-j/awesome-image-coloring", "stars": "48", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# Freebies Hub [![Awesome](https://awesome.re/badge.svg)](https://awesome.re) [![Check Links](https://github.com/zcraber/Freebies-Hub/actions/workflows/links.yml/badge.svg)](https://github.com/zcraber/Freebies-Hub/actions/workflows/links.yml) My attempt to list out some super-useful but not-so-popular websites which offer images, vectors, videos, music, templates etc for FREE with personal &amp; commercial use license. I created this list originally in <a href="https://forum.affinity.serif.com/index.php?/topic/110455-freebies-hub-free-images-vectors-videos-templates-music-fonts-more/" target="_blank">Affinity forum</a>. πŸ“Œ <b><i>Sometimes attributions are required. So make sure to check the license terms before using the items.</i></b> ## Multiple Freebies 🌐 <ul> <li><a href="https://mixkit.co/" target="_blank">Mixkit</a> - FREE Images, Videos, Templates &amp; Music</li> <li><a href="https://pikwizard.com/" target="_blank">Pikwizard</a> - FREE Images &amp; Videos</li> <li><a href="https://focastock.com/" target="_blank">FOCA</a> - FREE Images, Videos &amp; Templates</li> <li><a href="https://www.stockvault.net/" target="_blank">Stockvault</a> - FREE Images, Vectors, Brushes &amp; Templates</li> <li><a href="https://freedesignfile.com/" target="_blank">Freedesignlife</a> - FREE Images, Vectors, Brushes, PSDs, Icons &amp; Fonts</li> <li><a href="https://picspree.com/en" target="_blank">Picspree</a> - FREE Images &amp; Vectors</li> <li><a href="https://wingsart.studio/#subscribe" target="_blank">Wingart Studio</a> - FREE (Selected) Graphics &amp; Templates Every Month</li> <li><a href="https://picryl.com/" target="_blank">picryl</a> - FREE Images, Illustrations, Videos, Music, Documents etc</li> <li><a href="https://digitalmedia.fws.gov/" target="_blank">USFWS National Digital Library</a> - FREE Images, Illustrations, Videos, Audio, Maps etc</li> <li><a href="https://publicdomainclip-art.blogspot.com/" target="_blank">Clip Art Blog</a> - FREE Clip Art &amp; Images</li> </ul> ## FREE Images πŸ“· <ul> <li><a href="https://www.reshot.com/" target="_blank">Reshot</a></li> <li><a href="https://freephotos.cc/" target="_blank">Freephotos</a></li> <li><a href="https://www.freevector.com/" target="_blank">Freestocks</a></li> <li><a href="https://altphotos.com/" target="_blank">Altphotos</a></li> <li><a href="https://www.nappy.co/" target="_blank">nappy</a></li> <li><a href="https://www.slon.pics/" target="_blank">slon.pics</a></li> <li><a href="https://mystock.themeisle.com/" target="_blank">My Stock Photos</a></li> <li><a href="http://shutteroo.com/" target="_blank">Shutteroo</a></li> <li><a href="https://skitterphoto.com/" target="_blank">Skitterphoto</a></li> <li><a href="https://picography.co/" target="_blank">Picography</a></li> <li><a href="https://burst.shopify.com/" target="_blank">Burst</a></li> <li><a href="http://picmelon.com/" target="_blank">Pic Melon</a></li> <li><a href="https://myphotopack.com/" target="_blank">My Photo Pack</a></li> <li><a href="https://goo.gl/photos/6TB8VNQ6ADSk9T729" target="_blank">Vladmir&apos;s Collection</a></li> <li><a href="https://freenaturestock.com/" target="_blank">Free Nature Stock</a></li> <li><a href="https://travelcoffeebook.com/" target="_blank">Travel Coffee Book</a></li> <li><a href="http://skuawk.com/" target="_blank">Skuak</a></li> <li><a href="https://stokpic.com/" target="_blank">Stokpic</a></li> <li><a href="https://freelyphotos.com/" target="_blank">Freely Photos</a></li> <li><a href="https://wunderstock.com/" target="_blank">Wunderstock</a></li> <li><a href="https://moveast.me/" href="https://moveast.me/" target="_blank">Moveast</a></li> <li><a href="http://freefoodphotos.com/" target="_blank">Free Food Photos</a> - FREE Images of Food</li> <li><a href="http://unprofound.com/" target="_blank">unprofound</a></li> <li><a href="https://thepicpac.com/" target="_blank">Pic Pac</a> - FREE Images (pay what you want)</li> <li><a href="https://iwaria.com/" target="_blank">iwaria</a> - FREE Images from Africa</li> <li><a href="http://creativity103.com/" target="_blank">Creativity103</a> - FREE Abstract Images &amp; Textures</li> <li><a href="https://www.focusfitness.net/stock-photos/" target="_blank">Focus Fitness</a> - FREE Fitness Images</li> <li><a href="https://freevintageillustrations.com/" target="_blank">Free Vintage Illustrations</a> - FREE Illustrations from Past</li> <li><a href="https://www.oldbookillustrations.com/" target="_blank">Old Book Illustrations</a> - FREE Illustrations from Past</li> <li><a href="http://www.reusableart.com/" target="_blank">Reusable Art</a> - FREE Old Artwork</li> <li><a href="https://www.lowpolygonart.com/" target="_blank">lowpolygonart</a> - FREE Low Polygon Art</li> <li><a href="https://www.streamlineicons.com/free/" target="_blank">Streamline Icons</a> - FREE PNG Icons</li> <li><a href="https://dribbble.com/shots/2150452-Cosmos-free-icon-set-1/attachments/394013" target="_blank">Cosmos</a> - FREE PSD Icons</li> <li><a href="http://srufaculty.sru.edu/david.dailey/public/public_domain.htm" target="_blank">Dictionary Images</a> -FREE Public Domain Images and Illustrations from Dictionary</li> <li><a href="http://www.logodesignweb.com/stockphoto/" target="_blank">Logo Design Web</a> - FREE Public Domain Images</li> <li><a href="https://www.pdclipart.org/" target="_blank">PDClipart</a> - FREE Clipart (Raster)</li> <li><a href="https://antiqueclipart.com/" target="_blank">Antique Clipart</a> - FREE Antique Clipart (Raster)</li> <li><a href="https://wpclipart.com/" target="_blank">WPClipart</a> - FREE Images &amp; Clipart</li> <li><a href="https://gradienta.io/" target="_blank">Gradienta</a> - FREE CSS Gradients &amp; JPGs</li> <li><a href="https://clouddevs.com/3dbay/" target="_blank">3D Bay</a> - FREE 3D images</li> <li><a href="https://github.com/darriagada/Decay-Textures" target="_blank">Decay Textures</a> - FREE Grunge Textures</li> <li><a href="https://3dicons.co/" target="_blank">3dicons</a> - FREE 3D Icons</li> </ul> ## FREE Vectors 🎨 <ul> <li><a href="https://www.openpeeps.com/" target="_blank">Open Peeps</a> - FREE Hand-drawn Vector Library&nbsp;</li> <li><a href="https://isometric.online/" target="_blank">Isometric</a> - FREE Isometric Vectors</li> <li><a href="https://illlustrations.co/" target="_blank">Illustrations</a> - FREE Kit with 100 Vectors</li> <li><a href="https://www.drawkit.io/" target="_blank">DrawKit</a></li> - Some illustrations are FREE <li><a href="https://undraw.co/" target="_blank">unDraw</a></li> <li><a href="https://lukaszadam.com/illustrations" target="_blank">Lukaszadam</a></li> <li><a href="https://www.opendoodles.com/" target="_blank">Open Doodles</a></li> <li><a href="https://www.freevector.com/" target="_blank">Free Vector</a></li> <li><a href="https://www.glazestock.com/" target="_blank">Glaze</a></li> <li><a href="https://www.manypixels.co/gallery/" target="_blank">manypixels</a></li> <li><a href="https://freevectormaps.com/" target="_blank">Free Vector Maps</a></li> <li><a href="https://fresh-folk.com/" target="_blank">Fresh Folk</a> - FREE Vector Library with People &amp; Objects Illustrations</li> <li><a href="https://www.humaaans.com/" target="_blank">Humaaans</a> - FREE Vector Library with People Illustrations</li> <li><a href="https://openclipart.org/" target="_blank">Openclipart</a> - FREE Vector Cliparts</li> <li><a href="https://freesvg.org/" target="_blank">FREESVG</a></li> <li><a href="https://svgsilh.com/" target="_blank">SVG SILH</a> - FREE Vector Icons</li> <li><a href="https://www.svgrepo.com/" target="_blank">SVG Repo</a></li> <li><a href="https://www.sketchappsources.com/all-free-sources.html" target="_blank">Sketch App Resources</a> - FREE Sketch Resources</li> <li><a href="http://clipart.nicubunu.ro/" target="_blank">Nicu&apos;s Clipart Collection</a></li> <li><a href="https://iconmonstr.com/" target="_blank">iconmonstr</a> - FREE Icons</li> <li><a href="https://ikonate.com/" target="_blank">ikonate</a> - FREE Customizable Vector Icons</li> <li><a href="https://iconoir.com/" target="_blank">Iconoir</a> - FREE Icons (<a href="https://github.com/lucaburgio/iconoir">Open Source</a>)</li> <li><a href="https://heroicons.com/" target="_blank">Heroicons</a> - FREE Icons (<a href="https://github.com/tailwindlabs/heroicons">Open Source</a>)</li> <li><a href="https://ionic.io/ionicons" target="_blank">Ionicons</a> - FREE Icons (<a href="https://github.com/ionic-team/ionicons">Open Source</a>)</li> <li><a href="https://smolicons.com/" target="_blank">Smolicons</a> - FREE Icons</li> <li><a href="http://www.zondicons.com/" target="_blank">Zondicons</a> - FREE Icons</li> <li><a href="https://simpleicons.org/" target="_blank">Simpleicons</a> - FREE Icons (<a href="https://github.com/simple-icons/simple-icons">Open Source</a>)</li> <li><a href="https://icons.getbootstrap.com/" target="_blank">Bootstrap Icons</a> - FREE Icons (<a href="https://github.com/twbs/icons">Open Source</a>)</li> <li><a href="https://pattern.monster/" target="_blank">Pattern Monster</a> - FREE SVG Patterns (<a href="https://github.com/catchspider2002/svelte-svg-patterns">Open Source</a>)</li> <li><a href="https://heropatterns.com/" target="_blank">Hero Patterns</a> - FREE SVG Patterns</li> <li><a href="https://github.com/edent/SuperTinyIcons" target="_blank">SuperTinyIcons</a> - FREE Miniscule SVG Icons of Websites & Apps </li> <li><a href="https://majesticons.com/" target="_blank">Majesticons</a> - FREE Icons (<a href="https://github.com/simple-icons/simple-icons">Open Source</a>)</li> <li><a href="https://pixelarticons.com/" target="_blank">Pixelarticons</a> - FREE Icons (<a href="https://github.com/halfmage/pixelarticons">Open Source</a>)</li> <li><a href="https://icon-icons.com/" target="_blank">icon-icons</a> - FREE Icons </li> <li><a href="https://icongr.am/" target="_blank">icongram</a> - FREE Icons</li> <li><a href="https://icones.js.org/" target="_blank">icones</a> - Icon Explorer</li> <li><a href="https://www.streamlinehq.com/freebies" target="_blank">Streamline</a> - FREE Icons</li> <li><a href="https://iconify.design/" target="_blank">Iconfiy</a> - FREE Icons (<a href="https://github.com/iconify">Open Source</a>)</li> </ul> ## FREE Mockups, Placeholders, Templates etc πŸ’» <ul> <li><a href="https://uiprint.co/" target="_blank">uiprint</a> - FREE Printable Wireframes, Mockup and Sketchpads</li> <li><a href="https://uilogos.co/" target="_blank">uilogos</a> - FREE Logo Placeholders</li> <li><a href="https://www.ls.graphics/free-mockups" target="_blank">lstore graphics</a> - FREE Mockups</li> <li><a href="https://themockup.club/" target="_blank">Mockup Club</a> - FREE Mockups</li> <li><a href="https://365psd.com/" target="_blank">365psd</a> - FREE PSDs</li> <li><a href="https://www.creative-tim.com/templates/free" target="_blank">Creative Tim</a> - FREE Web Templates &amp; Themes</li> <li><a href="https://unlayer.com/templates" target="_blank">Email Monster</a> - FREE Email Templates</li> <li><a href="https://www.designdb.co/" target="_blank">Design DB</a> - FREE Templates</li> <li><a href="https://www.uiuxrepo.com/" target="_blank">UIUX Repo</a> - FREE UI and graphic design resources for Photoshop, Sketch, Adobe Xd and Figma</li> <li><a href="https://oceanwatcher.com/free-instagram-carousel-templates-for-affinity-photo/" target="_blank">Oceanwatcher Media</a> - FREE Affinity Photo Templates</li> <li><a href="https://unblast.com" target="_blank">Unblast</a> - FREE Mockups</li> <li><a href="https://www.pixeltrue.com/free-ui-kits" target="_blank">UI Kits</a> - FREE UI Kits</li> </ul> ## FREE Videos <ul> <li><a href="https://mazwai.com/" target="_blank">Mazwai</a></li> <li><a href="https://coverr.co/" target="_blank">Coverr</a></li> <li><a href="https://lifeofvids.com/" target="_blank">Life of Vids</a></li> <li><a href="https://www.vidsplay.com/" target="_blank">Vids Play</a></li> <li><a href="https://www.dareful.com/" target="_blank">Dareful</a></li> <li><a href="http://www.clipstill.com/" target="_blank">Clipstill</a> - FREE Cinemagraphs</li> <li><a href="https://www.motionelements.com/free/stock-footage" target="_blank">Motion Elements</a> - FREE Stock Footage</li> <li><a href="https://www.videvo.net/" target="_blank">Videvo</a> - FREE Stock Footage</li> <li><a href="https://github.com/darriagada/Retro-Noise" target="_blank">Retro Noise</a> - FREE Animated Noise Textures</li> </ul> ## FREE Music &amp; Sound FX 🎢 <ul> <li><a href="https://freemusicarchive.org/" target="_blank">Free Music Archive</a></li> <li><a href="https://incompetech.com/" target="_blank">Incomptech</a></li> <li><a href="https://www.m-operator.com/" target="_blank">m-operator</a></li> <li><a href="https://www.purple-planet.com/" target="_blank">Purple Planet</a></li> <li><a href="https://www.free-stock-music.com/" target="_blank">Free Stock Music</a></li> <li><a href="https://www.fesliyanstudios.com/" target="_blank">Fesliyan Studios</a> - FREE Music &amp; Sound Effects</li> <li><a href="https://www.themotionmonkey.co.uk/free-resources/retro-arcade-sounds/" target="_blank">The Motion Monkey</a> - FREE 300 Retro Game Sound Effects</li> <li><a href="https://www.freesfx.co.uk/" target="_blank">Free SFX</a> - FREE Sound Effects</li> <li><a href="https://sound-effects.bbcrewind.co.uk/" target="_blank">BBC Sound Effects</a> - FREE Sound Effects</li> <li><a href="https://99sounds.org/cinematic-sound-effects/" target="_blank">99Sounds</a> - FREE Cinematic Sound Effects</li> </ul> ## FREE Fonts ✍🏼 <ul> <li><a href="https://www.theleagueofmoveabletype.com/" target="_blank">League of Movable Type</a></li> <li><a href="https://fontlibrary.org/" target="_blank">Font Library</a></li> <li><a href="https://www.fontrepo.com/" target="_blank">FONT Repo</a></li> <li><a href="https://www.fontget.com/" target="_blank">FontGet</a></li> <li><a href="https://getfont.cc/" target="_blank">Get Font</a></li> <li><a href="http://velvetyne.fr/" target="_blank">VTF</a></li> <li><a href="https://www.fontshare.com/" target="_blank">Fontshare</a></li> <li><a href="https://www.wfonts.com/" target="_blank">wFonts</a></li> <li><a href="https://www.fontskey.com/" target="_blank">FontsKey</a></li> </ul> ### Credits 😍 List of users who suggested new websites. <li><a href="https://github.com/bestinjac" target="_blank">@bestinjac</a></li> <li><a href="https://forum.affinity.serif.com/index.php?/profile/132304-unemule/" target="_blank">@uneMule</a></li> <li><a href="https://github.com/imjackchan" target="_blank">@imjackchan</a></li> ### Notes πŸ“’ Feel free to make suggestions <a href="https://github.com/zcraber/Freebies-Hub/issues" target="_blank">here</a> if you know of any <b>not-so-popular</b> websites that should be on this list. Please note that I will not add your suggestion if the website is popular and well-known. Because the purpose of this list is to shout out hidden gems. πŸ’Ž ### Disclaimer πŸ”΄ I don't own any of these websites and I'll not be liable for any damage you get by using the items listed as freebies. Make sure to check the license terms of the item and crosscheck to ensure it is truly a freebie and not infringing someone's copyright. If you're the owner of one of the websites listed here and would like to remove it, just let me know. πŸ™‚
{ "repo_name": "zcraber/Freebies-Hub", "stars": "56", "repo_language": "None", "file_name": "links.yml", "mime_type": "text/plain" }
name: Links on: repository_dispatch: workflow_dispatch: schedule: - cron: "00 18 * * *" jobs: linkChecker: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Link Checker id: lychee uses: lycheeverse/lychee-action@v1 env: GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - name: Create Issue From File if: env.lychee_exit_code != 0 uses: peter-evans/create-issue-from-file@v4 with: title: Link Checker Report content-filepath: ./lychee/out.md labels: report, automated issue
{ "repo_name": "zcraber/Freebies-Hub", "stars": "56", "repo_language": "None", "file_name": "links.yml", "mime_type": "text/plain" }
#!/usr/bin/env bash event(){ case $1 in error|quote|encode|decode);; *) __ev.encode "${2-}";local f n='' e=bashup_event_$REPLY'[1]';f=${e/event/flag} case $1 in emit) shift;${!f-};eval "${!e-}"; return ;;on|once|off|has) case "${3-}" in @_) n='$#';; @*[^0-9]*);; @[0-9]*) n=$((${3#@}));; esac; ${n:+ set -- "$1" "$2" "${@:4}" } case $1/$# in on*/[12]) set -- error "${2-}: missing callback";; */[12]) REPLY=;; *) __ev.quote "${@:3}";((${n/\$#/1}))&&REPLY+=' "${@:2:'"$n"'}"';REPLY+=$'\n' esac esac esac ;__ev."$@";} __ev.error(){ echo "$1">&2;return "${2:-64}";} __ev.quote(){ REPLY=; ${@+printf -v REPLY ' %q' "$@"}; REPLY=${REPLY# };} __ev.has(){ [[ ${!e-} && $'\n'"${!e}" == *$'\n'"$REPLY"* && ! ${!f-} ]];} __ev.get(){ ${!f-};REPLY=${!e-};} __ev.on(){ __ev.has && return;if [[ ! ${!f-} ]];then eval "$e"+='$REPLY';else eval "${!e-};$REPLY";fi;} __ev.off(){ __ev.has||return 0; n="${!e}"; n=${REPLY:+"${n#"$REPLY"}"}; eval "$e"=$'"${n//\n"$REPLY"/\n}"';[[ ${!e} ]]||unset "${e%\[1]}";} __ev.fire(){ ${!f-};set -- "$e" "${@:2}"; while [[ ${!1-} ]];do eval "unset ${1%\[1]};${!1}"; done ;} __ev.all(){ ${!f-};e=${!e-};eval "${e//$'\n'/||return; }";} __ev.any(){ ${!f-};e=${!e-};eval "${e//$'\n'/&&return|| } ! :";} __ev.resolve(){ ${!f-};__ev.fire "$@";__ev.quote "$@" printf -v n "eval __ev.error 'event \"%s\" already resolved' 70;return" "$1"; eval "${f}"='$n' printf -v n 'set -- %s' "$REPLY"; eval "${e}"='$n';readonly "${f%\[1]}" "${e%\[1]}" } __ev.resolved(){ [[ ${!f-} ]];} __ev.once(){ n=${n:-0} n=${n/\$#/_}; event on "$1" "@$n" __ev_once $# "@$n" "$@";} __ev_once(){ event off "$3" "$2" __ev_once "${@:1:$1+2}"; "${@:4}";} __ev_jit(){ local q r=${__ev_jit-} s=$1;((${#r}<250))||__ev_jit= while [[ "$s" ]]; do r=${s::1};s=${s:1};printf -v q %q "$r";eval 's=${s//'"$q}";printf -v r 'REPLY=${REPLY//%s/_%02x};' "${q/#[~]/[~]}" "'$r";eval "$r";__ev_jit+="$r" done eval '__ev.encode(){ local LC_ALL=C;REPLY=${1//_/_5f};'\ "${__ev_jit-}"' [[ $REPLY != *[^_[:alnum:]]* ]] || __ev_jit "${REPLY//[_[:alnum:]]/}";}' };__ev_jit '' __ev.decode(){ REPLY=();while (($#));do printf -v n %b "${1//_/\\x}";REPLY+=("$n");shift;done;} __ev.list(){ eval 'set -- "${!'"${e%\[1]}"'@}"';__ev.decode "${@#bashup_event_}";}
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
BINS=bashup.events
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
# Practical Event Listeners for Bash `bashup.events` is an event listener/callback API for creating extensible bash programs. It's small (<2.2k), fast (~10k events/second), and highly portable (no bash4-isms or external programs used). Events can be one-time or repeated, listeners can be added or removed, and any string can be an event name. (You can even have "[promises](#promise-like-events)", of a sort!) Callbacks can be any command or function plus any number of arguments, and can even opt to receive [additional arguments supplied by the event](#passing-arguments-to-callbacks). Other features include: * Running a callback each time something happens ([`event on`](#event-on), [`event emit`](#event-emit)) * Running a callback the *next* time something happens, but not after that ([`event once`](#event-once)) * Alerting subscribers of an event once, making them re-subscribe for future occurrences ([`event fire`](#event-fire) ) * Alerting subscribers of a one-time only event or calculation... not just current subscribers, but *future* ones as well ([`event resolve`](#event-resolve)) * Allowing subscribed callbacks to veto a process (e.g. validation rules), using [`event all`](#event-all) * Searching for the first callback that can successfully handle something, using [`event any`](#event-any) #### Contents <!-- toc --> - [Installation, Requirements And Use](#installation-requirements-and-use) - [Basic Operations](#basic-operations) * [event on](#event-on) * [event emit](#event-emit) * [event off](#event-off) * [event has](#event-has) * [event fire](#event-fire) - [Passing Arguments To Callbacks](#passing-arguments-to-callbacks) - [Promise-Like Events](#promise-like-events) * [event resolve](#event-resolve) * [event resolved](#event-resolved) - [Conditional Operations](#conditional-operations) * [event all](#event-all) * [event any](#event-any) - [Other Operations](#other-operations) * [event once](#event-once) * [event encode](#event-encode) * [event decode](#event-decode) * [event get](#event-get) * [event list](#event-list) * [event quote](#event-quote) * [event error](#event-error) - [Event Handlers and Subshells](#event-handlers-and-subshells) - [License](#license) <!-- tocstop --> ### Installation, Requirements And Use Copy and paste the [code](bashup.events) into your script, or place it on `PATH` and `source bashup.events`. (If you have [basher](https://github.com/basherpm/basher), you can `basher install bashup/events` to get it installed on your `PATH`.) The code is licensed [CC0](http://creativecommons.org/publicdomain/zero/1.0/), so you are not required to add any attribution or copyright notices to your project. ````sh $ source bashup.events ```` This version of bashup.events works with bash 3.2+. If you don't need to support older bash versions, you can use the [bash44 branch](https://github.com/bashup/events/tree/bash44), which is significantly faster (~23k emits/second). Besides the supported bash version, the differences between the two versions are: * The 3.2+ version is a bit larger and a lot slower: only around 10K emits/second, even when run with a newer bash. * The 3.2+ version of `event list` returns sorted keys; the 4.4 version does not give a guaranteed order * The 4.4+ version uses associative arrays; the 3.2+ version emulates them using individual variables with urlencoded names. Among other things, this means that the 3.2+ version can mask specific events with `local`, but the 4.4 version cannot. * Other performance characteristics vary, as they use different `event encode` implementations with different performance characteristics. (4.4's is tuned for reasonable performance regardless of character set, while 3.2's is tuned for speed at all costs with a small character set.) ### Basic Operations Sourcing `bashup.events` exposes one public function, `event`, that provides a variety of subcommands. All of the primary subcommands take an event name as their first argument. Event names can be any string, but performance is best if you limit them to pure ASCII alphanumeric or `_` characters, as all other characters have to be encoded at the start of each event command. (And the larger the character set used, the slower the encoding process becomes.) #### event on `event on` *event cmd [args...]* subscribes *cmd args...* as a callback to *event*, if it's not already added: ````sh $ event on "event1" echo "got event1" $ event on "event1" echo "is this cool or what?" ```` #### event emit `event emit` *event data...* invokes all the callbacks for *event*, passing *data...* as additional arguments to any callbacks that [registered to receive them](#passing-arguments-to-callbacks). Callbacks added to the event while the `emit` is occurring will **not** be invoked until a subsequent occurrence of the event, and the already-added callbacks will remain subscribed (unless they unsubscribe themselves, or were registered with [`event once`](#event-once)). ````sh $ event emit "event1" got event1 is this cool or what? ```` #### event off `event off` *event [cmd [args...]]* unsubscribes the *cmd args...* callback from *event*. If no callback is given, *all* callbacks are removed. ````sh $ event off "event1" echo "got event1" $ event emit "event1" is this cool or what? $ event on "event2" echo foo $ event off "event2" $ event emit "event2" ```` #### event has * `event has` *event* returns truth if *event* has any registered callbacks. * `event has` *event cmd [args...]* returns truth if *cmd args...* has been registered as a callback for *event*. ````sh # `event has` with no callback tests for any callbacks at all $ event has "event1" && echo "yes, there are some callbacks" yes, there are some callbacks $ event has "something_else" || echo "but not for this other event" but not for this other event # Test for specific callback susbscription: $ event has "event1" echo "is this cool or what?" && echo "cool!" cool! $ event has "event1" echo "got event1" || echo "nope!" nope! ```` #### event fire `event fire` *event data...* fires a "one shot" event, by invoking all the callbacks for *event*, passing *data...* as additional arguments to any callbacks that [registered to receive them](#passing-arguments-to-callbacks). All callbacks are removed from the event, and any new callbacks added during the firing will be invoked as soon as all the previously-added callbacks have been invoked (and then are also removed from the event). The overall idea is somewhat similar to the Javascript "promise" resolution algorithm, except that you can `fire` an event more than once, and there is no "memory" of the arguments. (See [`event resolve`](#event-resolve) if you want something closer to a JS Promise.) ````sh # `event fire` removes callbacks and handles nesting: $ mycallback() { event on event1 echo "nested!"; } $ event on "event1" mycallback $ event fire "event1" is this cool or what? nested! $ event emit "event1" # all callbacks gone now ```` ### Passing Arguments To Callbacks When invoking an event, you can pass additional arguments that will be added to the end of the arguments supplied to the given callbacks. The callbacks, however, will only receive these arguments if they were registered to do so, by adding an extra argument after the event name: an `@` followed by the maximum number of arguments the callback is prepared to receive: ````sh # Callbacks can receive extra arguments sent by emit/fire/resolve/all/any: $ event on "event2" @2 echo "Args:" # accept up to 2 arguments $ event fire "event2" foo bar baz Args: foo bar ```` The reason an argument count is required, is because one purpose of an event system is to be *extensible*. If an event adds new arguments over time, old callbacks may break if they weren't written in such a way as to ignore the new arguments. Requiring an explicit request for arguments avoids this problem. If the nature of the event is that it emits a *variable* number of arguments, however, you can register your callback with `@_`, which means "receive *all* the arguments, no matter how many". You should only use it in places where you can definitely handle any number of arguments, or else you may run into unexpected behavior. ````sh # Why variable arguments lists aren't the default: $ event on "cleanup" @_ echo "rm -rf" $ event emit "cleanup" foo rm -rf foo $ event emit "cleanup" foo / # New release... "cleanup" event added a new argument! rm -rf foo / ```` [`event on`](#event-on), [`event once`](#event-once), [`event off`](#event-off), and [`event has`](#event-has) all accept argument count specifiers when adding, removing, or checking for callbacks. Callbacks with different argument counts are considered to be *different* callbacks: ````sh # Only one argument: $ event on "myevent" @1 echo $ event emit "myevent" foo bar baz foo # Different count = different callbacks: $ event has "myevent" @1 echo && echo got it got it $ event has "myevent" @2 echo || echo nope nope # Add 2 argument version (numeric value is what's used): $ event on "myevent" @02 echo $ event emit "myevent" foo bar baz foo foo bar # Remove the 2-arg version, add unlimited version: $ event off "myevent" @2 echo $ event on "myevent" @_ echo $ event emit "myevent" foo bar baz foo foo bar baz # Unlimited version is distinct, too: $ event has "myevent" @_ echo && echo got it got it $ event has "myevent" @2 echo || echo nope nope # As is the zero-arg version: $ event has "myevent" echo || echo nope nope # But the zero-arg version can be implicit or explicit, w/or without leading zeros: $ event on "myevent" echo $ event has "myevent" echo && echo got it got it $ event has "myevent" @0 echo && echo got it got it $ event off "myevent" @00 echo $ event has "myevent" echo || echo nope nope ```` ### Promise-Like Events #### event resolve If you have a truly one-time event, but subscribers could "miss it" by subscribing too late, you can use `event resolve` to "permanently [`fire`](#event-fire)" an event with a specific set of arguments. Once this is done, all future `event on` calls for that event will invoke the callback *immediately* with the previously-given arguments. There is no way to "unresolve" a resolved event within the current shell. Trying to `resolve`, `emit`, `fire`, `any` or `all` an already-resolved event will result in an error message and a failure return of 70 (`EX_SOFTWARE`). ````sh # Subscribers before the resolve will be fired upon resolve: $ event on "promised" event on "promised" @1 echo "Nested:" $ event on "promised" @1 echo "Plain:" $ event resolve "promised" value Plain: value Nested: value # Subscribers after the resolve are fired immediately: $ event on "promised" event on "promised" @1 echo "Nested:" Nested: value $ event on "promised" @1 echo "Plain:" Plain: value # And a resolved event never "has" any subscribers: $ event has "promised" || echo nope nope ```` #### event resolved `event resolved` *event* returns truth if `event resolve` *event* has been called. ````sh $ event resolved "promised" && echo "yep" yep $ event resolved "another_promise" || echo "not yet" not yet ```` ### Conditional Operations #### event all `event all` *event data*... works like [`event emit`](#event-emit), except that execution stops after the first callback that returns false (i.e., a non-zero exit code), and that exit code is returned. Truth is returned if all events return truth. ````sh # Use an event to validate a password $ validate() { echo "validating: $1"; [[ $3 =~ $2 ]]; } $ event on "password_check" @1 validate "has a number" '[0-9]+' $ event on "password_check" @1 validate "is 8+ chars" ........ $ event on "password_check" @1 validate "has uppercase" '[A-Z]' $ event on "password_check" @1 validate "has lowercase" '[a-z]' $ event all "password_check" 'foo27' || echo "fail!" validating: has a number validating: is 8+ chars fail! $ event all "password_check" 'Blue42Schmoo' && echo "pass!" validating: has a number validating: is 8+ chars validating: has uppercase validating: has lowercase pass! ```` #### event any `event any` *event data...* also works like [`event emit`](#event-emit), except that execution stops on the first callback to return truth (i.e. a zero exit code). An exit code of 1 is returned if all events return non-zero exit codes. ````sh $ match() { echo "checking for $1"; REPLY=$2; [[ $1 == $3 ]]; } $ event on "lookup" @1 match a "got one!" $ event on "lookup" @1 match b "number two" $ event on "lookup" @1 match c "third time's the charm" $ event any "lookup" b && echo "match: $REPLY" checking for a checking for b match: number two $ event any "lookup" q || echo "fail!" checking for a checking for b checking for c fail! ```` ### Other Operations #### event once `event once` *event cmd [args...]* is like [`event on`](#event-on), except that the callback is unsubscribed before it's invoked, ensuring it will be called at most once, even if *event* is emitted multiple times in a row: ````sh $ event once "something" @_ echo $ event emit "something" this that this that $ event emit "something" more stuff ```` (Note: a callback added by `event once` cannot be removed by `event off`; if you need to be able to remove such a callback you should use `event on` instead and make the callback remove itself with `event off`.) #### event encode `event encode` *string* sets `$REPLY` to an encoded version of *string* that is safe to use as part of a bash variable name (i.e. ascii alphanumerics and `_`). Underscores and all other non-alphanumerics are encoded as an underscore and two hex digits. ````sh $ event encode "foo" && echo $REPLY foo $ event encode "foo.bar" && echo $REPLY foo_2ebar $ event encode "foo_bar" && echo $REPLY foo_5fbar $ event encode ' !"#$%'\''()*+,-./:;<=>?@[\]^_`' && echo "$REPLY" _20_21_22_23_24_25_27_28_29_2a_2b_2c_2d_2e_2f_3a_3b_3c_3d_3e_3f_40_5b_5c_5d_5e_5f_60 $ event encode $'\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0b\f\r\x0e\x0f\x10' && > echo "$REPLY" _01_02_03_04_05_06_07_08_09_0a_0b_0c_0d_0e_0f_10 $ event encode $'{|}~\x7f' && echo "$REPLY" _7b_7c_7d_7e_7f ```` For performance reasons, the function that handles event encoding is JITted. Every time new non-ASCII or non-alphanumeric characters are seen, the function is rewritten to efficiently handle encoding them. This makes encoding extremely fast when a program only ever uses a handful of punctuation characters in event names or strings passed to `event encode`. Encoding arbitrary strings (or using them as event names) is not recommended, however, since this will "train" the encoder to run more slowly for *all* `event` operations from then on. #### event decode `event decode` *string* sets `$REPLY` to the original event name for *string*, turning the encoded characters back to their original values. If multiple arguments are given, `REPLY` is an array of results. ````sh $ event decode "foo_2ebar_2dbaz" && echo $REPLY foo.bar-baz $ event decode "_2fspim" "_2bspam" && printf '%s\n' "${REPLY[@]}" /spim +spam ```` #### event get `event get` *event* sets `$REPLY` to a string that can be `eval`'d to do the equivalent of `event emit "event" "${@:2}"`. This can be used for debugging, or to allow callbacks like `local` to be run in a specific calling context. An error 70 is returned if *event* is resolved. ~~~sh $ event get lookup && echo "$REPLY" match a got\ one\! "${@:2:1}" match b number\ two "${@:2:1}" match c third\ time\'s\ the\ charm "${@:2:1}" $ event get "promised" && echo "$REPLY" event "promised" already resolved [70] ~~~ (Notice that the encoded commands in `$REPLY` reference parameters beginning with `"$2"`, which means that if you want to eval them with `"$@"` you'll need to unshift a dummy argument.) #### event list `event list` *prefix* sets `REPLY` to an array of currently-defined event names beginning with *prefix*. events that currently have listeners are returned, as are resolved events. ````sh # event1 and event2 no longer have subscribers: $ event list "event" && echo "${#REPLY[@]}" 0 # But there are some events starting with "p" $ event list "p" && printf '%s\n' "${REPLY[@]}" password_check promised $ event list "lookup" && printf '%s\n' "${REPLY[@]}" lookup ```` #### event quote `event quote` *args* sets `$REPLY` to a space-separated list of the given arguments in shell-quoted form (using `printf %q`). The resulting string is safe to `eval`, in the sense that the arguments are guaranteed to expand to the same values (and number of values) as were originally given. ````sh $ event quote a b c && echo "$REPLY" a b c $ event quote "a b c" && echo "$REPLY" a\ b\ c $ event quote x "" y && echo "$REPLY" x '' y $ event quote && echo "'$REPLY'" '' ```` #### event error `event error` *message [exitlevel]* prints *message* to stderr and returns *exitlevel*, or 64 (`EX_USAGE`) if no *exitlevel* is given. (You will still need to `return` or `exit` for this to have any further effect, unless `set -e` is in effect.) ````sh $ event error "This is an error" 127 >/dev/null This is an error [127] ```` ### Event Handlers and Subshells Just as with bash variables and functions, the current event handlers and the state of promises are inherited by subshells (e.g. in command substitutions), but changes made by a subshell do not affect the state of the calling shell. (As should be expected given that subshells are forked processes without shared memory or other interprocess communication by default.) Note that this means adding or removing handlers in a subshell (even _implicitly_, via `fire`, `resolve`, `once`, etc.) has **no effect** on the calling shell. As is normally the case for subshells, you’ll need to read their output and act on it, if you need to apply side-effects in the calling process. ### License <p xmlns:dct="http://purl.org/dc/terms/" xmlns:vcard="http://www.w3.org/2001/vcard-rdf/3.0#"> <a rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="https://licensebuttons.net/p/zero/1.0/80x15.png" style="border-style: none;" alt="CC0" /></a><br /> To the extent possible under law, <a rel="dct:publisher" href="https://github.com/pjeby"><span property="dct:title">PJ Eby</span></a> has waived all copyright and related or neighboring rights to <span property="dct:title">bashup/events</span>. This work is published from: <span property="vcard:Country" datatype="dct:ISO3166" content="US" about="https://github.com/bashup/events">United States</span>. </p>
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
#!/usr/bin/env bash if ! [[ -f .dkrc ]]; then echo "Please run this script from the project root directory." >&2 exit 64 # EX_USAGE fi if ! [[ -d .devkit ]]; then # Modify this line if you want to pin a particular .devkit revision: git clone -q --depth 1 https://github.com/bashup/.devkit fi exec ".devkit/dk" "$(basename "$0")" "$@"
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
## Scripts To Rule Them All The scripts in this directory are a [Scripts To Rule Them All](https://githubengineering.com/scripts-to-rule-them-all/) implementation, powered by [.devkit](https://github.com/bashup/.devkit). They should be run from within the project's root directory, using e.g. `script/test` to run tests, and so on. Please check the containing project's documentation for more details, or see the preceding links for more background or reference information.
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
## Miscellaneous Cases and Error Handling We want to test all this with `-eu`, to catch undefined variables and dangling fail statuses: ````sh $ source bashup.events; set -eu ```` e.g. What happens if you don't pass a callback to event on, .has, or .off? ````sh $ ( event on foo ) || echo [$?] foo: missing callback [64] $ ( event on ) || echo [$?] : missing callback [64] $ ( event has x ) || echo [$?] [1] $ event on x echo y $ ( event has x ); echo [$?] [0] ```` Or don't give an event to fire or emit? (they're treated as an empty string) ````sh $ ( event has ) || echo [$?] [1] $ event on "" echo empty-string event $ ( event has ) && echo yes yes $ ( event emit ) || echo [$?] empty-string event $ ( event fire ) || echo [$?] empty-string event ```` And what if you try to pass an arg count to something other than has/on/off? (they're treated as arguments) ````sh $ event on foo @_ echo $ event emit foo @7 bar baz @7 bar baz $ event fire foo @_ bar baz @_ bar baz ```` Or an invalid arg indicator to has/on/off? (they're considered part of the command) ````sh $ event on bar @9.2 quiz $ event emit bar || echo [$?] */bashup.events: line 4: @9.2: command not found (glob) [127] ```` Or try to do something with an already-resolved promise: ````sh # Duplicate emit/fire/resolve/any/all produces code 70 (EX_SOFTWARE): $ event resolve "promised" other $ set +e $ event resolve "promised" other event "promised" already resolved [70] $ event fire "promised" other event "promised" already resolved [70] $ event emit "promised" other event "promised" already resolved [70] $ event any "promised" other event "promised" already resolved [70] $ event all "promised" other event "promised" already resolved [70] ```` Also, "event once" shouldn't leave anything behind in the event, and should handle various argument counts (the `@_` case is tested in the README): ````sh $ event once foobar echo baz $ event emit foobar baz $ event has foobar || echo nope nope $ event once foobar @2 echo fish $ event emit foobar baz spam thingy fish baz spam $ event has foobar || echo nope nope ````
{ "repo_name": "bashup/events", "stars": "75", "repo_language": "Shell", "file_name": "Misc.cram.md", "mime_type": "text/plain" }
{ "aliveStatusCodes": [ 429, 403, 200 0 ] }
{ "repo_name": "SergioGasquez/awesome-electronic-engineering", "stars": "78", "repo_language": "None", "file_name": "linkchecker.yml", "mime_type": "text/plain" }
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
{ "repo_name": "SergioGasquez/awesome-electronic-engineering", "stars": "78", "repo_language": "None", "file_name": "linkchecker.yml", "mime_type": "text/plain" }
# Contribution Guidelines Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. --- Ensure your pull request adheres to the following guidelines: - Follow the format convention: - The link and description are separated by a dash. Example: `- [AVA](…) - JavaScript test runner.` The description starts with an uppercase character and ends with a period. - Consistent and correct naming. For example, `Node.js`, not `NodeJS` or `node.js`. - Update the Table of Contents if it changed - And don't forget to check this Thank you for your suggestions! ## Updating your PR A lot of times, making a PR adhere to the standards above can be difficult. If the maintainers notice anything that we'd like changed, we'll ask you to edit your PR before we merge it. There's no need to open a new PR, just edit the existing one. If you're not sure how to do that, [here is a guide](https://github.com/RichardLitt/knowledge/blob/master/github/amending-a-commit-guide.md) on the different ways you can update your PR so that we can merge it.
{ "repo_name": "SergioGasquez/awesome-electronic-engineering", "stars": "78", "repo_language": "None", "file_name": "linkchecker.yml", "mime_type": "text/plain" }
# Electronic Engineering <!-- [![Awesome](https://awesome.re/badge.svg)](https://awesome.re) --> > awesome electronic engineering resources: Learning resources, circuits simulators, embedded systems, components and much more. ## Contents ## - [Learning Resources](#learning-resources) - [Websites](#websites) - [Books](#books) - [MOOCs](#moocs) - [YouTube Channels](#youtube-channels) - [Podcasts](#podcasts) - [Circuits Simulators](#circuits-simulators) - [PCB](#pcb) - [General](#general) - [KiCad](#kicad) - [Gerber Viewers](#gerber-viewers) - [Forums](#forums) - [Projects](#projects) - [Storing Components](#storing-components) - [Searching Engines of Components](#searching-engines-of-components) - [Blogs](#blogs) - [Interview Questions](#interview-questions) - [Others](#others) - [Contribute](#contribute) ## Learning Resources ## ### Websites ### - [All About Circuits](https://www.allaboutcircuits.com/education/) - Offers a wide variety of learning resources including textbooks, video lectures and worksheets. - [Electronics Tutorials](https://www.electronics-tutorials.ws/) - Very descriptive tutorials in many different fields of electronics. - [Electronics Club](https://electronicsclub.info/) - A website for anyone wishing to learn about electronics or build simple projects. Written for beginners but used by many others as a quick reference. - [Adafruit Learning System](https://learn.adafruit.com/) - It provides a good bit of documentations for a lot of their products, various projects and topics. While these articles tend to geared to beginners and hobbyists, it provides a good resource to discover a new topic. ### Books ### - [Paul and Winfield - The Art Of Electronics](https://www.uvm.edu/~gpetrucc/courses/Chem219/Lectures/Paul%20Horowitz,%20Winfield%20Hill%20-%20The%20Art%20of%20Electronics-Cambridge%20University%20Press%20(2015).pdf) - The most popular and important book, every Electronic Engineer should read it. - [Sedra and Smith - Microelectronic Circuits](https://www.dropbox.com/s/d1tasdkd5u6serm/Sedra%20Smith%20-%20Microelectronic%20Circuits%20-%205th%20Edition.pdf?dl=0) - Explains every microelectronics topic in a very lucid manner. - [Agarwal and Lang - Foundations of Analog and Digital](https://www.dropbox.com/s/g09ot8yzsp1dmrd/Agarwal%20and%20Lang%20-%20Foundations%20of%20Analog%20and%20Digital%20-%202005.pdf?dl=0) - Title is very self-explanatory, explains the basics of digital and analogue electronics. - [Hayt Kemmerly - Engineering Circuit Analysis](https://www.dropbox.com/s/zoyywgy0tgdz7my/Hayt%20Kemmerly%20-%20Engineering%20Circuit%20Analysis.pdf?dl=0) - Made for students, it explains circuit analysis in a very clear way. Lots of numerical examples are included. - [Darren Ashby - Electrical Engineering 101](https://www.dropbox.com/s/cv5nk91ow8jsjp7/Darren%20Ashby%20-%20Electrical%20Engineering%20101%20-%203rd%20Edition.pdf?dl=0) - Basic theory and practice of electronics. ### MOOCs ### - [MOOC LIST](https://www.mooc-list.com/categories/eng-electronics) - MOOC search engine that gathers electronics courses from all online MOOC platforms. - [edX](https://www.edx.org/learn/electronics) - Explore between all kind of electronics online courses. - [coursera](https://www.coursera.org/browse/physical-science-and-engineering/electrical-engineering) - Great compilation of Coursera electrical engineering courses. ### YouTube Channels ### - [GreatScott!](https://www.youtube.com/user/greatscottlab) - GreatScott! offers from basics concepts to experiments in a very clear and explained way. - [EEVblog](https://www.youtube.com/user/EEVblog) - David L. Jones is one of the most known and wise electronics engineers and in his YouTube channel, you can find a lot of interesting videos about certain electronics concepts, reviews or even live videos where he replies to any question fro . - [Andreas Spiess](https://www.youtube.com/channel/UCu7_D0o48KbfhpEohoP7YSQ) - Projects and comparison of electronic devices. - [Jeremy Blum](https://www.youtube.com/user/sciguy14) - Amazing Arduino tutorial series and projects. - [Proto G](https://www.youtube.com/user/garofalo42) - Yet another interesting channel with lots of great projects. - [Phils Lab](https://www.youtube.com/c/PhilS94) - Analog and digital electronics design, PCB design, control systems, digital signal processing, STM32, KiCad, RF, etc. - [Introduction to Embedded Linux: Buildroot, Yocto...](https://www.youtube.com/watch?v=9vsu67uMcko&list=PLEBQazB0HUyTpoJoZecRK6PpDG31Y7RPB&index=1) - YouTube playlist with that covers the basics of embedded systems. ### Podcasts ### - [Internet of Things](https://iotpodcast.com/) - Hosted by Stacey Higginbotham they discuss IoT topics and news. - [The Amp Hour](https://theamphour.com/tag/contextual-electronics/) - Podcast by Contextual Electronics with lots of interviews to important engineers. - [MIT Open Courseware - Circuits and Electronics](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-002-circuits-and-electronics-spring-2007/) - MIT course of an introduction to circuits and electronics. - [Programming Electronics Academy Podcast](https://programmingelectronics.com/oshpodcast/) - Podcast focused on how to programm embedded systems. ## Circuits Simulators ## - [LTspice](http://www.analog.com/en/design-center/design-tools-and-calculators.html) - Free software with a great variety of design simulation tools.- ## PCB ## ### General ### - [Top 5 PCB Design Guidelines Every PCB Designer Needs to Know](https://resources.altium.com/pcb-design-blog/top-pcb-design-guidelines-every-pcb-designer-needs-to-know) - General guidelines to design PCBs. - [EEVblog - PCB Desing Tutorial](http://www.alternatezone.com/electronics/files/PCBDesignTutorialRevA.pdf) - Long and detailed guide that covers everything about PCB design. - [CABLAB.io](https://cadlab.io/) - Git Version Control for Eagle PCB Design. - [UPVERTER](https://upverter.com/) - UPVERTER is a cloud based circuit board design tool (aka EDA). It can assist with developing schematics, PCB layouts, bills of materials, and gerber files. ### KiCad ### - [B.A.Byrce - KiCad PCB Tutorial](http://babryce.com/kicad/tutorial.html) - Short yet efficient KiCad tutorial that uses an example to guide you through all the processes of creating a PCB. - [Contextual Electronics - Shine On You Crazy KiCad](https://www.youtube.com/watch?v=BVhWh3AsXQs&list=PLy2022BX6EspFAKBCgRuEuzapuz_4aJCn) - Contextual Electronics offers lots of KiCad video tutorials. - [AddOhms](https://www.youtube.com/watch?v=5fvdxd0QhTw&list=PLRIGIzu0Z7KllhKqPsNDwitjpK45SHoKg) - Custom Arduino Design Series, Schematic, PCB, Test. ### Gerber Viewers ### - [gerbv](http://gerbv.geda-project.org/) - Free and open source Gerber viewer. Is a native Linux application, but also has an available version for Windows. - [Reference Gerber Viewer](https://gerber.ucamco.com/) - Free and online Gerber viewer developed by Ucamco. - [Tracespace.io](http://viewer.tracespace.io/) - Online viewer that allows to seeing each layer isolated. ## Forums ## - [Electronics StackExchange.](https://electronics.stackexchange.com/) - Do you have any questions? 98% it will be already solved in here. - [/r/AskElectronics/](https://www.reddit.com/r/AskElectronics/) - Feel free to ask any question, gentle people will try their best to help you. - [/r/ECE/](https://www.reddit.com/r/ECE/) - Discussion of all things related to electrical and computer engineering. - [/r/electronic_circuits/](https://www.reddit.com/r/electronic_circuits/) - Place to discuss diagrams and schematics of any circuit. - [/r/ElectricalEngineering/](https://www.reddit.com//r/ElectricalEngineering/) - Subreddit for Electrical Engineering. - [/r/electronics/](https://www.reddit.com/r/electronics/) - Subreddit dedicated to news, articles and discussions related to electronic systems and circuits. - [/r/arduino](https://www.reddit.com/r/arduino/) - A place for any Arduino discussion. - [/r/ArduinoProjects/](https://www.reddit.com/r/ArduinoProjects/) - Show your Arduino project or get amazed by others projects. ## Projects ## - [Instructables](http://www.instructables.com/technology/) - You can find any kind of electronics project. - [Hackter.io](https://www.hackster.io/projects) - Platform to search and upload electronics projects, they also host lots of projects contests with greats rewards. - [Hackaday.io](https://hackaday.io/projects) - This popular blog also host a project sharing page. - [Electronics Projects Hub](https://electronicsprojectshub.com/) - Small site with great projects. ## Storing Components ## - [Partsbox.io](https://partsbox.io/) - They offer a very innovative and great way to keep track of your electronics parts. - [Reddit - Storing your electronic components](https://es.reddit.com/r/electronics/comments/7xz1vs/tip_storing_your_electronic_components/) - Reddit thread with lots of ways to store your components. ## Searching Engines of Components ## - [Octopart](https://octopart.com/) - Find any component by its description, part number or category. - [Findchips](https://www.findchips.com/) - Get instant insight into any electronic component. ## Blogs ## - [Circuits.io](https://circuits.io/) - Ideal for simulations and tutorials. - [Interrupt](https://interrupt.memfault.com/blog/) - Blog from Memfault with lots of interesting embedded posts. - [Embedded Artistry](https://embeddedartistry.com/) - Website for embedded systems developers who are dedicated to excellence and continual improvement. - [Microwaves & RF](http://www.mwrf.com/) - News related to microelectronics and RF. - [EDN Network](https://www.edn.com/) - All kinds of electronics news. - [SparkFun](https://www.sparkfun.com/) - Bunch of different resources, tutorials and a great shop! - [Jay Carlson: So you want to build an embedded system?](https://jaycarlson.net/embedded-linux/) - Incredible post from Jay Carlson about embedded systems. ## Interview Questions ## - [A C Test: The 0x10 Best Questions for Would-be Embedded Programmers](https://rmbconsulting.us/publications/a-c-test-the-0x10-best-questions-for-would-be-embedded-programmers/) - Interesting embedded C interview questions. - [Interview Question Breakdown: Bad C Analysis](https://embeddedartistry.com/blog/2017/06/05/interview-question-breakdown-bad-c-analysis/) - Set of interview questions based on a C problem. - [Embedded c interview questions and answers](https://aticleworld.com/embedded-c-interview-questions-2/) - 100 Embedded C short interview questions. - [Embedded Interview Questions](https://docs.google.com/document/d/18HMyd-lFu1hWiixFLS2Pc7-SgyzDDqitzXbfAnUVeBE/edit#heading=h.pvyrqg4xft42) - Embeeded questions from OS to communication protocols. - [What are some more obscure interview questions for embedded positions?](https://www.reddit.com/r/embedded/comments/bqoqpr/what_are_some_more_obscure_interview_questions/) - r/embedded thread with lots of interesting interview questions. ## Others ## - [Soldering is easy](http://mightyohm.com/files/soldercomic/FullSolderComic_EN.pdf) - Soldering comic guide that teaches everything you need to know to become a master of soldering. - [Fritzing](http://fritzing.org/home/) - Open source hardware that includes schematic capture and breadboard layout applications. - [XOD Visual Programming Arduino](https://www.youtube.com/watch?v=qxjLH_3US04&feature=youtu.be) - Program Arduino in a very particular way through visual blocks. - [Electronics Weekly](https://www.electronicsweekly.com/) - Electronics Weekly is a good resource for those looking for industry-related news. There are topics in business, design, products, and so much more which are all directly related to electrical engineering. You can also use it to view available jobs or post jobs yourself. ## Contribute ## Contributions welcome! Read the [contribution guidelines](CONTRIBUTING.md) first.
{ "repo_name": "SergioGasquez/awesome-electronic-engineering", "stars": "78", "repo_language": "None", "file_name": "linkchecker.yml", "mime_type": "text/plain" }
name: CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] workflow_dispatch: schedule: - cron: "0 9 * * *" jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: gaurav-nelson/github-action-markdown-link-check@v1
{ "repo_name": "SergioGasquez/awesome-electronic-engineering", "stars": "78", "repo_language": "None", "file_name": "linkchecker.yml", "mime_type": "text/plain" }
#include <ESP8266WiFi.h> #define Selector_0 16 #define Selector_1 5 #define Selector_2 4 #define Enable_0 14 #define Enable_1 12 #define pot_limit 315 #define timeout 10 IPAddress serverIP(192, 168, 4, 1); //for ledcWrite //RANGE OF JX 2060 IS 1800 TO 7800 //RANGE OF MG90S IS 1750 TO 7550 //for adafruit PWM //RANGE OF MG90S IS 100 TO 500 //RANGE OF JX60 IS 110 TO 460 uint16_t pot_array[8]; void select_channel(int); WiFiClient client; void setup() { pinMode(Selector_0, OUTPUT); pinMode(Selector_1, OUTPUT); pinMode(Selector_2, OUTPUT); pinMode(Enable_0, OUTPUT); pinMode(Enable_1, OUTPUT); Serial.begin(115200); client.setNoDelay(1); const char *ssid = "espServer"; const char *password = "11111111"; WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("\nConnecting to "); Serial.println(ssid); while ( WiFi.status() != WL_CONNECTED) { delay(500); Serial.println(WiFi.status()); } Serial.println("WIFI connected"); Serial.println(WiFi.localIP()); // get interface IP address mask Serial.println(client.connect(serverIP, 5000)); } void loop() { if (client.connected()) { Serial.println("Connection success!"); } else { Serial.println("oops"); client.connect(serverIP, 5000); delay(50); } for (;;) { for (int channel = 0; channel < 8; channel++) { select_channel(channel); pot_array[channel] = analogRead(0); if (pot_array[channel] < pot_limit) { pot_array[channel] = pot_limit; } yield(); } client.write_P((const char*)pot_array, sizeof(pot_array)); delay(timeout); if(!client.connected()) { Serial.println("connection reset"); client.connect(serverIP, 5000); break; } // yield(); } } void select_channel(int channel_num) { if (channel_num < 8) { digitalWrite(Enable_0, 0); digitalWrite(Enable_1, 1); } else { digitalWrite(Enable_0, 1); digitalWrite(Enable_1, 0); } switch (channel_num) { case 0: digitalWrite(Selector_0, 0); digitalWrite(Selector_1, 0); digitalWrite(Selector_2, 0); break; case 1: digitalWrite(Selector_0, 1); digitalWrite(Selector_1, 0); digitalWrite(Selector_2, 0); break; case 2: digitalWrite(Selector_0, 0); digitalWrite(Selector_1, 1); digitalWrite(Selector_2, 0); break; case 3: digitalWrite(Selector_0, 1); digitalWrite(Selector_1, 1); digitalWrite(Selector_2, 0); break; case 4: digitalWrite(Selector_0, 0); digitalWrite(Selector_1, 0); digitalWrite(Selector_2, 1); break; case 5: digitalWrite(Selector_0, 1); digitalWrite(Selector_1, 0); digitalWrite(Selector_2, 1); break; case 6: digitalWrite(Selector_0, 0); digitalWrite(Selector_1, 1); digitalWrite(Selector_2, 1); break; case 7: digitalWrite(Selector_0, 1); digitalWrite(Selector_1, 1); digitalWrite(Selector_2, 1); break; } }
{ "repo_name": "youmebangbang/esp8266-wifi-direct-examples", "stars": "27", "repo_language": "C++", "file_name": "esp8266_motion_server.ino", "mime_type": "text/x-c" }
# esp8266-wifi-direct-examples for Arduino IDE Server and client example to wifi control a Adafruit PCA9685 servo controller This will allow you to take advantage of the esp8266's WIFI direct feature, aka p2p feature. A client esp8266 connects to a server esp8266 with no access point inbetween, and establishes a TCP socket connection. Analog data is read from potentiometers wired to a 4051 multiplexer to the esp's single analog input. Data is sent as a casted array to the server. The speed is very fast, possibly up to HD video quality streaming. IMPORTANT NOTES: There is little information on the internet about how to p2p the esp8266. The majority of the issue is because the wifi mode on the client must be set to Wifi_STA and the server must be set to Wifi_AP. If Wifi_AP_STA or Wifi_STA is used for the server, the client will connect and send some little data, and then quickly disconnect. client.setNoDelay(1) must be used or transmission will be slow due to the Nagle algorithm. Any calls to server.available() will disconnect the current client. For multiple clients a array and queue can be used to keep previous connections alive (google examples).
{ "repo_name": "youmebangbang/esp8266-wifi-direct-examples", "stars": "27", "repo_language": "C++", "file_name": "esp8266_motion_server.ino", "mime_type": "text/x-c" }
#include <ESP8266WiFi.h> #include <Wire.h> #include <Adafruit_PWMServoDriver.h> #define LOWFREQ 110 #define HIFREQ 460 //for ledcWrite //RANGE OF JX 2060 IS 1800 TO 7800 //RANGE OF MG90S IS 1750 TO 7550 //for adafruit PWM //RANGE OF MG90S IS 100 TO 500 //RANGE OF JX60 IS 110 TO 460 const char* ssid = "espServer"; const char* password = "11111111"; uint8_t readin[16]; uint16_t pot_array[8]; Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x40); uint8_t servonum = 0; // -1 correction int middle; WiFiServer server(5000); WiFiClient client; void setup() { Serial.begin(115200); Wire.begin(5,4); delay(10); WiFi.mode(WIFI_AP); WiFi.softAP(ssid, password); server.begin(); server.setNoDelay(1); IPAddress ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server Serial.print("Server IP is: "); // Print the IP to the monitor window Serial.println(ServerIP); middle = LOWFREQ + ((HIFREQ - LOWFREQ) / 2); pwm.begin(); pwm.setPWMFreq(50); } void loop() { // Check if a client has connected if (!client.connected()) { //Serial.println("no client yet"); client = server.available(); return; } Serial.println("GOT CLIENT!!!!!!!"); client.setNoDelay(1); for (;;) { while (client.available()) { client.read((uint8_t*)pot_array, sizeof(pot_array)); for(int x = 0; x < 8; x++) { pot_array[x] = map(pot_array[x], 315, 1024, LOWFREQ, HIFREQ); //10bit mapping Serial.print(pot_array[x]); Serial.print(','); pwm.setPWM(x, 0, pot_array[x]); } Serial.println(" "); yield(); } if (!client.connected()) { Serial.println("client disconnected"); //close client and reconnect client.flush(); client.stop(); break; } } }
{ "repo_name": "youmebangbang/esp8266-wifi-direct-examples", "stars": "27", "repo_language": "C++", "file_name": "esp8266_motion_server.ino", "mime_type": "text/x-c" }
--[[ Linear Phase 15-Bands Equalizer Key: - toggle equalizer control: ctrl+e - prev/next gain control: UP / DOWN - decrease/increase gain: LEFT / RIGHT - copy gain value from prev gain control: [ - copy gain value from next gain control: ] Note that ~~/lua-settings directory should exist to save gain values. --]] local options = require "mp.options" local msg = require "mp.msg" local key_toggle_control = "ctrl+e" local key_prev_entry = "UP" local key_next_entry = "DOWN" local key_decrease = "LEFT" local key_increase = "RIGHT" local key_copy_prev = "[" local key_copy_next = "]" local control_enabled = false local num_entry = 15 local selected_entry = 0 local min_val = -360 local max_val = 120 local stale_gain_entry = "" local function eq(x) return "eq" .. x end local gain_table = { eq0 = 0, eq1 = 0, eq2 = 0, eq3 = 0, eq4 = 0, eq5 = 0, eq6 = 0, eq7 = 0, eq8 = 0, eq9 = 0, eq10 = 0, eq11 = 0, eq12 = 0, eq13 = 0, eq14 = 0 } local freq_label = { eq0 = "# 0 Hz:", eq1 = "# 65 Hz:", eq2 = "# 157 Hz:", eq3 = "# 288 Hz:", eq4 = "# 472 Hz:", eq5 = "# 733 Hz:", eq6 = "# 1k1 Hz:", eq7 = "# 1k6 Hz:", eq8 = "# 2k4 Hz:", eq9 = "# 3k4 Hz:", eq10 = "# 4k9 Hz:", eq11 = "# 7k0 Hz:", eq12 = "# 10k Hz:", eq13 = "# 14k Hz:", eq14 = "# 20k Hz:" } options.read_options(gain_table) for x = 0, num_entry-1 do gain_table[eq(x)] = math.min(math.max(gain_table[eq(x)], min_val), max_val) end local function save_gain_table() local settingdir = mp.find_config_file("lua-settings") local fp = settingdir and io.open(settingdir .. "/" .. mp.get_script_name() .. ".conf", "w") if fp == nil then msg.warn("Cannot save gain table.") else for x = 0, num_entry-1 do fp:write(eq(x) .. "=" .. gain_table[eq(x)] .. "\n") end fp:close() end end local normalcolor = "ffffff" local selectedcolor = "00ffff" local fontsize = 70 local fontfamily = "mono" local pdefault = "{\\fn" .. fontfamily .. "\\fscx" .. fontsize .. "\\fscy" .. fontsize .. "\\1c&" .. normalcolor .. "&}" local pselected = "{\\fn" .. fontfamily .. "\\fscx" .. fontsize .. "\\fscy" .. fontsize .. "\\1c&" .. selectedcolor .. "&}" local function gain_line(x) local val = gain_table[eq(x)] - min_val; local str = "" local x = 10 while x <= val do str = str .. "=" x = x + 20 end return str end local function show_osd_ass() local str = pdefault .. "Linear Phase 15-Bands Equalizer\n" for x = 0, num_entry-1 do local pval = pdefault if x == selected_entry then pval = pselected end str = str .. pval .. freq_label[eq(x)] .. string.format("%7.1f", gain_table[eq(x)]*0.1) .. " dB |" .. gain_line(x) .. "\n" end mp.set_osd_ass(0, 0, str) end local function hide_osd_ass() mp.set_osd_ass(0, 0, "{}") end local function gen_gain_entry() local str = string.format("entry(0,%.1f)", gain_table[eq(0)]*0.1) for x = 1, num_entry-1 do str = str .. string.format(";entry(%d,%.1f)", x, gain_table[eq(x)]*0.1) end return str end local function insert_filter(gain_entry) local graph = "firequalizer = " .. "wfunc = tukey:" .. "delay = 0.028:" .. "scale = linlog:" .. "zero_phase = on:" .. "gain_entry = '" .. gain_entry .. "':" .. "gain = 'cubic_interpolate(2.8853900817779269*log(f/157.48+1))'" mp.commandv("af", "add", "@" .. mp.get_script_name() .. ":lavfi=graph=[" .. graph .. "]") end local function audio_reconfig() local gain_entry = gen_gain_entry() if not (stale_gain_entry == gain_entry) then insert_filter(gain_entry) stale_gain_entry = gain_entry end end audio_reconfig() mp.register_event("playback-restart", audio_reconfig) local function send_command() mp.commandv("af-command", mp.get_script_name(), "gain_entry", gen_gain_entry()) end local function prev_entry() selected_entry = math.max(selected_entry-1, 0) show_osd_ass() end local function next_entry() selected_entry = math.min(selected_entry+1, num_entry-1) show_osd_ass() end local function decrease_gain() gain_table[eq(selected_entry)] = math.max(gain_table[eq(selected_entry)]-1, min_val) send_command() show_osd_ass() save_gain_table() end local function increase_gain() gain_table[eq(selected_entry)] = math.min(gain_table[eq(selected_entry)]+1, max_val) send_command() show_osd_ass() save_gain_table() end local function copy_prev() gain_table[eq(selected_entry)] = gain_table[eq(math.max(selected_entry-1, 0))] send_command() show_osd_ass() save_gain_table() end local function copy_next() gain_table[eq(selected_entry)] = gain_table[eq(math.min(selected_entry+1, num_entry-1))] send_command() show_osd_ass() save_gain_table() end local function binding_name(name) return mp.get_script_name() .. "-" .. name end local function toggle_control() control_enabled = not control_enabled if control_enabled then show_osd_ass() mp.add_forced_key_binding(key_prev_entry, binding_name("prev"), prev_entry, {repeatable=true}) mp.add_forced_key_binding(key_next_entry, binding_name("next"), next_entry, {repeatable=true}) mp.add_forced_key_binding(key_decrease, binding_name("decrease"), decrease_gain, {repeatable=true}) mp.add_forced_key_binding(key_increase, binding_name("increase"), increase_gain, {repeatable=true}) mp.add_forced_key_binding(key_copy_prev, binding_name("copy_prev"), copy_prev) mp.add_forced_key_binding(key_copy_next, binding_name("copy_next"), copy_next) else hide_osd_ass() mp.remove_key_binding(binding_name("prev")) mp.remove_key_binding(binding_name("next")) mp.remove_key_binding(binding_name("decrease")) mp.remove_key_binding(binding_name("increase")) mp.remove_key_binding(binding_name("copy_prev")) mp.remove_key_binding(binding_name("copy_next")) end end mp.add_forced_key_binding(key_toggle_control, binding_name("toggle_control"), toggle_control)
{ "repo_name": "mfcc64/mpv-scripts", "stars": "124", "repo_language": "Lua", "file_name": "Readme.md", "mime_type": "text/plain" }
-- various audio visualization local opts = { mode = "novideo", -- off disable visualization -- noalbumart enable visualization when no albumart and no video -- novideo enable visualization when no video -- force always enable visualization name = "showcqt", -- off -- showcqt -- avectorscope -- showspectrum -- showcqtbar -- showwaves quality = "medium", -- verylow -- low -- medium -- high -- veryhigh height = 6, -- [4 .. 12] forcewindow = true, -- true (yes) always run visualizer regardless of force-window settings -- false (no) does not run visualizer when force-window is no } -- key bindings -- cycle visualizer local cycle_key = "c" if not (mp.get_property("options/lavfi-complex", "") == "") then return end local visualizer_name_list = { "off", "showcqt", "avectorscope", "showspectrum", "showcqtbar", "showwaves", } local axis_0 = "image/png;base64," .. "iVBORw0KGgoAAAANSUhEUgAAB4AAAAAgCAQAAABZEK0tAAAACXBIWXMAAA7EAAAOxAGVKw4bAAASO0lEQVR42u2de2wU1xXGV/IfSJEqVUJCQrIUISFFiiqhSFWkKFKFokpB1TqxHROT8ApueDgEE9u4MW4TSqFA" .. "3TSUQmkSChRwII6BkAQCDSYlBtc1hiSA4/CyMcYGtsZvY3t3vXu719vVPjxzz71zd+wBvnOkdvHZ78w5v7mZmbt7Z9blgsFgMBgMBoPBYDAYDAaDwWAwGAwGg8FgMBgMBoPBYDAYDAaDwWCw+9HYBFbKboe8lE1A" .. "HHHEEUccccQRRxxxxBFHHPEHNe4KBSJWijjiiCOOOOKII4444ogjjjjiD1icwWAwGAwGg8FgMBgM9hAYJsAwGAwGg8FgMBgMBnsozOVyR7zuQOSPdQeif0UcccQRRxxxxBFHHHHEEUcc8QciHn05KaPuwGDHYEfd" .. "gUkZRgkQRxxxxBFHHHHEEUccccQRR/w+jhu9FQ6Hw+FwOBwOh8Ph8AfOx3Zz07LTXpmYzl89McuJOJ6e/czcCWkP7u4Gf/AHf/AHf/AHf/AHf/AHf/B/iPm73D99qaW2u7n7RqI/8lz4LWbxw1tVNjQh7dgH/Z6R" .. "JdjBzmuXKxl7b42sdvqctrORCjqvTc1S3elx9V9vOXNy1+gcP3r+5K6Bu7y8YW/jqZO7PPU5S+Tyx/Fp9lysO/CLV1TqA3/wB3/wB3/wB3/wB3/wB3/wB/8x4e9yL37N+PlYP3o+/BazePVe+c089XL7D4n6qjJZ" .. "dUlhrO7TLWo7wKj+gbvxkGbMv3sl8T3Ht8vlL8hLVPr6dq7Xqw/8wR/8wR/8wR/8wR/8wR/8wR/8k86f/89bK26eYazjSsXGsJ8ui90Bo+MVG7ua1HZAY1VoZj9Utacof8b8DSU15cGAmn5tcfnG/zaE2+tqUtsB" .. "8fXv33T6w8EOxpprYt9xs46xgK9qT0Hes/M2rbr13cgA2SOfP+hnrLacZ68t72sNiYNvrbBWH/iDP/iDP/iDP/iDP/iDP/iDP/jbxD/8f3UVjF2v5q8ef9HlXpQbyjAcuxY7Gp8y8uV1878ZO7lLtsDNv+Ul/e5X" .. "0b9cqlT9JGFypq+XscZTHM3bRaq7IFo/9z+/zZivPxrdsY7Xt35l5N8paV3XGavcLp8/4GMs0t+UrFvf8mESWcKgVh/4gz/4gz/4gz/4gz/4gz/4gz/428Q/vsC1xQFf9b5JGXcvf3/UqIE1bw57az5yuff/uadl" .. "eZ5sefzzh8ZTsX+ZPmfvO5MzVRCWv8tXhz8xi6O5+pXeDqjaw1hvazTaFNqtjV/Hvn/Xho4ruUut7QCXO/vV4DBja95Ur0+Ff+Fy8Ad/8Ad/8Ad/8Ad/8Ad/8Ad/8FfgHy2wt7Wugs+d284aNxCJ36xTbb+7mbGj" .. "76uq4p2vYb9U6XIf3sq/LH/qZfUdwOuvq/juM89F/nnD3ndi6gvt1C+06ovfAaGMN9Q6Bn/wB3/wB3/wB3/wB3/wB3/wB3/b+UcLjFjbOeMGRPFHnpu7yBzKPQ9jkduSH39xweKcJTlLFiz+Sbas3uVe9jrf8soC" .. "rh8eZOzETpXtx9cfvgm7IOb76/6Y+sw8Je3Jl+R3AF/TfrpMXq/LX5yf5k/VR/FX6c8K/4npOUvi61XjT+l1+Yvz0/yp+ij+Kv1Z4f/oC4tyfz7POn9Kr8tfnJ/mT9VH8Vfpz9rxR+0EMPr4Q5+g9I4/Ipc5/oid" .. "Pv7I9wf+9yf/1MxXc/kCQav8Rfpk8DfPL8dfVJ8Mf9n+MP7vv/HPr29/Nts6f0qfjOt/8/xy1/+i+mSu/2X7szb+017JWWK+qJYe/2K9/vgX5ZcZ/+L66PEv35/Djj/RAgfaG6u6Gs0/gTCPry4aaOdtNf/70ReM" .. "NtJ/i7GyUv6qII/ffv1/Cxbly+ld7otH+Kr469Xcvd2M9d+OXSFP60fqv8vVzdWe+oCXsYA3+hV5/23GPvyjGaKfZB/a0nTK211/VH4H3DkfGiQ75PU6/On8Yv4y9Yn4S/dnkX9KWs1HXMEXUZj9epmIv4xehz+d" .. "X8xfpj4Rf+n+LPJPzfz+GOfLWOfVuYvU+cvodfjT+cX8ZeoT8ZfuzyL/sJcU+geHB+ctVucvo9c7/lP5qeM/XZ/4+C/Zn0X+0+cEfGEf9n77qTp/Gb0Ofzq/mL9MfSL+0v1pjP8JabUf8wsvFvzkL1bGP6XXHf/i" .. "/PT4p+qjxr9Ufxb5tzdE9i/3jBxV/jJ6Hf50fjF/mfpE/KX7szz+95R6e3jBd86b/cCLePzTer3xT+Wnxj9dn3j8S/Znmf9rr/e08Pz9HmvnX1qvx5/KT/Gn6xPzl+xP6/pHbQI8+vpHYgLM12i/t4axugMu94aS" .. "tm8W5cY3wON/X8fYuYOJF6D3PN7ek7svf8VYTbnRRtrOMla1m796Zm74t564+e+FPwWg9VOz/AOJj7revEp++4lr0J98qb2BsfYfIv/mzzerrTBDdO4gX/3OmPwEeELaUGeowt/K63X40/nF/Gm9mL9Kf1b4f7mN" .. "sdvnj29vrmbBq1+r85fR6/Cn84v503oxf5X+rPCv2MhYS+2xbRePDA92XlPnL6PX4U/nF/On9WL+Kv1Z4R8m2nmNb9Xst/FE/GX0Ovzp/GL+tF7MX6U/K/yfmcsfqXG58nLlD8e3rlbnL6PX4U/nF/On9WL+Kv1Z" .. "G/+pmfwpop3Xaj769tDqIvXxT+v1xj+Vnxr/lJ4a//L9WeHf3jDQwffu5cq+NsaM17mI+MvodfjT+cX8ab2Yv0p/Vvgvez043Nd6uqzhy4DPU69+/JHR6/Cn84v503oxf5X+rPBPSeu+4R+s3ne6zD8w0G5856yI" .. "v4xehz+dX8yf1ov5q/Rn9fpHbQI8+vpHegLscucuTQnN7fnTvmK/5o7G85alpI2+AA3jaP5PwBt9eHfUa/kK8JsRNFOypmbxXRJ5DDetP7QltLsG+ArysPe2hi45z8hvP3EHuNzb1jLm7Y386/SHoX/1zJgfjU9M" .. "L3931sLI7nq7aGK6ygT4c75O3v/MXHm9Dn86v5g/rRfzV+tPnX/bue7m8OdNjaeGBxO/+aH5y+h1+NP5xfxpvZi/Wn/q/KdmrS0Ovzr/GWPGP4Mu4i+j1+FP5xfzp/Vi/mr9qfPnzu+84ZdXchPgeP4yeh3+dH4x" .. "f1ov5q/Wnzp/PsGjfjJCxF9Gr8Ofzi/mT+vF/NX6szL++c+CfHPI+MgmM/5pvd74p/JT45/SU+NfpT91/sX5kUl1b2t3szp/Gb0Ofzq/mD+tF/NX60+d/4kdjIUnQ98eYsx4kbuIv4xehz+dX8yf1ov5q/Wnzn/m" .. "Lxk7/eFIH+WM7Vinyl9Gr8Ofzi/mT+vF/NX6s3b9ozYBHn39Q0yAfzabPxb79vmi/Ih7vo89QEfjK94YfaftuU+CgfC0k4My+hJ8xnz/YGjG31BakprJPzFYnsefJRbJT+mfnce/+G89G/ls7cmX6vYzFgwW54eH" .. "Ar39+P7eWlGx0VPPF0xE4o/N7LvFv9bfUxr+z6cg785Fxm7GXWKJJnjTsgN+xg5uKsovzt/2+4tHWHD0CnSRXo8/nT+Rf96yWP6UnuKv2p8q/6deDt/dMTG9+8Y9jyz/aHe0Xo8/nV/Mn9JT/FX7szb+p8/ZvGqw" .. "o7NRnT+tT8b4F+WXGf/mernxL9+fOv+nZ/v6Oq9+9Q+zCR7Fn9Lr8qfyU/zFepq/Wn+q/PkEr/1Sc03LmSPvGU8yxPxpvR5/Or+YP6Wn+Kv2p8p/UoZ/sKvx6dkbSqbPkT//RunRej3+dH4xf0pP8Vftz9rxn196" .. "m91XJ3P8F+mTcfwX5Zc5/pvr5Y7/8v2p8t+6mrHPt05Ie2LWnfP3/qvOn9br8afzi/lTeoq/an+q/GctDH8r63Lvfcf4m0oxf1qvx5/OL+ZP6Sn+qv1ZPf6Yu9zxx3QCnLuUPzR6tEVShOLRdeMsGEicmTediszl" .. "d65nrLTEaDOfbuFFcbm3h/9oMbfIwUKsX1v8f2XI+CdtM+aH73fkFl7wTG0/vv6IBXwlhdH3FC739ob/7usN5w8Gd/9BboI4a+Fofo1f/zhddoKqy5+egIr5i/WJ/J+dF+Vf+7Fkf0ngPymj5Qxjxz6Q4990amJ6" .. "4mWKmT45/M3zy/E308vyF/anzX/Lav63oU6jB03I8Bfpk8FflF+Gv7lejj/Rnyb/H44Hg0X5lduNJ3g0f7Fen784P81fpJfhT/anxf+JWSMLxgYHOxJ/rEGOP6XX5U/lp/iL9TR/if60+OcuDV0sXeCXcEG/0ZM9" .. "Kf6UXpc/lZ/iL9bT/CX6S8L51+Wu/djq8UesT8751zy/3PnXTC97/hX2p8mf32Tm7Q0O+/tXvGGFv1ivz1+cn+Yv0svwJ/vT4p+S1tfq69+/6eRufpc9fxKyGn9Kr8ufyk/xF+tp/hL9JeX4Y+ayxx/TCfC07PAt" .. "zGY7ID7e70m8zb/pdOwE9I+/Nt5QacmdC1EQnVc/+lOkRLF+1kK+tG3k8rKLD+/JmXevhHfJ8ODx7TLbT+wvGLznaTr12uuJlxEXDocfZcOt7WxkWSM9wZuW3R3NH/T3tzfsKVWZoOryl5kAi/iL9Yn8J2Uk8lft" .. "zwr/adn8AfDG9wmM5l9WOvo9Ir0+f1F+Gf7mejn+Kv1Z4f/YzENbQtOMQHP16AOLDH+xXp+/KL8Mf3O9HH+V/lT5/6aQBS8cdrnNJngUf1qvx5/KT/EX62n+qv2pj/+y0tKSiekpafVfMBb74C7Z8U/pdce/OD89" .. "/kV6mfGv1p8q/02r+F+aq/f+6e6lYDD26aFy/Gm9Hn8qP8VfrKf5q/Zn7fqHP6rGeIGvzPFfrE/G9Y95frnrHzO97PWPfH+q/FMz275hbLAj4AsGyt9V50/r9fhT+Sn+Yj3NX7U/9fFflD/QMfLX0DVWzT718U/p" .. "dce/OD89/kV6mfGv1p/V44+Zyx5/TCfAuv7NoeBw+AHYfAnygsXm73xs5sqCzauK8uO/xpfX626f8tTMksLNqwryjB6QT00wKdfVJyO/MX/n9GfGf/ZCftdBVZnVvLr6ZOU34++U/kTjn/snf9F7Wp+uXje/aPw7" .. "oT9j/vyjjb62riZ+kmk7a/yMA5Hr6pOX35i/c/qjxn9BHmOf/dV6fl29bn5q/I93f8b8V7zBHzLHX5UUMnZyl2pWXX3y8hvzd05/ovFflK93htHVJyO/aPw7oT9j/l+8z9i2tSlpU7MaqwL+KVmqWXX1yctvzN85" .. "/ZmP/ylZ61fmLj25m2/JSmZdfXLym49/Z/RHnX9tcf0U+zcxtvEt/up6dcCnfgEy3no5fxAmwPdnf+uKfb1BP/9s76mX/75u7PVOr8/u/qK+Yx1j5p/x2q93en329Hf5q86r3PlPvd08o35809U7vT67+5ucGbnX" .. "74M1jO3aMNZ6p9dnd39TsoaHum/wVzlLGPvXP8Za7/T67O4v7GcPitZ32K93en329dfwZdCfOvIAoyN/Y8xskbF9eqfXZ3d/EV/zZsDXdV30qDl79U6vz+7+bPJknAAG2oe6jm///hhjdfvvPz3lxfkXDtcfZay7" .. "pf5obYX02vKk6Z1en739PTuP37PQ1VR/tP6o5yJjks92S5re6fXZ3Z/L3VzdXP351oObqvcNdfv6jX/mwU690+uzu7+wn9jZfinysInx0Du9Pvv662rsaancvn9TzT5vz1D3tOyx1ju9Prv7c7n5mb3hn59u6bjC" .. "TJcY26l3en1298f9nqf7+njqnV6fff2Vv8t/4urEzu8+8/V7e1Izx1rv9Prs7u/xF2srTuy4+q9gYKizcPnY651en9392ezJSLJ+5VAXX4DdenZq1v2oF3vl9uhN1v7+2Id1j43e6fXZ29/shfF3RryQM7Z6p9dn" .. "d38ud/W+yL0Zva3rV4693un12d0f9x+n8x+zZ+yeZ1LGeOidXp+d/ZVv9PaE9293i9kdtnbqnV6f3f3x59u3/Cf84JQv3h8PvdPrs7s/l/uR5/pu6Sxu19U7vT57+6v9OHyG6WuL/tTLWOqdXp+9/WXk8AfMMea5" .. "+ItXxkPv9Prs7s9mT9YpIHepTvvjrYfD4Waempm7tDj/+QVWl7fo6p1en939wcfXH3luweKifLMfmbFf7/T67O6Pe/ary/MefWH89E6vz+7+4OPpU7Pyls38pfXzi67e6fXZ29/kzOV5OrMLXb3T67O7P1sdBxc4" .. "HA6Hw+FwOBwOhz8UDgRwOBwOh8PhcDgcDn8oHAjgcDgcDofD4XA4HP4w+P8AQEuXMXpD8/kAAAAASUVORK5CYII=" local axis_1 = "image/png;base64," .. "iVBORw0KGgoAAAANSUhEUgAAB4AAAAAwCAQAAABaxq+2AAAACXBIWXMAAA7EAAAOxAGVKw4bAAATVklEQVR42u2df0xUZ7rHJ+EPkiabbGJiYkLSmJg0aTYxTTZNmiYb09ykZjO0QLHY+quy9Qe1YgG5Re62rlev" .. "etluXVevt62rrkq1FLG21epW7FqUZRFtq1LqLxAR1FnkNwIzw8x752V27gzDOe/zvuedA0f5fp9kd+SZ7zPv8zlvz5x35pwzLhcEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAE" .. "QRAEQRAEQRAEQRAEQRAEQRAEQRBkq1gyK2F3Q1HCkpFHHnnkkUceeeSRRx555JFH/lHNu0KJiEqQRx555JFHHnnkkUceeeSRR/4RyzMIgiAIgiAIgiAImgTCAhiCIAiCIAiCIAiaFHK53JGoq4j8sa4i+lfkkUce" .. "eeSRRx555JFHHnnkkX8k8tGHU9PrKgY7BjvqKqamGxVAHnnkkUceeeSRRx555JFHHvmHOG/0VAQCgUAgEAgEAoFAIB65AAIEAoFAIBAIBAKBQEyKAAIEAoFAIBAIBAKBQEyKGN+Xm5mV+tqUNP7oqblOxPHsvOcW" .. "JKc+upsb/MEf/MEf/MEf/MEf/MEf/MF/EvN3uX/5Skttd3P3rfh47IXwU8zyR3eovFBy6omP+j0jN+EKdt64WsnYB+tlvbPmt52PjKDzxoxM1Y0+avw3W86d3ju2xs9ePL134D4f3rC38czpvZ767OVy9UfxafZc" .. "rqv49Wsq4wN/8Ad/8Ad/8Ad/8Ad/8Ad/8Af/ceHvci97w/gXkn72YvgpZvnqA/Iv88yr7T/F+6tKZd3FBbG+z7erbQCj8Q/cHw1p9qL71+Kfc3KXXP383Hinr2/PJr3xgT/4gz/4gz/4gz/4gz/4gz/4g3/C+fP/" .. "eWf17XOMdVwr3xKOs6WxG2BsvnxLV5PaBmisCq3sh6r2F+bNXrS5uKYsGFDzbygq2/LPhnB7XU1qG2D0+A9tPfvxYAdjzTWxz7hdx1jAV7U/P/f5hVvX3vlhZILsl68f9DNWW8ar15b1tYbMwXdWWxsf+IM/+IM/" .. "+IM/+IM/+IM/+IM/+NvEP/x/deWM3azmj5582eVemhOqMBx7LnY0P33ky+vmvzN2eq/sALf9jg/pP/89+pcrlaqfJEzL8PUy1niGo3m3UHUTRMfP44/vMubrj2Z3b+Tj27Qm8u+k1K6bjFXukq8f8DEW6W965p3v" .. "+TSJnMKgNj7wB3/wB3/wB3/wB3/wB3/wB3/wt4n/6AFuKAr4qg9OTb9/9cfjRg2sf3vYW/OJy33ojz0tq3Jlh8c/f2g8E/uXWfMPvDctQwVh2fv87PCn5nI017/R2wBV+xnrbY1mm0KbtfHb2Ofv3dxxLWeFtQ3g" .. "cme9HhxmbP3b6uNT4V+wCvzBH/zBH/zBH/zBH/zBH/zBH/wV+EcH2NtaV87Xzm3njRuI5G/Xqbbf3czY8Q9VXaODn8N+pdLlPrqDf1n+zKvqG4CPv678hy88l/nnDQfeixlfaKN+pTW+0RsgVPGWWsfgD/7gD/7g" .. "D/7gD/7gD/7gD/7gbzv/6AAjartg3IAo/9gLC5aaQ3ngYSxyWfKTLy9elr08e/niZb/IkvW73Cvf5K+8Jp/7hwcZO7VH5fVHjz98EXZ+zPfX/THjM4uk1Kdfkd8A/Jz2s6Xyfl3+4vo0f2p8FH+V/qzwn5KWvXz0" .. "eNX4U35d/uL6NH9qfBR/lf6s8H/8paU5/7bQOn/Kr8tfXJ/mT42P4q/Sn7X9j9obwNj9D/0Gpbf/EYXM/kcc9P5Hvj/wfzj5p2S8nsNPELTKX+RPBH/z+nL8ReOT4S/bH+b/wzf/+fHtr+ZZ50/5E3H8b15f7vhf" .. "ND6Z43/Z/qzN/9TXspebn1RLz3+xX3/+i+rLzH/x+Oj5L9+fw/Y/0QEOtDdWdTWafwJhnl9XONDO22r+++MvGb1I/x3GSkv4o/xcfvn1vxQszJPzu9yXj/Gz4m9W8/B2M9Z/N/YMedo/Mv773N1c7akPeBkLeKNf" .. "kfffZezj35sh+kXWke1NZ7zd9cflN8C9i6FJslver8Ofri/mLzM+EX/p/izyT0qt+YQ7+EkUZr9eJuIv49fhT9cX85cZn4i/dH8W+adk/HiC82Ws8/qCper8Zfw6/On6Yv4y4xPxl+7PIv9wFBf4B4cHFy5T5y/j" .. "19v/U/Wp/T89PvH+X7I/i/xnzQ/4wjHs/f5zdf4yfh3+dH0xf5nxifhL96cx/5NTaz/lB14s+NmfrMx/yq87/8X16flPjY+a/1L9WeTf3hDZvjzSs1X5y/h1+NP1xfxlxifiL92f5fm/v8Tbwwd876LZD7yI5z/t" .. "15v/VH1q/tPjE89/yf4s83/jzZ4WXr/fY+39l/br8afqU/zp8Yn5S/andfyjtgAee/wjsQDm52h/sJ6xugqXe3Nx23dLc0Y3wPN/3sjYhcPxB6APPN7e0/uufsNYTZnRi7SdZ6xqH3/03ILwbz1x+R+EPwWg/TMy" .. "/QPxt7retlb+9ePPQX/6lfYGxtp/ivyb39+sttwM0YXD/Ox3xuQXwMmpQ52hEf5O3q/Dn64v5k/7xfxV+rPC/+udjN29eHJXczULXv9Wnb+MX4c/XV/Mn/aL+av0Z4V/+RbGWmpP7Lx8bHiw84Y6fxm/Dn+6vpg/" .. "7RfzV+nPCv8w0c4b/FXNfhtPxF/Gr8Ofri/mT/vF/FX6s8L/uQX8lhpXK69W/nRyxzp1/jJ+Hf50fTF/2i/mr9KftfmfksHvItp5o+aT74+sK1Sf/7Rfb/5T9an5T/mp+S/fnxX+7Q0DHXzrXq3sa2PM+DwXEX8Z" .. "vw5/ur6YP+0X81fpzwr/lW8Gh/taz5Y2fB3weerV9z8yfh3+dH0xf9ov5q/SnxX+Sandt/yD1QfPlvoHBtqNr5wV8Zfx6/Cn64v5034xf5X+rB7/qC2Axx7/SC+AXe6cFUmhtT2/21fs19zRfO7KpNSxB6BhHM3/" .. "CHijN++ORi0/A/x2BM30zBmZfJNEbsNN+49sD22uAX4GeTh6W0OHnOfkXz9+A7jcOzcw5u2N/Ovsx6F/9cxeFM1PSSt7f+6SyOZ6t3BKmsoC+Et+nrz/uQXyfh3+dH0xf9ov5q/Wnzr/tgvdzeHPmxrPDA/Gf/ND" .. "85fx6/Cn64v5034xf7X+1PnPyNxQFH508QvGjH8GXcRfxq/Dn64v5k/7xfzV+lPnz4NfecMPr+QWwKP5y/h1+NP1xfxpv5i/Wn/q/PkCj/rJCBF/Gb8Of7q+mD/tF/NX68/K/Oc/C/LdEeM9m8z8p/1685+qT81/" .. "yk/Nf5X+1PkX5UUW1b2t3c3q/GX8Ovzp+mL+tF/MX60/df6ndjMWXgx9f4Qx45PcRfxl/Dr86fpi/rRfzF+tP3X+c37D2NmPR/ooY2z3RlX+Mn4d/nR9MX/aL+av1p+14x+1BfDY4x9iAfyrefy22HcvFuZFwvNj" .. "7A46ml/91tgrbS98FgyEl50clNGX4LMX+QdDK/6GkuKUDP6Jwapcfi+xSH3K//xC/sV/6/nIZ2tPv1J3iLFgsCgvPBXo1x/d3zury7d46vkJE5H8E3P67vCv9feXhP/zyc+9d5mx26MOsUQLvJlZAT9jh7cW5hXl" .. "7fyvy8dYcOwZ6CK/Hn+6fjz/3JWx/Ck/xV+1P1X+z7wavrpjSlr3rQceWf7R7mi/Hn+6vpg/5af4q/Znbf7Pmr9t7WBHZ6M6f9qfiPkvqi8z/839cvNfvj91/s/O8/V1Xv/mL2YLPIo/5dflT9Wn+Iv9NH+1/lT5" .. "8wVe+5XmmpZzxz4wXmSI+dN+Pf50fTF/yk/xV+1Plf/UdP9gV+Oz8zYXz5ov//4bpUf79fjT9cX8KT/FX7U/a/t/fuhtdl2dzP5f5E/E/l9UX2b/b+6X2//L96fKf8c6xr7ckZz61Nx7Fx/8U50/7dfjT9cX86f8" .. "FH/V/lT5z10S/lbW5T7wnvE3lWL+tF+PP11fzJ/yU/xV+7O6/zEPuf2P6QI4ZwW/afRYRUqE8tHzxlkwEL8ybzoTWcvv2cRYSbHRy3y+nQ+K2709/EeLuSI7C7F/Q9G/nCHxT9pmLwpf78gVPuGZev3R448o4Csu" .. "iD6nYJW3N/x3X2+4fjC477/lFohzl4zl1/jtz9NkF6i6/OkFqJi/2B/P//mFUf61n0r2lwD+U9NbzjF24iM5/k1npqTFH6aY+RPD37y+HH8zvyx/YX/a/Lev438b6jS60YQMf5E/EfxF9WX4m/vl+BP9afL/6WQw" .. "WJhXuct4gUfzF/v1+Yvr0/xFfhn+ZH9a/J+aO3LC2OBgR/yPNcjxp/y6/Kn6FH+xn+Yv0Z8W/5wVoYOlS/wQLug3urMnxZ/y6/Kn6lP8xX6av0R/CXj/dblrP7W6/xH7E/P+a15f7v3XzC/7/ivsT5M/v8jM2xsc" .. "9vevfssKf7Ffn7+4Ps1f5JfhT/anxT8pta/V139o6+l9/Cp7fidkNf6UX5c/VZ/iL/bT/CX6S8j+xyxk9z+mC+CZWeFLmM02wOh8vyf+Mv+ms7EL0N//h/ELlRTfuxQF0Xn9kz9Ehij2z13CT20bObzs4tN7Wsb9" .. "a+FNMjx4cpfM68f3Fww+8DSdeePN+MOIS0fDt7LhajsfOa2RXuDNzOqO1g/6+9sb9peoLFB1+cssgEX8xf54/lPT4/mr9meF/8wsfgN44+sExvIvLRn7HJFfn7+ovgx/c78cf5X+rPB/Ys6R7aFlRqC5euyORYa/" .. "2K/PX1Rfhr+5X46/Sn+q/H9bwIKXjrrcZgs8ij/t1+NP1af4i/00f9X+1Od/aUlJ8ZS0pNT6rxiLvXGX7Pyn/LrzX1yfnv8iv8z8V+tPlf/WtfwvzdUH/nD/SjAYe/dQOf60X48/VZ/iL/bT/FX7s3b8w29VY3yC" .. "r8z+X+xPxPGPeX254x8zv+zxj3x/qvxTMtq+Y2ywI+ALBsreV+dP+/X4U/Up/mI/zV+1P/X5X5g30DHy19AxVs1B9flP+XXnv7g+Pf9Ffpn5r9af1f2PWcjuf0wXwLrx3ZHgcPgG2PwU5MXLzJ/5xJw1+dvWFuaN" .. "/hpf3q/7+lSkZBQXbFubn2t0g3xqgUmFrj8R9Y35O6c/M/7zlvCrDqpKrdbV9Seqvhl/p/Qnmv88PvuT3t36dP269UXz3wn9GfPnH230tXU18TeZtvPG9zgQha4/cfWN+TunP2r+5+cy9sX/WK+v69etT83/ie7P" .. "mP/qt/hN5vij4gLGTu9VrarrT1x9Y/7O6U80/wvz9N5hdP2JqC+a/07oz5j/Vx8ytnNDUuqMzMaqgH96pmpVXX/i6hvzd05/5vN/euamNTkrTu/jr2Slsq4/MfXN578z+qPef20J/RKHtjK25R3+6GZ1wKd+ADLR" .. "frl4FBbAD2d/G4t8vUE//2zvmVf/vHH8/U4fn939RWP3RsbMP+O13+/08dnT39VvOq/z4D/1dvuc+v5N1+/08dnd37SMyLV+H61nbO/m8fY7fXx29zc9c3io+xZ/lL2csb/9Zbz9Th+f3f2F4/xh0fkd9vudPj77" .. "+mv4OuhPGbmB0bH/ZczsJGP7/E4fn939RWL92wFf103Rrebs9Tt9fHb3Z1Mk4g1goH2o6+SuH08wVnfo4fNTUZR36Wj9cca6W+qP15ZLn1ueML/Tx2dvf88v5NcsdDXVH68/7rnMmOS93RLmd/r47O7P5W6ubq7+" .. "csfhrdUHh7p9/cY/82Cn3+njs7u/cJza034lcrOJifA7fXz29dfV2NNSuevQ1pqD3p6h7plZ4+13+vjs7s/l5u/sDX/9fHvHNWZ6irGdfqePz+7+eDzwdN+cSL/Tx2dff2Xv85+4OrXnhy98/d6elIzx9jt9fHb3" .. "9+TLteWndl//WzAw1Fmwavz9Th+f3f3ZHIkosmnNUBc/Abv1/IzMh9Evjspd0Yus/f2xN+seH7/Tx2dvf/OWjL4y4qXs8fU7fXx29+dyVx+MXJvR27ppzfj7nT4+u/vj8fM0/mP2jD3wTE2fCL/Tx2dnf2VbvD3h" .. "7dvdYnaFrZ1+p4/P7v74/e1b/hG+ccpXH06E3+njs7s/l/uxF/ru6Jzcrut3+vjs7a/20/A7TF9b9KdextPv9PHZ2196Nr/BHGOey79+bSL8Th+f3f3ZHIl6C8hZodP+RPsRCIRZpGTkrCjKe3Gx1dNbdP1OH5/d" .. "/SEmNh57YfGywjyzH5mx3+/08dndH4+s11flPv7SxPmdPj67+0NMZMzIzF055zfW3190/U4fn739TctYlauzutD1O318dvdna2DngkAgEAgEAoFAIBCISRFAgEAgEAgEAoFAIBCISRHRh1PT6yqGOoc66yqMr6NC" .. "HnnkkUceeeSRRx555JFHHvmHOB99WFcRuZGO8b00kUceeeSRRx555JFHHnnkkUf+Ic4zCIIgCIIgCIIgCJoEwgIYgiAIgiAIgiAImhRyRcVK/v+vJS4DIY888sgjjzzyyCOPPPLII4/8o5B3seTQU+6EooQlI488" .. "8sgjjzzyyCOPPPLII4/8o5qHIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCEqf/A/SNfayCCBqGAAAAAElFTkSuQmCC" local options = require 'mp.options' local msg = require 'mp.msg' options.read_options(opts) opts.height = math.min(12, math.max(4, opts.height)) opts.height = math.floor(opts.height) if not opts.forcewindow and mp.get_property('force-window') == "no" then return end local function get_visualizer(name, quality, vtrack) local w, h, fps if quality == "verylow" then w = 640 fps = 30 elseif quality == "low" then w = 960 fps = 30 elseif quality == "medium" then w = 1280 fps = 60 elseif quality == "high" then w = 1920 fps = 60 elseif quality == "veryhigh" then w = 2560 fps = 60 else msg.log("error", "invalid quality") return "" end h = w * opts.height / 16 if name == "showcqt" then local count = math.ceil(w * 180 / 1920 / fps) return "[aid1] asplit [ao]," .. "afifo, aformat = channel_layouts = stereo," .. "firequalizer =" .. "gain = '1.4884e8 * f*f*f / (f*f + 424.36) / (f*f + 1.4884e8) / sqrt(f*f + 25122.25)':" .. "scale = linlin:" .. "wfunc = tukey:" .. "zero_phase = on:" .. "fft2 = on," .. "showcqt =" .. "fps =" .. fps .. ":" .. "size =" .. w .. "x" .. h .. ":" .. "count =" .. count .. ":" .. "csp = bt709:" .. "bar_g = 2:" .. "sono_g = 4:" .. "bar_v = 9:" .. "sono_v = 17:" .. "axisfile = data\\\\:'" .. axis_0 .. "':" .. "font = 'Nimbus Mono L,Courier New,mono|bold':" .. "fontcolor = 'st(0, (midi(f)-53.5)/12); st(1, 0.5 - 0.5 * cos(PI*ld(0))); r(1-ld(1)) + b(ld(1))':" .. "tc = 0.33:" .. "attack = 0.033:" .. "tlength = 'st(0,0.17); 384*tc / (384 / ld(0) + tc*f /(1-ld(0))) + 384*tc / (tc*f / ld(0) + 384 /(1-ld(0)))'," .. "format = yuv420p [vo]" elseif name == "avectorscope" then return "[aid1] asplit [ao]," .. "afifo," .. "aformat =" .. "sample_rates = 192000," .. "avectorscope =" .. "size =" .. w .. "x" .. h .. ":" .. "r =" .. fps .. "," .. "format = rgb0 [vo]" elseif name == "showspectrum" then return "[aid1] asplit [ao]," .. "afifo," .. "showspectrum =" .. "size =" .. w .. "x" .. h .. ":" .. "win_func = blackman [vo]" elseif name == "showcqtbar" then local axis_h = math.ceil(w * 12 / 1920) * 4 return "[aid1] asplit [ao]," .. "afifo, aformat = channel_layouts = stereo," .. "firequalizer =" .. "gain = '1.4884e8 * f*f*f / (f*f + 424.36) / (f*f + 1.4884e8) / sqrt(f*f + 25122.25)':" .. "scale = linlin:" .. "wfunc = tukey:" .. "zero_phase = on:" .. "fft2 = on," .. "showcqt =" .. "fps =" .. fps .. ":" .. "size =" .. w .. "x" .. (h + axis_h)/2 .. ":" .. "count = 1:" .. "csp = bt709:" .. "bar_g = 2:" .. "sono_g = 4:" .. "bar_v = 9:" .. "sono_v = 17:" .. "sono_h = 0:" .. "axisfile = data\\\\:'" .. axis_1 .. "':" .. "axis_h =" .. axis_h .. ":" .. "font = 'Nimbus Mono L,Courier New,mono|bold':" .. "fontcolor = 'st(0, (midi(f)-53.5)/12); st(1, 0.5 - 0.5 * cos(PI*ld(0))); r(1-ld(1)) + b(ld(1))':" .. "tc = 0.33:" .. "attack = 0.033:" .. "tlength = 'st(0,0.17); 384*tc / (384 / ld(0) + tc*f /(1-ld(0))) + 384*tc / (tc*f / ld(0) + 384 /(1-ld(0)))'," .. "format = yuv420p," .. "split [v0]," .. "crop =" .. "h =" .. (h - axis_h)/2 .. ":" .. "y = 0," .. "vflip [v1];" .. "[v0][v1] vstack [vo]" elseif name == "showwaves" then return "[aid1] asplit [ao]," .. "afifo," .. "showwaves =" .. "size =" .. w .. "x" .. h .. ":" .. "r =" .. fps .. ":" .. "mode = p2p," .. "format = rgb0 [vo]" elseif name == "off" then local hasvideo = false for id, track in ipairs(mp.get_property_native("track-list")) do if track.type == "video" then hasvideo = true break end end if hasvideo then return "[aid1] asetpts=PTS [ao]; [vid1] setpts=PTS [vo]" else return "[aid1] asetpts=PTS [ao];" .. "color =" .. "c = Black:" .. "s =" .. w .. "x" .. h .. "," .. "format = yuv420p [vo]" end end msg.log("error", "invalid visualizer name") return "" end local function select_visualizer(vtrack) if opts.mode == "off" then return "" elseif opts.mode == "force" then return get_visualizer(opts.name, opts.quality, vtrack) elseif opts.mode == "noalbumart" then if vtrack == nil then return get_visualizer(opts.name, opts.quality, vtrack) end return "" elseif opts.mode == "novideo" then if vtrack == nil or vtrack.albumart then return get_visualizer(opts.name, opts.quality, vtrack) end return "" end msg.log("error", "invalid mode") return "" end local function visualizer_hook() local count = mp.get_property_number("track-list/count", -1) if count <= 0 then return end local atrack = mp.get_property_native("current-tracks/audio") local vtrack = mp.get_property_native("current-tracks/video") --no tracks selected (yet) if atrack == nil and vtrack == nil then for id, track in ipairs(mp.get_property_native("track-list")) do if track.type == "video" and (vtrack == nil or vtrack.albumart == true) and mp.get_property("vid") ~= "no" then vtrack = track elseif track.type == "audio" then atrack = track end end end local lavfi = select_visualizer(vtrack) --prevent endless loop if lavfi ~= mp.get_property("options/lavfi-complex", "") then mp.set_property("options/lavfi-complex", lavfi) end end mp.add_hook("on_preloaded", 50, visualizer_hook) mp.observe_property("current-tracks/audio", "native", visualizer_hook) mp.observe_property("current-tracks/video", "native", visualizer_hook) local function cycle_visualizer() local i, index = 1 for i = 1, #visualizer_name_list do if (visualizer_name_list[i] == opts.name) then index = i + 1 if index > #visualizer_name_list then index = 1 end break end end opts.name = visualizer_name_list[index] visualizer_hook() end mp.add_key_binding(cycle_key, "cycle-visualizer", cycle_visualizer)
{ "repo_name": "mfcc64/mpv-scripts", "stars": "124", "repo_language": "Lua", "file_name": "Readme.md", "mime_type": "text/plain" }
## Various mpv lua scripts - visualizer.lua - various audio visualization. - firequalizer.lua - linear phase 15-bands equalizer. ## Key bindings Look at the lua scripts. ## Screenshoots ### visualizer.lua - showcqt ![showcqt](screenshoots/showcqt.jpg) - avectorscope ![avectorscope](screenshoots/avectorscope.jpg) - showspectrum ![showspectrum](screenshoots/showspectrum.jpg) - showcqtbar ![showcqtbar](screenshoots/showcqtbar.jpg) - showwaves ![showwaves](screenshoots/showwaves.jpg) ### firequalizer15.lua ![firequalizer15](screenshoots/firequalizer15.jpg) ## Related projects - [HTML5 ShowCQTBar](https://github.com/mfcc64/html5-showcqtbar) - showcqt/showcqtbar visualizer on an HTML5 page. - [YouTube Musical Spectrum](https://github.com/mfcc64/youtube-musical-spectrum) - showcqt visualizer as a Chrome extension.
{ "repo_name": "mfcc64/mpv-scripts", "stars": "124", "repo_language": "Lua", "file_name": "Readme.md", "mime_type": "text/plain" }
[nosetests] with-doctest = yes doctest-tests = yes doctest-extension = doctest doctest-fixtures = _fixture
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }
recursive-include src/markdoc/static/ * include distribute_setup.py include REQUIREMENTS global-exclude .DS_Store prune src/markdoc/static/default-static/media/sass/.sass-cache
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }
#!python """Bootstrap distribute installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from distribute_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import sys import time import fnmatch import tempfile import tarfile from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None try: import subprocess def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 except ImportError: # will be used for python 2.3 def _python_cmd(*args): args = (sys.executable,) + args # quoting arguments if windows if sys.platform == 'win32': def quote(arg): if ' ' in arg: return '"%s"' % arg return arg args = [quote(arg) for arg in args] return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 DEFAULT_VERSION = "0.6.10" DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" SETUPTOOLS_FAKED_VERSION = "0.6c11" SETUPTOOLS_PKG_INFO = """\ Metadata-Version: 1.0 Name: setuptools Version: %s Summary: xxxx Home-page: xxx Author: xxx Author-email: xxx License: xxx Description: xxx """ % SETUPTOOLS_FAKED_VERSION def _install(tarball): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Distribute') if not _python_cmd('setup.py', 'install'): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') finally: os.chdir(old_wd) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Distribute egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): if not no_fake: _fake_setuptools() raise ImportError except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("distribute>="+version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of distribute (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U distribute'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) finally: if not no_fake: _create_fake_setuptools_pkg_info(to_dir) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): """Download distribute from a specified location and return its filename `version` should be a valid distribute version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen tgz_name = "distribute-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: log.warn("Downloading %s", url) src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(saveto, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True def _same_content(path, content): return open(path).read() == content def _no_sandbox(function): def __no_sandbox(*args, **kw): try: from setuptools.sandbox import DirectorySandbox def violation(*args): pass DirectorySandbox._old = DirectorySandbox._violation DirectorySandbox._violation = violation patched = True except ImportError: patched = False try: return function(*args, **kw) finally: if patched: DirectorySandbox._violation = DirectorySandbox._old del DirectorySandbox._old return __no_sandbox @_no_sandbox def _rename_path(path): new_name = path + '.OLD.%s' % time.time() log.warn('Renaming %s into %s', path, new_name) os.rename(path, new_name) return new_name def _remove_flat_installation(placeholder): if not os.path.isdir(placeholder): log.warn('Unkown installation at %s', placeholder) return False found = False for file in os.listdir(placeholder): if fnmatch.fnmatch(file, 'setuptools*.egg-info'): found = True break if not found: log.warn('Could not locate setuptools*.egg-info') return log.warn('Removing elements out of the way...') pkg_info = os.path.join(placeholder, file) if os.path.isdir(pkg_info): patched = _patch_egg_dir(pkg_info) else: patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) if not patched: log.warn('%s already patched.', pkg_info) return False # now let's move the files out of the way for element in ('setuptools', 'pkg_resources.py', 'site.py'): element = os.path.join(placeholder, element) if os.path.exists(element): _rename_path(element) else: log.warn('Could not find the %s element of the ' 'Setuptools distribution', element) return True def _after_install(dist): log.warn('After install bootstrap.') placeholder = dist.get_command_obj('install').install_purelib _create_fake_setuptools_pkg_info(placeholder) @_no_sandbox def _create_fake_setuptools_pkg_info(placeholder): if not placeholder or not os.path.exists(placeholder): log.warn('Could not find the install location') return pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) setuptools_file = 'setuptools-%s-py%s.egg-info' % \ (SETUPTOOLS_FAKED_VERSION, pyver) pkg_info = os.path.join(placeholder, setuptools_file) if os.path.exists(pkg_info): log.warn('%s already exists', pkg_info) return log.warn('Creating %s', pkg_info) f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() pth_file = os.path.join(placeholder, 'setuptools.pth') log.warn('Creating %s', pth_file) f = open(pth_file, 'w') try: f.write(os.path.join(os.curdir, setuptools_file)) finally: f.close() def _patch_egg_dir(path): # let's check if it's already patched pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') if os.path.exists(pkg_info): if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): log.warn('%s already patched.', pkg_info) return False _rename_path(path) os.mkdir(path) os.mkdir(os.path.join(path, 'EGG-INFO')) pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() return True def _before_install(): log.warn('Before install bootstrap.') _fake_setuptools() def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] return location.startswith(top_dir) elif arg == option: if len(args) > index: top_dir = args[index+1] return location.startswith(top_dir) elif option == '--user' and USER_SITE is not None: return location.startswith(USER_SITE) return True def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', replacement=False)) except TypeError: # old distribute API setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) if setuptools_dist is None: log.warn('No setuptools distribution found') return # detecting if it was already faked setuptools_location = setuptools_dist.location log.warn('Setuptools installation detected at %s', setuptools_location) # if --root or --preix was provided, and if # setuptools is not located in them, we don't patch it if not _under_prefix(setuptools_location): log.warn('Not patching, --root or --prefix is installing Distribute' ' in another location') return # let's see if its an egg if not setuptools_location.endswith('.egg'): log.warn('Non-egg installation') res = _remove_flat_installation(setuptools_location) if not res: return else: log.warn('Egg installation') pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') if (os.path.exists(pkg_info) and _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): log.warn('Already patched.') return log.warn('Patching...') # let's create a fake egg replacing setuptools one res = _patch_egg_dir(setuptools_location) if not res: return log.warn('Patched done.') _relaunch() def _relaunch(): log.warn('Relaunching...') # we have to relaunch the process args = [sys.executable] + sys.argv sys.exit(subprocess.call(args)) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball) if __name__ == '__main__': main(sys.argv[1:])
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }
argparse CherryPy Jinja2 Markdown Pygments PyYAML webob
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }
# -*- coding: utf-8 -*- import os import os.path as p import re from distribute_setup import use_setuptools; use_setuptools() from setuptools import setup, find_packages rel_file = lambda *args: p.join(p.dirname(p.abspath(__file__)), *args) def read_from(filename): fp = open(filename) try: return fp.read() finally: fp.close() if not hasattr(p, 'relpath'): def relpath(path, start=p.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = p.abspath(start).split(p.sep) path_list = p.abspath(path).split(p.sep) # Work out how much of the filepath is shared by start and path. i = len(p.commonprefix([start_list, path_list])) rel_list = [p.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return p.curdir return p.join(*rel_list) p.relpath = relpath def get_version(): data = read_from(rel_file('src', 'markdoc', '__init__.py')) return re.search(r"__version__ = '([^']+)'", data).group(1) def get_requirements(): data = read_from(rel_file('REQUIREMENTS')) lines = map(lambda s: s.strip(), data.splitlines()) return filter(None, lines) def find_package_data(): files = [] src_root = p.join(p.dirname(__file__), 'src', 'markdoc') static_root = p.join(src_root, 'static') for dirpath, subdirs, filenames in os.walk(static_root): for filename in filenames: if not filename.startswith('.') or filename.startswith('_'): abs_path = p.join(dirpath, filename) files.append(p.relpath(abs_path, start=src_root)) return files setup( name = 'Markdoc', version = get_version(), author = "Zachary Voase", author_email = "[email protected]", url = 'http://github.com/zacharyvoase/markdoc', description = "A lightweight Markdown-based wiki build tool.", packages = find_packages(where='src'), package_dir = {'': 'src'}, package_data = {'markdoc': find_package_data()}, entry_points = {'console_scripts': ['markdoc = markdoc.cli.main:main']}, install_requires = get_requirements(), )
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }
# Markdoc Markdoc is a lightweight Markdown-based wiki system. It’s been designed to allow you to create and manage wikis as quickly and easily as possible. ## What is it good for? Potential use cases for Markdoc include, but aren’t limited to: * **Technical Documentation/Manuals** Markdoc can be used to write and render hand-written guides and manuals for software. Such documentation will normally be separate from automatically-generated API documentation, and might give a higher-level view than API docs alone. It might be used for client documentation for web/desktop applications, or even developer documentation for frameworks. * **Internal Project Wikis** Markdoc wikis consist of a single plain-text file per page. By combining a wiki with a DVCS (such as [Mercurial][] or [Git][]), you can collaborate with several other people. Use the DVCS to track, share and merge changes with one another, and view the wiki’s history. [Mercurial]: http://mercurial.selenic.com/ [Git]: http://git-scm.com/ * **Static Site Generation** Markdoc converts wikis into raw HTML files and media. This allows you to manage a blog, personal website or a collection of pages in a Markdoc wiki, perhaps with custom CSS styles, and publish the rendered HTML to a website. Markdoc need not be installed on the hosting site, since the resultant HTML is completely independent. ## Cool Features * Set up [Google Analytics][] tracking in one line of configuration. * [Barebones][] wikis that just look like directories with Markdown-formatted text files in them. * A built-in HTTP server and WSGI application to serve up a compiled wiki with a single command. * Continuous builds (via `rsync`) mean the server can keep running whilst Markdoc re-compiles the wiki. Just refresh your browser to see the changes. * Add [Pygments][]-powered syntax highlighting to your Markdoc wiki with a single [configuration parameter][syntax-highlighting]. * Markdoc is [public domain software][licensing]. It will always be completely free to use, and you can redistribute it (in part or in whole) under any circumstances (open-source, proprietary or otherwise) with no attribution or encumberances. [google analytics]: http://markdoc.org/ref/configuration#metadata [barebones]: http://markdoc.org/tips/barebones [pygments]: http://pygments.org/ [syntax-highlighting]: http://markdoc.org/tips/syntax-highlighting [licensing]: http://markdoc.org/about#license ## Quickstart ### Requirements The minimum requirements to run the Markdoc utility are: * Python 2.4 or later (2.5+ highly recommended) * A UNIX (or at least POSIX-compliant) operating system * [rsync](http://www.samba.org/rsync/) -- installed out of the box with most modern OSes, including Mac OS X and Ubuntu. In the future Markdoc may include a pure-Python implementation. ### Installation $ easy_install Markdoc # OR $ pip install Markdoc ### Making a Wiki markdoc init my-wiki cd my-wiki/ vim wiki/somefile.md # ... write some documentation ... markdoc build markdoc serve # .. open http://localhost:8008/ in a browser ... ## (Un)license This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/>
{ "repo_name": "zacharyvoase/markdoc", "stars": "347", "repo_language": "Python", "file_name": "apache.md", "mime_type": "text/plain" }